1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUSubtarget.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 19 #include "SIDefines.h" 20 #include "SIInstrInfo.h" 21 #include "SIMachineFunctionInfo.h" 22 #include "SIRegisterInfo.h" 23 #include "Utils/AMDGPUBaseInfo.h" 24 #include "llvm/ADT/APFloat.h" 25 #include "llvm/ADT/APInt.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/BitVector.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/ADT/Statistic.h" 30 #include "llvm/ADT/StringRef.h" 31 #include "llvm/ADT/StringSwitch.h" 32 #include "llvm/ADT/Twine.h" 33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 34 #include "llvm/CodeGen/Analysis.h" 35 #include "llvm/CodeGen/CallingConvLower.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/FunctionLoweringInfo.h" 38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 39 #include "llvm/CodeGen/ISDOpcodes.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunction.h" 43 #include "llvm/CodeGen/MachineInstr.h" 44 #include "llvm/CodeGen/MachineInstrBuilder.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfo.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/CodeGen/SelectionDAG.h" 51 #include "llvm/CodeGen/SelectionDAGNodes.h" 52 #include "llvm/CodeGen/TargetCallingConv.h" 53 #include "llvm/CodeGen/TargetRegisterInfo.h" 54 #include "llvm/CodeGen/ValueTypes.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DebugLoc.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/DiagnosticInfo.h" 60 #include "llvm/IR/Function.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/InstrTypes.h" 63 #include "llvm/IR/Instruction.h" 64 #include "llvm/IR/Instructions.h" 65 #include "llvm/IR/IntrinsicInst.h" 66 #include "llvm/IR/Type.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/ErrorHandling.h" 72 #include "llvm/Support/KnownBits.h" 73 #include "llvm/Support/MachineValueType.h" 74 #include "llvm/Support/MathExtras.h" 75 #include "llvm/Target/TargetOptions.h" 76 #include <cassert> 77 #include <cmath> 78 #include <cstdint> 79 #include <iterator> 80 #include <tuple> 81 #include <utility> 82 #include <vector> 83 84 using namespace llvm; 85 86 #define DEBUG_TYPE "si-lower" 87 88 STATISTIC(NumTailCalls, "Number of tail calls"); 89 90 static cl::opt<bool> DisableLoopAlignment( 91 "amdgpu-disable-loop-alignment", 92 cl::desc("Do not align and prefetch loops"), 93 cl::init(false)); 94 95 static cl::opt<bool> VGPRReserveforSGPRSpill( 96 "amdgpu-reserve-vgpr-for-sgpr-spill", 97 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 98 99 static cl::opt<bool> UseDivergentRegisterIndexing( 100 "amdgpu-use-divergent-register-indexing", 101 cl::Hidden, 102 cl::desc("Use indirect register addressing for divergent indexes"), 103 cl::init(false)); 104 105 static bool hasFP32Denormals(const MachineFunction &MF) { 106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 107 return Info->getMode().allFP32Denormals(); 108 } 109 110 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 111 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 112 return Info->getMode().allFP64FP16Denormals(); 113 } 114 115 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 116 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 117 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 118 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 119 return AMDGPU::SGPR0 + Reg; 120 } 121 } 122 llvm_unreachable("Cannot allocate sgpr"); 123 } 124 125 SITargetLowering::SITargetLowering(const TargetMachine &TM, 126 const GCNSubtarget &STI) 127 : AMDGPUTargetLowering(TM, STI), 128 Subtarget(&STI) { 129 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 130 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 131 132 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 134 135 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 136 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 138 139 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 140 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 141 142 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 144 145 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 146 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 147 148 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 149 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 150 151 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 155 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 156 157 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 159 160 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 161 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 162 163 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 164 addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass); 165 166 if (Subtarget->has16BitInsts()) { 167 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 168 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 169 170 // Unless there are also VOP3P operations, not operations are really legal. 171 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 172 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 173 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 174 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 175 } 176 177 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 178 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 179 180 computeRegisterProperties(Subtarget->getRegisterInfo()); 181 182 // The boolean content concept here is too inflexible. Compares only ever 183 // really produce a 1-bit result. Any copy/extend from these will turn into a 184 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 185 // it's what most targets use. 186 setBooleanContents(ZeroOrOneBooleanContent); 187 setBooleanVectorContents(ZeroOrOneBooleanContent); 188 189 // We need to custom lower vector stores from local memory 190 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 193 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 194 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 195 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 196 setOperationAction(ISD::LOAD, MVT::i1, Custom); 197 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 198 199 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 201 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 202 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 203 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 204 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 205 setOperationAction(ISD::STORE, MVT::i1, Custom); 206 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 207 208 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 209 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 210 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 212 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 213 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 214 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 215 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 216 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 217 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 218 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 219 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 220 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 221 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 222 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 223 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 224 225 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 226 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 227 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 228 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 229 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 230 231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 232 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 233 234 setOperationAction(ISD::SELECT, MVT::i1, Promote); 235 setOperationAction(ISD::SELECT, MVT::i64, Custom); 236 setOperationAction(ISD::SELECT, MVT::f64, Promote); 237 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 238 239 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 240 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 241 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 242 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 243 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 244 245 setOperationAction(ISD::SETCC, MVT::i1, Promote); 246 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 247 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 249 250 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 251 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 252 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 253 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 254 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 255 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 256 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 257 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 258 259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 260 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 262 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 267 268 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 269 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 270 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 271 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 272 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 273 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 274 275 setOperationAction(ISD::UADDO, MVT::i32, Legal); 276 setOperationAction(ISD::USUBO, MVT::i32, Legal); 277 278 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 279 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 280 281 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 282 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 283 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 284 285 #if 0 286 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 287 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 288 #endif 289 290 // We only support LOAD/STORE and vector manipulation ops for vectors 291 // with > 4 elements. 292 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 293 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 294 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 295 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 296 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 297 switch (Op) { 298 case ISD::LOAD: 299 case ISD::STORE: 300 case ISD::BUILD_VECTOR: 301 case ISD::BITCAST: 302 case ISD::EXTRACT_VECTOR_ELT: 303 case ISD::INSERT_VECTOR_ELT: 304 case ISD::INSERT_SUBVECTOR: 305 case ISD::EXTRACT_SUBVECTOR: 306 case ISD::SCALAR_TO_VECTOR: 307 break; 308 case ISD::CONCAT_VECTORS: 309 setOperationAction(Op, VT, Custom); 310 break; 311 default: 312 setOperationAction(Op, VT, Expand); 313 break; 314 } 315 } 316 } 317 318 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 319 320 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 321 // is expanded to avoid having two separate loops in case the index is a VGPR. 322 323 // Most operations are naturally 32-bit vector operations. We only support 324 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 325 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 326 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 328 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 330 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 333 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 334 335 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 337 } 338 339 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 340 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 344 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 345 346 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 347 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 348 349 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 351 } 352 353 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 354 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 358 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 359 360 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 361 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 362 363 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 365 } 366 367 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 368 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 372 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 373 374 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 375 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 376 377 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 378 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 379 } 380 381 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 382 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 383 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 384 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 385 386 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 387 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 388 389 // Avoid stack access for these. 390 // TODO: Generalize to more vector types. 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 395 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 401 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 403 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 404 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 405 406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 408 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 409 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 410 411 // Deal with vec3 vector operations when widened to vec4. 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 416 417 // Deal with vec5 vector operations when widened to vec8. 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 419 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 420 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 421 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 422 423 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 424 // and output demarshalling 425 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 427 428 // We can't return success/failure, only the old value, 429 // let LLVM add the comparison 430 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 431 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 432 433 if (Subtarget->hasFlatAddressSpace()) { 434 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 435 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 436 } 437 438 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 439 440 // FIXME: This should be narrowed to i32, but that only happens if i64 is 441 // illegal. 442 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 443 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 444 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 445 446 // On SI this is s_memtime and s_memrealtime on VI. 447 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 448 setOperationAction(ISD::TRAP, MVT::Other, Custom); 449 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::FPOW, MVT::f16, Promote); 453 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 454 setOperationAction(ISD::FLOG, MVT::f16, Custom); 455 setOperationAction(ISD::FEXP, MVT::f16, Custom); 456 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 457 } 458 459 if (Subtarget->hasMadMacF32Insts()) 460 setOperationAction(ISD::FMAD, MVT::f32, Legal); 461 462 if (!Subtarget->hasBFI()) { 463 // fcopysign can be done in a single instruction with BFI. 464 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 466 } 467 468 if (!Subtarget->hasBCNT(32)) 469 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 470 471 if (!Subtarget->hasBCNT(64)) 472 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 473 474 if (Subtarget->hasFFBH()) 475 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 476 477 if (Subtarget->hasFFBL()) 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 480 // We only really have 32-bit BFE instructions (and 16-bit on VI). 481 // 482 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 483 // effort to match them now. We want this to be false for i64 cases when the 484 // extraction isn't restricted to the upper or lower half. Ideally we would 485 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 486 // span the midpoint are probably relatively rare, so don't worry about them 487 // for now. 488 if (Subtarget->hasBFE()) 489 setHasExtractBitsInsn(true); 490 491 // Clamp modifier on add/sub 492 if (Subtarget->hasIntClamp()) { 493 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 494 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 495 } 496 497 if (Subtarget->hasAddNoCarry()) { 498 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 499 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 502 } 503 504 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 505 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 508 509 510 // These are really only legal for ieee_mode functions. We should be avoiding 511 // them for functions that don't have ieee_mode enabled, so just say they are 512 // legal. 513 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 514 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 517 518 519 if (Subtarget->haveRoundOpsF64()) { 520 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 521 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 522 setOperationAction(ISD::FRINT, MVT::f64, Legal); 523 } else { 524 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 525 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 526 setOperationAction(ISD::FRINT, MVT::f64, Custom); 527 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 528 } 529 530 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 531 532 setOperationAction(ISD::FSIN, MVT::f32, Custom); 533 setOperationAction(ISD::FCOS, MVT::f32, Custom); 534 setOperationAction(ISD::FDIV, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f64, Custom); 536 537 if (Subtarget->has16BitInsts()) { 538 setOperationAction(ISD::Constant, MVT::i16, Legal); 539 540 setOperationAction(ISD::SMIN, MVT::i16, Legal); 541 setOperationAction(ISD::SMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::UMIN, MVT::i16, Legal); 544 setOperationAction(ISD::UMAX, MVT::i16, Legal); 545 546 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 547 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 548 549 setOperationAction(ISD::ROTR, MVT::i16, Expand); 550 setOperationAction(ISD::ROTL, MVT::i16, Expand); 551 552 setOperationAction(ISD::SDIV, MVT::i16, Promote); 553 setOperationAction(ISD::UDIV, MVT::i16, Promote); 554 setOperationAction(ISD::SREM, MVT::i16, Promote); 555 setOperationAction(ISD::UREM, MVT::i16, Promote); 556 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 557 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 558 559 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 560 561 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 563 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 566 567 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 568 569 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::LOAD, MVT::i16, Custom); 572 573 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 574 575 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 576 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 577 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 579 580 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 582 583 // F16 - Constant Actions. 584 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 585 586 // F16 - Load/Store Actions. 587 setOperationAction(ISD::LOAD, MVT::f16, Promote); 588 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 589 setOperationAction(ISD::STORE, MVT::f16, Promote); 590 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 591 592 // F16 - VOP1 Actions. 593 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 594 setOperationAction(ISD::FCOS, MVT::f16, Custom); 595 setOperationAction(ISD::FSIN, MVT::f16, Custom); 596 597 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 598 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 599 600 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 601 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 602 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 603 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::FROUND, MVT::f16, Custom); 605 606 // F16 - VOP2 Actions. 607 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 608 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 609 610 setOperationAction(ISD::FDIV, MVT::f16, Custom); 611 612 // F16 - VOP3 Actions. 613 setOperationAction(ISD::FMA, MVT::f16, Legal); 614 if (STI.hasMadF16()) 615 setOperationAction(ISD::FMAD, MVT::f16, Legal); 616 617 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 618 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 619 switch (Op) { 620 case ISD::LOAD: 621 case ISD::STORE: 622 case ISD::BUILD_VECTOR: 623 case ISD::BITCAST: 624 case ISD::EXTRACT_VECTOR_ELT: 625 case ISD::INSERT_VECTOR_ELT: 626 case ISD::INSERT_SUBVECTOR: 627 case ISD::EXTRACT_SUBVECTOR: 628 case ISD::SCALAR_TO_VECTOR: 629 break; 630 case ISD::CONCAT_VECTORS: 631 setOperationAction(Op, VT, Custom); 632 break; 633 default: 634 setOperationAction(Op, VT, Expand); 635 break; 636 } 637 } 638 } 639 640 // v_perm_b32 can handle either of these. 641 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 642 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 643 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 644 645 // XXX - Do these do anything? Vector constants turn into build_vector. 646 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 647 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 650 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 653 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 654 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 655 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 656 657 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 658 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 659 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 660 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 661 662 setOperationAction(ISD::AND, MVT::v2i16, Promote); 663 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 664 setOperationAction(ISD::OR, MVT::v2i16, Promote); 665 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 666 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 668 669 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 670 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 671 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 672 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 673 674 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 675 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 676 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 677 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 678 679 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 680 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 681 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 682 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 683 684 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 685 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 686 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 687 688 if (!Subtarget->hasVOP3PInsts()) { 689 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 690 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 691 } 692 693 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 694 // This isn't really legal, but this avoids the legalizer unrolling it (and 695 // allows matching fneg (fabs x) patterns) 696 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 697 698 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 699 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 700 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 701 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 702 703 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 704 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 705 706 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 707 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 708 } 709 710 if (Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 712 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 713 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 714 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 715 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 716 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 717 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 718 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 719 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 720 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 721 722 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 723 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 724 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 725 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 726 727 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 728 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 732 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 733 734 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 735 736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 738 739 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 740 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 741 742 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 743 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 744 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 745 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 746 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 747 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 748 749 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 750 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 751 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 752 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 753 754 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 755 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 756 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 757 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 758 759 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 760 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 762 763 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 764 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 765 766 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 767 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 768 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 769 770 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 771 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 772 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 773 } 774 775 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 776 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 777 778 if (Subtarget->has16BitInsts()) { 779 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 780 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 781 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 782 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 783 } else { 784 // Legalization hack. 785 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 786 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 787 788 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 790 } 791 792 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 793 setOperationAction(ISD::SELECT, VT, Custom); 794 } 795 796 setOperationAction(ISD::SMULO, MVT::i64, Custom); 797 setOperationAction(ISD::UMULO, MVT::i64, Custom); 798 799 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 801 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 802 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 803 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 804 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 805 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 806 807 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 808 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 809 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 810 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 811 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 812 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 813 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 818 819 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 820 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 821 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 822 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 823 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 824 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 829 830 setTargetDAGCombine(ISD::ADD); 831 setTargetDAGCombine(ISD::ADDCARRY); 832 setTargetDAGCombine(ISD::SUB); 833 setTargetDAGCombine(ISD::SUBCARRY); 834 setTargetDAGCombine(ISD::FADD); 835 setTargetDAGCombine(ISD::FSUB); 836 setTargetDAGCombine(ISD::FMINNUM); 837 setTargetDAGCombine(ISD::FMAXNUM); 838 setTargetDAGCombine(ISD::FMINNUM_IEEE); 839 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 840 setTargetDAGCombine(ISD::FMA); 841 setTargetDAGCombine(ISD::SMIN); 842 setTargetDAGCombine(ISD::SMAX); 843 setTargetDAGCombine(ISD::UMIN); 844 setTargetDAGCombine(ISD::UMAX); 845 setTargetDAGCombine(ISD::SETCC); 846 setTargetDAGCombine(ISD::AND); 847 setTargetDAGCombine(ISD::OR); 848 setTargetDAGCombine(ISD::XOR); 849 setTargetDAGCombine(ISD::SINT_TO_FP); 850 setTargetDAGCombine(ISD::UINT_TO_FP); 851 setTargetDAGCombine(ISD::FCANONICALIZE); 852 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 853 setTargetDAGCombine(ISD::ZERO_EXTEND); 854 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 855 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 856 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 857 858 // All memory operations. Some folding on the pointer operand is done to help 859 // matching the constant offsets in the addressing modes. 860 setTargetDAGCombine(ISD::LOAD); 861 setTargetDAGCombine(ISD::STORE); 862 setTargetDAGCombine(ISD::ATOMIC_LOAD); 863 setTargetDAGCombine(ISD::ATOMIC_STORE); 864 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 865 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 866 setTargetDAGCombine(ISD::ATOMIC_SWAP); 867 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 868 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 870 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 871 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 872 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 873 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 878 setTargetDAGCombine(ISD::INTRINSIC_VOID); 879 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 880 881 // FIXME: In other contexts we pretend this is a per-function property. 882 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 883 884 setSchedulingPreference(Sched::RegPressure); 885 } 886 887 const GCNSubtarget *SITargetLowering::getSubtarget() const { 888 return Subtarget; 889 } 890 891 //===----------------------------------------------------------------------===// 892 // TargetLowering queries 893 //===----------------------------------------------------------------------===// 894 895 // v_mad_mix* support a conversion from f16 to f32. 896 // 897 // There is only one special case when denormals are enabled we don't currently, 898 // where this is OK to use. 899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 900 EVT DestVT, EVT SrcVT) const { 901 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 902 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 903 DestVT.getScalarType() == MVT::f32 && 904 SrcVT.getScalarType() == MVT::f16 && 905 // TODO: This probably only requires no input flushing? 906 !hasFP32Denormals(DAG.getMachineFunction()); 907 } 908 909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 910 // SI has some legal vector types, but no legal vector operations. Say no 911 // shuffles are legal in order to prefer scalarizing some vector operations. 912 return false; 913 } 914 915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 916 CallingConv::ID CC, 917 EVT VT) const { 918 if (CC == CallingConv::AMDGPU_KERNEL) 919 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 920 921 if (VT.isVector()) { 922 EVT ScalarVT = VT.getScalarType(); 923 unsigned Size = ScalarVT.getSizeInBits(); 924 if (Size == 16) { 925 if (Subtarget->has16BitInsts()) 926 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 927 return VT.isInteger() ? MVT::i32 : MVT::f32; 928 } 929 930 if (Size < 16) 931 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 932 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 933 } 934 935 if (VT.getSizeInBits() > 32) 936 return MVT::i32; 937 938 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 939 } 940 941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 942 CallingConv::ID CC, 943 EVT VT) const { 944 if (CC == CallingConv::AMDGPU_KERNEL) 945 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 946 947 if (VT.isVector()) { 948 unsigned NumElts = VT.getVectorNumElements(); 949 EVT ScalarVT = VT.getScalarType(); 950 unsigned Size = ScalarVT.getSizeInBits(); 951 952 // FIXME: Should probably promote 8-bit vectors to i16. 953 if (Size == 16 && Subtarget->has16BitInsts()) 954 return (NumElts + 1) / 2; 955 956 if (Size <= 32) 957 return NumElts; 958 959 if (Size > 32) 960 return NumElts * ((Size + 31) / 32); 961 } else if (VT.getSizeInBits() > 32) 962 return (VT.getSizeInBits() + 31) / 32; 963 964 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 965 } 966 967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 968 LLVMContext &Context, CallingConv::ID CC, 969 EVT VT, EVT &IntermediateVT, 970 unsigned &NumIntermediates, MVT &RegisterVT) const { 971 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 972 unsigned NumElts = VT.getVectorNumElements(); 973 EVT ScalarVT = VT.getScalarType(); 974 unsigned Size = ScalarVT.getSizeInBits(); 975 // FIXME: We should fix the ABI to be the same on targets without 16-bit 976 // support, but unless we can properly handle 3-vectors, it will be still be 977 // inconsistent. 978 if (Size == 16 && Subtarget->has16BitInsts()) { 979 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 980 IntermediateVT = RegisterVT; 981 NumIntermediates = (NumElts + 1) / 2; 982 return NumIntermediates; 983 } 984 985 if (Size == 32) { 986 RegisterVT = ScalarVT.getSimpleVT(); 987 IntermediateVT = RegisterVT; 988 NumIntermediates = NumElts; 989 return NumIntermediates; 990 } 991 992 if (Size < 16 && Subtarget->has16BitInsts()) { 993 // FIXME: Should probably form v2i16 pieces 994 RegisterVT = MVT::i16; 995 IntermediateVT = ScalarVT; 996 NumIntermediates = NumElts; 997 return NumIntermediates; 998 } 999 1000 1001 if (Size != 16 && Size <= 32) { 1002 RegisterVT = MVT::i32; 1003 IntermediateVT = ScalarVT; 1004 NumIntermediates = NumElts; 1005 return NumIntermediates; 1006 } 1007 1008 if (Size > 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = RegisterVT; 1011 NumIntermediates = NumElts * ((Size + 31) / 32); 1012 return NumIntermediates; 1013 } 1014 } 1015 1016 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1017 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1018 } 1019 1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1021 assert(DMaskLanes != 0); 1022 1023 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1024 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1025 return EVT::getVectorVT(Ty->getContext(), 1026 EVT::getEVT(VT->getElementType()), 1027 NumElts); 1028 } 1029 1030 return EVT::getEVT(Ty); 1031 } 1032 1033 // Peek through TFE struct returns to only use the data size. 1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1035 auto *ST = dyn_cast<StructType>(Ty); 1036 if (!ST) 1037 return memVTFromImageData(Ty, DMaskLanes); 1038 1039 // Some intrinsics return an aggregate type - special case to work out the 1040 // correct memVT. 1041 // 1042 // Only limited forms of aggregate type currently expected. 1043 if (ST->getNumContainedTypes() != 2 || 1044 !ST->getContainedType(1)->isIntegerTy(32)) 1045 return EVT(); 1046 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1047 } 1048 1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1050 const CallInst &CI, 1051 MachineFunction &MF, 1052 unsigned IntrID) const { 1053 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1054 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1055 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1056 (Intrinsic::ID)IntrID); 1057 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1058 return false; 1059 1060 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1061 1062 if (RsrcIntr->IsImage) { 1063 Info.ptrVal = MFI->getImagePSV( 1064 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1065 CI.getArgOperand(RsrcIntr->RsrcArg)); 1066 Info.align.reset(); 1067 } else { 1068 Info.ptrVal = MFI->getBufferPSV( 1069 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1070 CI.getArgOperand(RsrcIntr->RsrcArg)); 1071 } 1072 1073 Info.flags = MachineMemOperand::MODereferenceable; 1074 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1075 unsigned DMaskLanes = 4; 1076 1077 if (RsrcIntr->IsImage) { 1078 const AMDGPU::ImageDimIntrinsicInfo *Intr 1079 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1080 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1081 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1082 1083 if (!BaseOpcode->Gather4) { 1084 // If this isn't a gather, we may have excess loaded elements in the 1085 // IR type. Check the dmask for the real number of elements loaded. 1086 unsigned DMask 1087 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1088 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1089 } 1090 1091 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1092 } else 1093 Info.memVT = EVT::getEVT(CI.getType()); 1094 1095 // FIXME: What does alignment mean for an image? 1096 Info.opc = ISD::INTRINSIC_W_CHAIN; 1097 Info.flags |= MachineMemOperand::MOLoad; 1098 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1099 Info.opc = ISD::INTRINSIC_VOID; 1100 1101 Type *DataTy = CI.getArgOperand(0)->getType(); 1102 if (RsrcIntr->IsImage) { 1103 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1104 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1105 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1106 } else 1107 Info.memVT = EVT::getEVT(DataTy); 1108 1109 Info.flags |= MachineMemOperand::MOStore; 1110 } else { 1111 // Atomic 1112 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1113 ISD::INTRINSIC_W_CHAIN; 1114 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1115 Info.flags = MachineMemOperand::MOLoad | 1116 MachineMemOperand::MOStore | 1117 MachineMemOperand::MODereferenceable; 1118 1119 // XXX - Should this be volatile without known ordering? 1120 Info.flags |= MachineMemOperand::MOVolatile; 1121 } 1122 return true; 1123 } 1124 1125 switch (IntrID) { 1126 case Intrinsic::amdgcn_atomic_inc: 1127 case Intrinsic::amdgcn_atomic_dec: 1128 case Intrinsic::amdgcn_ds_ordered_add: 1129 case Intrinsic::amdgcn_ds_ordered_swap: 1130 case Intrinsic::amdgcn_ds_fadd: 1131 case Intrinsic::amdgcn_ds_fmin: 1132 case Intrinsic::amdgcn_ds_fmax: { 1133 Info.opc = ISD::INTRINSIC_W_CHAIN; 1134 Info.memVT = MVT::getVT(CI.getType()); 1135 Info.ptrVal = CI.getOperand(0); 1136 Info.align.reset(); 1137 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1138 1139 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1140 if (!Vol->isZero()) 1141 Info.flags |= MachineMemOperand::MOVolatile; 1142 1143 return true; 1144 } 1145 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1147 1148 Info.opc = ISD::INTRINSIC_W_CHAIN; 1149 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1150 Info.ptrVal = MFI->getBufferPSV( 1151 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1152 CI.getArgOperand(1)); 1153 Info.align.reset(); 1154 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1155 1156 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1157 if (!Vol || !Vol->isZero()) 1158 Info.flags |= MachineMemOperand::MOVolatile; 1159 1160 return true; 1161 } 1162 case Intrinsic::amdgcn_ds_append: 1163 case Intrinsic::amdgcn_ds_consume: { 1164 Info.opc = ISD::INTRINSIC_W_CHAIN; 1165 Info.memVT = MVT::getVT(CI.getType()); 1166 Info.ptrVal = CI.getOperand(0); 1167 Info.align.reset(); 1168 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1169 1170 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1171 if (!Vol->isZero()) 1172 Info.flags |= MachineMemOperand::MOVolatile; 1173 1174 return true; 1175 } 1176 case Intrinsic::amdgcn_global_atomic_csub: { 1177 Info.opc = ISD::INTRINSIC_W_CHAIN; 1178 Info.memVT = MVT::getVT(CI.getType()); 1179 Info.ptrVal = CI.getOperand(0); 1180 Info.align.reset(); 1181 Info.flags = MachineMemOperand::MOLoad | 1182 MachineMemOperand::MOStore | 1183 MachineMemOperand::MOVolatile; 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_fadd: { 1187 Info.opc = ISD::INTRINSIC_W_CHAIN; 1188 Info.memVT = MVT::getVT(CI.getType()); 1189 Info.ptrVal = CI.getOperand(0); 1190 Info.align.reset(); 1191 Info.flags = MachineMemOperand::MOLoad | 1192 MachineMemOperand::MOStore | 1193 MachineMemOperand::MODereferenceable | 1194 MachineMemOperand::MOVolatile; 1195 return true; 1196 } 1197 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1198 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1201 Info.ptrVal = MFI->getImagePSV( 1202 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5)); 1203 Info.align.reset(); 1204 Info.flags = MachineMemOperand::MOLoad | 1205 MachineMemOperand::MODereferenceable; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_ds_gws_init: 1209 case Intrinsic::amdgcn_ds_gws_barrier: 1210 case Intrinsic::amdgcn_ds_gws_sema_v: 1211 case Intrinsic::amdgcn_ds_gws_sema_br: 1212 case Intrinsic::amdgcn_ds_gws_sema_p: 1213 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1214 Info.opc = ISD::INTRINSIC_VOID; 1215 1216 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1217 Info.ptrVal = 1218 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1219 1220 // This is an abstract access, but we need to specify a type and size. 1221 Info.memVT = MVT::i32; 1222 Info.size = 4; 1223 Info.align = Align(4); 1224 1225 Info.flags = MachineMemOperand::MOStore; 1226 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1227 Info.flags = MachineMemOperand::MOLoad; 1228 return true; 1229 } 1230 default: 1231 return false; 1232 } 1233 } 1234 1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1236 SmallVectorImpl<Value*> &Ops, 1237 Type *&AccessTy) const { 1238 switch (II->getIntrinsicID()) { 1239 case Intrinsic::amdgcn_atomic_inc: 1240 case Intrinsic::amdgcn_atomic_dec: 1241 case Intrinsic::amdgcn_ds_ordered_add: 1242 case Intrinsic::amdgcn_ds_ordered_swap: 1243 case Intrinsic::amdgcn_ds_append: 1244 case Intrinsic::amdgcn_ds_consume: 1245 case Intrinsic::amdgcn_ds_fadd: 1246 case Intrinsic::amdgcn_ds_fmin: 1247 case Intrinsic::amdgcn_ds_fmax: 1248 case Intrinsic::amdgcn_global_atomic_fadd: 1249 case Intrinsic::amdgcn_global_atomic_csub: { 1250 Value *Ptr = II->getArgOperand(0); 1251 AccessTy = II->getType(); 1252 Ops.push_back(Ptr); 1253 return true; 1254 } 1255 default: 1256 return false; 1257 } 1258 } 1259 1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1261 if (!Subtarget->hasFlatInstOffsets()) { 1262 // Flat instructions do not have offsets, and only have the register 1263 // address. 1264 return AM.BaseOffs == 0 && AM.Scale == 0; 1265 } 1266 1267 return AM.Scale == 0 && 1268 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1269 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1270 /*Signed=*/false)); 1271 } 1272 1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1274 if (Subtarget->hasFlatGlobalInsts()) 1275 return AM.Scale == 0 && 1276 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1277 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1278 /*Signed=*/true)); 1279 1280 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1281 // Assume the we will use FLAT for all global memory accesses 1282 // on VI. 1283 // FIXME: This assumption is currently wrong. On VI we still use 1284 // MUBUF instructions for the r + i addressing mode. As currently 1285 // implemented, the MUBUF instructions only work on buffer < 4GB. 1286 // It may be possible to support > 4GB buffers with MUBUF instructions, 1287 // by setting the stride value in the resource descriptor which would 1288 // increase the size limit to (stride * 4GB). However, this is risky, 1289 // because it has never been validated. 1290 return isLegalFlatAddressingMode(AM); 1291 } 1292 1293 return isLegalMUBUFAddressingMode(AM); 1294 } 1295 1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1297 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1298 // additionally can do r + r + i with addr64. 32-bit has more addressing 1299 // mode options. Depending on the resource constant, it can also do 1300 // (i64 r0) + (i32 r1) * (i14 i). 1301 // 1302 // Private arrays end up using a scratch buffer most of the time, so also 1303 // assume those use MUBUF instructions. Scratch loads / stores are currently 1304 // implemented as mubuf instructions with offen bit set, so slightly 1305 // different than the normal addr64. 1306 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1307 return false; 1308 1309 // FIXME: Since we can split immediate into soffset and immediate offset, 1310 // would it make sense to allow any immediate? 1311 1312 switch (AM.Scale) { 1313 case 0: // r + i or just i, depending on HasBaseReg. 1314 return true; 1315 case 1: 1316 return true; // We have r + r or r + i. 1317 case 2: 1318 if (AM.HasBaseReg) { 1319 // Reject 2 * r + r. 1320 return false; 1321 } 1322 1323 // Allow 2 * r as r + r 1324 // Or 2 * r + i is allowed as r + r + i. 1325 return true; 1326 default: // Don't allow n * r 1327 return false; 1328 } 1329 } 1330 1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1332 const AddrMode &AM, Type *Ty, 1333 unsigned AS, Instruction *I) const { 1334 // No global is ever allowed as a base. 1335 if (AM.BaseGV) 1336 return false; 1337 1338 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1339 return isLegalGlobalAddressingMode(AM); 1340 1341 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1342 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1343 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1344 // If the offset isn't a multiple of 4, it probably isn't going to be 1345 // correctly aligned. 1346 // FIXME: Can we get the real alignment here? 1347 if (AM.BaseOffs % 4 != 0) 1348 return isLegalMUBUFAddressingMode(AM); 1349 1350 // There are no SMRD extloads, so if we have to do a small type access we 1351 // will use a MUBUF load. 1352 // FIXME?: We also need to do this if unaligned, but we don't know the 1353 // alignment here. 1354 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1355 return isLegalGlobalAddressingMode(AM); 1356 1357 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1358 // SMRD instructions have an 8-bit, dword offset on SI. 1359 if (!isUInt<8>(AM.BaseOffs / 4)) 1360 return false; 1361 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1362 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1363 // in 8-bits, it can use a smaller encoding. 1364 if (!isUInt<32>(AM.BaseOffs / 4)) 1365 return false; 1366 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1367 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1368 if (!isUInt<20>(AM.BaseOffs)) 1369 return false; 1370 } else 1371 llvm_unreachable("unhandled generation"); 1372 1373 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1374 return true; 1375 1376 if (AM.Scale == 1 && AM.HasBaseReg) 1377 return true; 1378 1379 return false; 1380 1381 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1382 return isLegalMUBUFAddressingMode(AM); 1383 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1384 AS == AMDGPUAS::REGION_ADDRESS) { 1385 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1386 // field. 1387 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1388 // an 8-bit dword offset but we don't know the alignment here. 1389 if (!isUInt<16>(AM.BaseOffs)) 1390 return false; 1391 1392 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1393 return true; 1394 1395 if (AM.Scale == 1 && AM.HasBaseReg) 1396 return true; 1397 1398 return false; 1399 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1400 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1401 // For an unknown address space, this usually means that this is for some 1402 // reason being used for pure arithmetic, and not based on some addressing 1403 // computation. We don't have instructions that compute pointers with any 1404 // addressing modes, so treat them as having no offset like flat 1405 // instructions. 1406 return isLegalFlatAddressingMode(AM); 1407 } 1408 1409 // Assume a user alias of global for unknown address spaces. 1410 return isLegalGlobalAddressingMode(AM); 1411 } 1412 1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1414 const SelectionDAG &DAG) const { 1415 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1416 return (MemVT.getSizeInBits() <= 4 * 32); 1417 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1418 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1419 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1420 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1421 return (MemVT.getSizeInBits() <= 2 * 32); 1422 } 1423 return true; 1424 } 1425 1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1427 unsigned Size, unsigned AddrSpace, Align Alignment, 1428 MachineMemOperand::Flags Flags, bool *IsFast) const { 1429 if (IsFast) 1430 *IsFast = false; 1431 1432 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1433 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1434 // Check if alignment requirements for ds_read/write instructions are 1435 // disabled. 1436 if (Subtarget->hasUnalignedDSAccessEnabled() && 1437 !Subtarget->hasLDSMisalignedBug()) { 1438 if (IsFast) 1439 *IsFast = Alignment != Align(2); 1440 return true; 1441 } 1442 1443 if (Size == 64) { 1444 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1445 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1446 // with adjacent offsets. 1447 bool AlignedBy4 = Alignment >= Align(4); 1448 if (IsFast) 1449 *IsFast = AlignedBy4; 1450 1451 return AlignedBy4; 1452 } 1453 if (Size == 96) { 1454 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1455 bool Aligned = Alignment >= Align(16); 1456 if (IsFast) 1457 *IsFast = Aligned; 1458 1459 return Aligned; 1460 } 1461 if (Size == 128) { 1462 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1463 // can do a 8 byte aligned, 16 byte access in a single operation using 1464 // ds_read2/write2_b64. 1465 bool Aligned = Alignment >= Align(8); 1466 if (IsFast) 1467 *IsFast = Aligned; 1468 1469 return Aligned; 1470 } 1471 } 1472 1473 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1474 bool AlignedBy4 = Alignment >= Align(4); 1475 if (IsFast) 1476 *IsFast = AlignedBy4; 1477 1478 return AlignedBy4 || 1479 Subtarget->enableFlatScratch() || 1480 Subtarget->hasUnalignedScratchAccess(); 1481 } 1482 1483 // FIXME: We have to be conservative here and assume that flat operations 1484 // will access scratch. If we had access to the IR function, then we 1485 // could determine if any private memory was used in the function. 1486 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1487 !Subtarget->hasUnalignedScratchAccess()) { 1488 bool AlignedBy4 = Alignment >= Align(4); 1489 if (IsFast) 1490 *IsFast = AlignedBy4; 1491 1492 return AlignedBy4; 1493 } 1494 1495 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1496 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1497 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1498 // If we have an uniform constant load, it still requires using a slow 1499 // buffer instruction if unaligned. 1500 if (IsFast) { 1501 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1502 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1503 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1504 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1505 Alignment >= Align(4) : Alignment != Align(2); 1506 } 1507 1508 return true; 1509 } 1510 1511 // Smaller than dword value must be aligned. 1512 if (Size < 32) 1513 return false; 1514 1515 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1516 // byte-address are ignored, thus forcing Dword alignment. 1517 // This applies to private, global, and constant memory. 1518 if (IsFast) 1519 *IsFast = true; 1520 1521 return Size >= 32 && Alignment >= Align(4); 1522 } 1523 1524 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1525 EVT VT, unsigned AddrSpace, unsigned Alignment, 1526 MachineMemOperand::Flags Flags, bool *IsFast) const { 1527 if (IsFast) 1528 *IsFast = false; 1529 1530 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1531 // which isn't a simple VT. 1532 // Until MVT is extended to handle this, simply check for the size and 1533 // rely on the condition below: allow accesses if the size is a multiple of 4. 1534 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1535 VT.getStoreSize() > 16)) { 1536 return false; 1537 } 1538 1539 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1540 Align(Alignment), Flags, IsFast); 1541 } 1542 1543 EVT SITargetLowering::getOptimalMemOpType( 1544 const MemOp &Op, const AttributeList &FuncAttributes) const { 1545 // FIXME: Should account for address space here. 1546 1547 // The default fallback uses the private pointer size as a guess for a type to 1548 // use. Make sure we switch these to 64-bit accesses. 1549 1550 if (Op.size() >= 16 && 1551 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1552 return MVT::v4i32; 1553 1554 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1555 return MVT::v2i32; 1556 1557 // Use the default. 1558 return MVT::Other; 1559 } 1560 1561 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1562 const MemSDNode *MemNode = cast<MemSDNode>(N); 1563 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1564 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1565 return I && I->getMetadata("amdgpu.noclobber"); 1566 } 1567 1568 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1569 unsigned DestAS) const { 1570 // Flat -> private/local is a simple truncate. 1571 // Flat -> global is no-op 1572 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1573 return true; 1574 1575 const GCNTargetMachine &TM = 1576 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1577 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1578 } 1579 1580 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1581 const MemSDNode *MemNode = cast<MemSDNode>(N); 1582 1583 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1584 } 1585 1586 TargetLoweringBase::LegalizeTypeAction 1587 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1588 int NumElts = VT.getVectorNumElements(); 1589 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1590 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1591 return TargetLoweringBase::getPreferredVectorAction(VT); 1592 } 1593 1594 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1595 Type *Ty) const { 1596 // FIXME: Could be smarter if called for vector constants. 1597 return true; 1598 } 1599 1600 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1601 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1602 switch (Op) { 1603 case ISD::LOAD: 1604 case ISD::STORE: 1605 1606 // These operations are done with 32-bit instructions anyway. 1607 case ISD::AND: 1608 case ISD::OR: 1609 case ISD::XOR: 1610 case ISD::SELECT: 1611 // TODO: Extensions? 1612 return true; 1613 default: 1614 return false; 1615 } 1616 } 1617 1618 // SimplifySetCC uses this function to determine whether or not it should 1619 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1620 if (VT == MVT::i1 && Op == ISD::SETCC) 1621 return false; 1622 1623 return TargetLowering::isTypeDesirableForOp(Op, VT); 1624 } 1625 1626 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1627 const SDLoc &SL, 1628 SDValue Chain, 1629 uint64_t Offset) const { 1630 const DataLayout &DL = DAG.getDataLayout(); 1631 MachineFunction &MF = DAG.getMachineFunction(); 1632 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1633 1634 const ArgDescriptor *InputPtrReg; 1635 const TargetRegisterClass *RC; 1636 LLT ArgTy; 1637 1638 std::tie(InputPtrReg, RC, ArgTy) = 1639 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1640 1641 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1642 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1643 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1644 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1645 1646 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1647 } 1648 1649 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1650 const SDLoc &SL) const { 1651 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1652 FIRST_IMPLICIT); 1653 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1654 } 1655 1656 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1657 const SDLoc &SL, SDValue Val, 1658 bool Signed, 1659 const ISD::InputArg *Arg) const { 1660 // First, if it is a widened vector, narrow it. 1661 if (VT.isVector() && 1662 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1663 EVT NarrowedVT = 1664 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1665 VT.getVectorNumElements()); 1666 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1667 DAG.getConstant(0, SL, MVT::i32)); 1668 } 1669 1670 // Then convert the vector elements or scalar value. 1671 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1672 VT.bitsLT(MemVT)) { 1673 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1674 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1675 } 1676 1677 if (MemVT.isFloatingPoint()) 1678 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1679 else if (Signed) 1680 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1681 else 1682 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1683 1684 return Val; 1685 } 1686 1687 SDValue SITargetLowering::lowerKernargMemParameter( 1688 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1689 uint64_t Offset, Align Alignment, bool Signed, 1690 const ISD::InputArg *Arg) const { 1691 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1692 1693 // Try to avoid using an extload by loading earlier than the argument address, 1694 // and extracting the relevant bits. The load should hopefully be merged with 1695 // the previous argument. 1696 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1697 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1698 int64_t AlignDownOffset = alignDown(Offset, 4); 1699 int64_t OffsetDiff = Offset - AlignDownOffset; 1700 1701 EVT IntVT = MemVT.changeTypeToInteger(); 1702 1703 // TODO: If we passed in the base kernel offset we could have a better 1704 // alignment than 4, but we don't really need it. 1705 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1706 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1707 MachineMemOperand::MODereferenceable | 1708 MachineMemOperand::MOInvariant); 1709 1710 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1711 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1712 1713 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1714 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1715 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1716 1717 1718 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1719 } 1720 1721 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1722 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1723 MachineMemOperand::MODereferenceable | 1724 MachineMemOperand::MOInvariant); 1725 1726 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1727 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1728 } 1729 1730 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1731 const SDLoc &SL, SDValue Chain, 1732 const ISD::InputArg &Arg) const { 1733 MachineFunction &MF = DAG.getMachineFunction(); 1734 MachineFrameInfo &MFI = MF.getFrameInfo(); 1735 1736 if (Arg.Flags.isByVal()) { 1737 unsigned Size = Arg.Flags.getByValSize(); 1738 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1739 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1740 } 1741 1742 unsigned ArgOffset = VA.getLocMemOffset(); 1743 unsigned ArgSize = VA.getValVT().getStoreSize(); 1744 1745 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1746 1747 // Create load nodes to retrieve arguments from the stack. 1748 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1749 SDValue ArgValue; 1750 1751 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1752 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1753 MVT MemVT = VA.getValVT(); 1754 1755 switch (VA.getLocInfo()) { 1756 default: 1757 break; 1758 case CCValAssign::BCvt: 1759 MemVT = VA.getLocVT(); 1760 break; 1761 case CCValAssign::SExt: 1762 ExtType = ISD::SEXTLOAD; 1763 break; 1764 case CCValAssign::ZExt: 1765 ExtType = ISD::ZEXTLOAD; 1766 break; 1767 case CCValAssign::AExt: 1768 ExtType = ISD::EXTLOAD; 1769 break; 1770 } 1771 1772 ArgValue = DAG.getExtLoad( 1773 ExtType, SL, VA.getLocVT(), Chain, FIN, 1774 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1775 MemVT); 1776 return ArgValue; 1777 } 1778 1779 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1780 const SIMachineFunctionInfo &MFI, 1781 EVT VT, 1782 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1783 const ArgDescriptor *Reg; 1784 const TargetRegisterClass *RC; 1785 LLT Ty; 1786 1787 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1788 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1789 } 1790 1791 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1792 CallingConv::ID CallConv, 1793 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1794 FunctionType *FType, 1795 SIMachineFunctionInfo *Info) { 1796 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1797 const ISD::InputArg *Arg = &Ins[I]; 1798 1799 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1800 "vector type argument should have been split"); 1801 1802 // First check if it's a PS input addr. 1803 if (CallConv == CallingConv::AMDGPU_PS && 1804 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1805 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1806 1807 // Inconveniently only the first part of the split is marked as isSplit, 1808 // so skip to the end. We only want to increment PSInputNum once for the 1809 // entire split argument. 1810 if (Arg->Flags.isSplit()) { 1811 while (!Arg->Flags.isSplitEnd()) { 1812 assert((!Arg->VT.isVector() || 1813 Arg->VT.getScalarSizeInBits() == 16) && 1814 "unexpected vector split in ps argument type"); 1815 if (!SkipArg) 1816 Splits.push_back(*Arg); 1817 Arg = &Ins[++I]; 1818 } 1819 } 1820 1821 if (SkipArg) { 1822 // We can safely skip PS inputs. 1823 Skipped.set(Arg->getOrigArgIndex()); 1824 ++PSInputNum; 1825 continue; 1826 } 1827 1828 Info->markPSInputAllocated(PSInputNum); 1829 if (Arg->Used) 1830 Info->markPSInputEnabled(PSInputNum); 1831 1832 ++PSInputNum; 1833 } 1834 1835 Splits.push_back(*Arg); 1836 } 1837 } 1838 1839 // Allocate special inputs passed in VGPRs. 1840 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1841 MachineFunction &MF, 1842 const SIRegisterInfo &TRI, 1843 SIMachineFunctionInfo &Info) const { 1844 const LLT S32 = LLT::scalar(32); 1845 MachineRegisterInfo &MRI = MF.getRegInfo(); 1846 1847 if (Info.hasWorkItemIDX()) { 1848 Register Reg = AMDGPU::VGPR0; 1849 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1850 1851 CCInfo.AllocateReg(Reg); 1852 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1853 } 1854 1855 if (Info.hasWorkItemIDY()) { 1856 Register Reg = AMDGPU::VGPR1; 1857 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1858 1859 CCInfo.AllocateReg(Reg); 1860 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1861 } 1862 1863 if (Info.hasWorkItemIDZ()) { 1864 Register Reg = AMDGPU::VGPR2; 1865 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1866 1867 CCInfo.AllocateReg(Reg); 1868 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1869 } 1870 } 1871 1872 // Try to allocate a VGPR at the end of the argument list, or if no argument 1873 // VGPRs are left allocating a stack slot. 1874 // If \p Mask is is given it indicates bitfield position in the register. 1875 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1876 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1877 ArgDescriptor Arg = ArgDescriptor()) { 1878 if (Arg.isSet()) 1879 return ArgDescriptor::createArg(Arg, Mask); 1880 1881 ArrayRef<MCPhysReg> ArgVGPRs 1882 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1883 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1884 if (RegIdx == ArgVGPRs.size()) { 1885 // Spill to stack required. 1886 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1887 1888 return ArgDescriptor::createStack(Offset, Mask); 1889 } 1890 1891 unsigned Reg = ArgVGPRs[RegIdx]; 1892 Reg = CCInfo.AllocateReg(Reg); 1893 assert(Reg != AMDGPU::NoRegister); 1894 1895 MachineFunction &MF = CCInfo.getMachineFunction(); 1896 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1897 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1898 return ArgDescriptor::createRegister(Reg, Mask); 1899 } 1900 1901 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1902 const TargetRegisterClass *RC, 1903 unsigned NumArgRegs) { 1904 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1905 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1906 if (RegIdx == ArgSGPRs.size()) 1907 report_fatal_error("ran out of SGPRs for arguments"); 1908 1909 unsigned Reg = ArgSGPRs[RegIdx]; 1910 Reg = CCInfo.AllocateReg(Reg); 1911 assert(Reg != AMDGPU::NoRegister); 1912 1913 MachineFunction &MF = CCInfo.getMachineFunction(); 1914 MF.addLiveIn(Reg, RC); 1915 return ArgDescriptor::createRegister(Reg); 1916 } 1917 1918 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1919 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1920 } 1921 1922 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1923 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1924 } 1925 1926 /// Allocate implicit function VGPR arguments at the end of allocated user 1927 /// arguments. 1928 void SITargetLowering::allocateSpecialInputVGPRs( 1929 CCState &CCInfo, MachineFunction &MF, 1930 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1931 const unsigned Mask = 0x3ff; 1932 ArgDescriptor Arg; 1933 1934 if (Info.hasWorkItemIDX()) { 1935 Arg = allocateVGPR32Input(CCInfo, Mask); 1936 Info.setWorkItemIDX(Arg); 1937 } 1938 1939 if (Info.hasWorkItemIDY()) { 1940 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1941 Info.setWorkItemIDY(Arg); 1942 } 1943 1944 if (Info.hasWorkItemIDZ()) 1945 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1946 } 1947 1948 /// Allocate implicit function VGPR arguments in fixed registers. 1949 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1950 CCState &CCInfo, MachineFunction &MF, 1951 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1952 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1953 if (!Reg) 1954 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1955 1956 const unsigned Mask = 0x3ff; 1957 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1958 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1959 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1960 } 1961 1962 void SITargetLowering::allocateSpecialInputSGPRs( 1963 CCState &CCInfo, 1964 MachineFunction &MF, 1965 const SIRegisterInfo &TRI, 1966 SIMachineFunctionInfo &Info) const { 1967 auto &ArgInfo = Info.getArgInfo(); 1968 1969 // TODO: Unify handling with private memory pointers. 1970 1971 if (Info.hasDispatchPtr()) 1972 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1973 1974 if (Info.hasQueuePtr()) 1975 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1976 1977 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1978 // constant offset from the kernarg segment. 1979 if (Info.hasImplicitArgPtr()) 1980 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1981 1982 if (Info.hasDispatchID()) 1983 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1984 1985 // flat_scratch_init is not applicable for non-kernel functions. 1986 1987 if (Info.hasWorkGroupIDX()) 1988 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1989 1990 if (Info.hasWorkGroupIDY()) 1991 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1992 1993 if (Info.hasWorkGroupIDZ()) 1994 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1995 } 1996 1997 // Allocate special inputs passed in user SGPRs. 1998 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1999 MachineFunction &MF, 2000 const SIRegisterInfo &TRI, 2001 SIMachineFunctionInfo &Info) const { 2002 if (Info.hasImplicitBufferPtr()) { 2003 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2004 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2005 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2006 } 2007 2008 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2009 if (Info.hasPrivateSegmentBuffer()) { 2010 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2011 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2012 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2013 } 2014 2015 if (Info.hasDispatchPtr()) { 2016 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2017 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2018 CCInfo.AllocateReg(DispatchPtrReg); 2019 } 2020 2021 if (Info.hasQueuePtr()) { 2022 Register QueuePtrReg = Info.addQueuePtr(TRI); 2023 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2024 CCInfo.AllocateReg(QueuePtrReg); 2025 } 2026 2027 if (Info.hasKernargSegmentPtr()) { 2028 MachineRegisterInfo &MRI = MF.getRegInfo(); 2029 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2030 CCInfo.AllocateReg(InputPtrReg); 2031 2032 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2033 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2034 } 2035 2036 if (Info.hasDispatchID()) { 2037 Register DispatchIDReg = Info.addDispatchID(TRI); 2038 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2039 CCInfo.AllocateReg(DispatchIDReg); 2040 } 2041 2042 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2043 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2044 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2045 CCInfo.AllocateReg(FlatScratchInitReg); 2046 } 2047 2048 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2049 // these from the dispatch pointer. 2050 } 2051 2052 // Allocate special input registers that are initialized per-wave. 2053 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2054 MachineFunction &MF, 2055 SIMachineFunctionInfo &Info, 2056 CallingConv::ID CallConv, 2057 bool IsShader) const { 2058 if (Info.hasWorkGroupIDX()) { 2059 Register Reg = Info.addWorkGroupIDX(); 2060 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2061 CCInfo.AllocateReg(Reg); 2062 } 2063 2064 if (Info.hasWorkGroupIDY()) { 2065 Register Reg = Info.addWorkGroupIDY(); 2066 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2067 CCInfo.AllocateReg(Reg); 2068 } 2069 2070 if (Info.hasWorkGroupIDZ()) { 2071 Register Reg = Info.addWorkGroupIDZ(); 2072 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2073 CCInfo.AllocateReg(Reg); 2074 } 2075 2076 if (Info.hasWorkGroupInfo()) { 2077 Register Reg = Info.addWorkGroupInfo(); 2078 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2079 CCInfo.AllocateReg(Reg); 2080 } 2081 2082 if (Info.hasPrivateSegmentWaveByteOffset()) { 2083 // Scratch wave offset passed in system SGPR. 2084 unsigned PrivateSegmentWaveByteOffsetReg; 2085 2086 if (IsShader) { 2087 PrivateSegmentWaveByteOffsetReg = 2088 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2089 2090 // This is true if the scratch wave byte offset doesn't have a fixed 2091 // location. 2092 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2093 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2094 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2095 } 2096 } else 2097 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2098 2099 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2100 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2101 } 2102 } 2103 2104 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2105 MachineFunction &MF, 2106 const SIRegisterInfo &TRI, 2107 SIMachineFunctionInfo &Info) { 2108 // Now that we've figured out where the scratch register inputs are, see if 2109 // should reserve the arguments and use them directly. 2110 MachineFrameInfo &MFI = MF.getFrameInfo(); 2111 bool HasStackObjects = MFI.hasStackObjects(); 2112 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2113 2114 // Record that we know we have non-spill stack objects so we don't need to 2115 // check all stack objects later. 2116 if (HasStackObjects) 2117 Info.setHasNonSpillStackObjects(true); 2118 2119 // Everything live out of a block is spilled with fast regalloc, so it's 2120 // almost certain that spilling will be required. 2121 if (TM.getOptLevel() == CodeGenOpt::None) 2122 HasStackObjects = true; 2123 2124 // For now assume stack access is needed in any callee functions, so we need 2125 // the scratch registers to pass in. 2126 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2127 2128 if (!ST.enableFlatScratch()) { 2129 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2130 // If we have stack objects, we unquestionably need the private buffer 2131 // resource. For the Code Object V2 ABI, this will be the first 4 user 2132 // SGPR inputs. We can reserve those and use them directly. 2133 2134 Register PrivateSegmentBufferReg = 2135 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2136 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2137 } else { 2138 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2139 // We tentatively reserve the last registers (skipping the last registers 2140 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2141 // we'll replace these with the ones immediately after those which were 2142 // really allocated. In the prologue copies will be inserted from the 2143 // argument to these reserved registers. 2144 2145 // Without HSA, relocations are used for the scratch pointer and the 2146 // buffer resource setup is always inserted in the prologue. Scratch wave 2147 // offset is still in an input SGPR. 2148 Info.setScratchRSrcReg(ReservedBufferReg); 2149 } 2150 } 2151 2152 MachineRegisterInfo &MRI = MF.getRegInfo(); 2153 2154 // For entry functions we have to set up the stack pointer if we use it, 2155 // whereas non-entry functions get this "for free". This means there is no 2156 // intrinsic advantage to using S32 over S34 in cases where we do not have 2157 // calls but do need a frame pointer (i.e. if we are requested to have one 2158 // because frame pointer elimination is disabled). To keep things simple we 2159 // only ever use S32 as the call ABI stack pointer, and so using it does not 2160 // imply we need a separate frame pointer. 2161 // 2162 // Try to use s32 as the SP, but move it if it would interfere with input 2163 // arguments. This won't work with calls though. 2164 // 2165 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2166 // registers. 2167 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2168 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2169 } else { 2170 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2171 2172 if (MFI.hasCalls()) 2173 report_fatal_error("call in graphics shader with too many input SGPRs"); 2174 2175 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2176 if (!MRI.isLiveIn(Reg)) { 2177 Info.setStackPtrOffsetReg(Reg); 2178 break; 2179 } 2180 } 2181 2182 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2183 report_fatal_error("failed to find register for SP"); 2184 } 2185 2186 // hasFP should be accurate for entry functions even before the frame is 2187 // finalized, because it does not rely on the known stack size, only 2188 // properties like whether variable sized objects are present. 2189 if (ST.getFrameLowering()->hasFP(MF)) { 2190 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2191 } 2192 } 2193 2194 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2195 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2196 return !Info->isEntryFunction(); 2197 } 2198 2199 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2200 2201 } 2202 2203 void SITargetLowering::insertCopiesSplitCSR( 2204 MachineBasicBlock *Entry, 2205 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2206 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2207 2208 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2209 if (!IStart) 2210 return; 2211 2212 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2213 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2214 MachineBasicBlock::iterator MBBI = Entry->begin(); 2215 for (const MCPhysReg *I = IStart; *I; ++I) { 2216 const TargetRegisterClass *RC = nullptr; 2217 if (AMDGPU::SReg_64RegClass.contains(*I)) 2218 RC = &AMDGPU::SGPR_64RegClass; 2219 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2220 RC = &AMDGPU::SGPR_32RegClass; 2221 else 2222 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2223 2224 Register NewVR = MRI->createVirtualRegister(RC); 2225 // Create copy from CSR to a virtual register. 2226 Entry->addLiveIn(*I); 2227 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2228 .addReg(*I); 2229 2230 // Insert the copy-back instructions right before the terminator. 2231 for (auto *Exit : Exits) 2232 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2233 TII->get(TargetOpcode::COPY), *I) 2234 .addReg(NewVR); 2235 } 2236 } 2237 2238 SDValue SITargetLowering::LowerFormalArguments( 2239 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2240 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2241 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2242 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2243 2244 MachineFunction &MF = DAG.getMachineFunction(); 2245 const Function &Fn = MF.getFunction(); 2246 FunctionType *FType = MF.getFunction().getFunctionType(); 2247 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2248 2249 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2250 DiagnosticInfoUnsupported NoGraphicsHSA( 2251 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2252 DAG.getContext()->diagnose(NoGraphicsHSA); 2253 return DAG.getEntryNode(); 2254 } 2255 2256 SmallVector<ISD::InputArg, 16> Splits; 2257 SmallVector<CCValAssign, 16> ArgLocs; 2258 BitVector Skipped(Ins.size()); 2259 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2260 *DAG.getContext()); 2261 2262 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2263 bool IsKernel = AMDGPU::isKernel(CallConv); 2264 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2265 2266 if (IsGraphics) { 2267 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2268 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2269 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2270 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2271 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2272 !Info->hasWorkItemIDZ()); 2273 } 2274 2275 if (CallConv == CallingConv::AMDGPU_PS) { 2276 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2277 2278 // At least one interpolation mode must be enabled or else the GPU will 2279 // hang. 2280 // 2281 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2282 // set PSInputAddr, the user wants to enable some bits after the compilation 2283 // based on run-time states. Since we can't know what the final PSInputEna 2284 // will look like, so we shouldn't do anything here and the user should take 2285 // responsibility for the correct programming. 2286 // 2287 // Otherwise, the following restrictions apply: 2288 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2289 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2290 // enabled too. 2291 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2292 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2293 CCInfo.AllocateReg(AMDGPU::VGPR0); 2294 CCInfo.AllocateReg(AMDGPU::VGPR1); 2295 Info->markPSInputAllocated(0); 2296 Info->markPSInputEnabled(0); 2297 } 2298 if (Subtarget->isAmdPalOS()) { 2299 // For isAmdPalOS, the user does not enable some bits after compilation 2300 // based on run-time states; the register values being generated here are 2301 // the final ones set in hardware. Therefore we need to apply the 2302 // workaround to PSInputAddr and PSInputEnable together. (The case where 2303 // a bit is set in PSInputAddr but not PSInputEnable is where the 2304 // frontend set up an input arg for a particular interpolation mode, but 2305 // nothing uses that input arg. Really we should have an earlier pass 2306 // that removes such an arg.) 2307 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2308 if ((PsInputBits & 0x7F) == 0 || 2309 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2310 Info->markPSInputEnabled( 2311 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2312 } 2313 } else if (IsKernel) { 2314 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2315 } else { 2316 Splits.append(Ins.begin(), Ins.end()); 2317 } 2318 2319 if (IsEntryFunc) { 2320 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2321 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2322 } else { 2323 // For the fixed ABI, pass workitem IDs in the last argument register. 2324 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2325 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2326 } 2327 2328 if (IsKernel) { 2329 analyzeFormalArgumentsCompute(CCInfo, Ins); 2330 } else { 2331 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2332 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2333 } 2334 2335 SmallVector<SDValue, 16> Chains; 2336 2337 // FIXME: This is the minimum kernel argument alignment. We should improve 2338 // this to the maximum alignment of the arguments. 2339 // 2340 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2341 // kern arg offset. 2342 const Align KernelArgBaseAlign = Align(16); 2343 2344 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2345 const ISD::InputArg &Arg = Ins[i]; 2346 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2347 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2348 continue; 2349 } 2350 2351 CCValAssign &VA = ArgLocs[ArgIdx++]; 2352 MVT VT = VA.getLocVT(); 2353 2354 if (IsEntryFunc && VA.isMemLoc()) { 2355 VT = Ins[i].VT; 2356 EVT MemVT = VA.getLocVT(); 2357 2358 const uint64_t Offset = VA.getLocMemOffset(); 2359 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2360 2361 if (Arg.Flags.isByRef()) { 2362 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2363 2364 const GCNTargetMachine &TM = 2365 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2366 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2367 Arg.Flags.getPointerAddrSpace())) { 2368 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2369 Arg.Flags.getPointerAddrSpace()); 2370 } 2371 2372 InVals.push_back(Ptr); 2373 continue; 2374 } 2375 2376 SDValue Arg = lowerKernargMemParameter( 2377 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2378 Chains.push_back(Arg.getValue(1)); 2379 2380 auto *ParamTy = 2381 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2382 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2383 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2384 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2385 // On SI local pointers are just offsets into LDS, so they are always 2386 // less than 16-bits. On CI and newer they could potentially be 2387 // real pointers, so we can't guarantee their size. 2388 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2389 DAG.getValueType(MVT::i16)); 2390 } 2391 2392 InVals.push_back(Arg); 2393 continue; 2394 } else if (!IsEntryFunc && VA.isMemLoc()) { 2395 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2396 InVals.push_back(Val); 2397 if (!Arg.Flags.isByVal()) 2398 Chains.push_back(Val.getValue(1)); 2399 continue; 2400 } 2401 2402 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2403 2404 Register Reg = VA.getLocReg(); 2405 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2406 EVT ValVT = VA.getValVT(); 2407 2408 Reg = MF.addLiveIn(Reg, RC); 2409 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2410 2411 if (Arg.Flags.isSRet()) { 2412 // The return object should be reasonably addressable. 2413 2414 // FIXME: This helps when the return is a real sret. If it is a 2415 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2416 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2417 unsigned NumBits 2418 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2419 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2420 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2421 } 2422 2423 // If this is an 8 or 16-bit value, it is really passed promoted 2424 // to 32 bits. Insert an assert[sz]ext to capture this, then 2425 // truncate to the right size. 2426 switch (VA.getLocInfo()) { 2427 case CCValAssign::Full: 2428 break; 2429 case CCValAssign::BCvt: 2430 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2431 break; 2432 case CCValAssign::SExt: 2433 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2434 DAG.getValueType(ValVT)); 2435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2436 break; 2437 case CCValAssign::ZExt: 2438 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2439 DAG.getValueType(ValVT)); 2440 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2441 break; 2442 case CCValAssign::AExt: 2443 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2444 break; 2445 default: 2446 llvm_unreachable("Unknown loc info!"); 2447 } 2448 2449 InVals.push_back(Val); 2450 } 2451 2452 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2453 // Special inputs come after user arguments. 2454 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2455 } 2456 2457 // Start adding system SGPRs. 2458 if (IsEntryFunc) { 2459 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2460 } else { 2461 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2462 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2463 } 2464 2465 auto &ArgUsageInfo = 2466 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2467 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2468 2469 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2470 Info->setBytesInStackArgArea(StackArgSize); 2471 2472 return Chains.empty() ? Chain : 2473 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2474 } 2475 2476 // TODO: If return values can't fit in registers, we should return as many as 2477 // possible in registers before passing on stack. 2478 bool SITargetLowering::CanLowerReturn( 2479 CallingConv::ID CallConv, 2480 MachineFunction &MF, bool IsVarArg, 2481 const SmallVectorImpl<ISD::OutputArg> &Outs, 2482 LLVMContext &Context) const { 2483 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2484 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2485 // for shaders. Vector types should be explicitly handled by CC. 2486 if (AMDGPU::isEntryFunctionCC(CallConv)) 2487 return true; 2488 2489 SmallVector<CCValAssign, 16> RVLocs; 2490 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2491 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2492 } 2493 2494 SDValue 2495 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2496 bool isVarArg, 2497 const SmallVectorImpl<ISD::OutputArg> &Outs, 2498 const SmallVectorImpl<SDValue> &OutVals, 2499 const SDLoc &DL, SelectionDAG &DAG) const { 2500 MachineFunction &MF = DAG.getMachineFunction(); 2501 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2502 2503 if (AMDGPU::isKernel(CallConv)) { 2504 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2505 OutVals, DL, DAG); 2506 } 2507 2508 bool IsShader = AMDGPU::isShader(CallConv); 2509 2510 Info->setIfReturnsVoid(Outs.empty()); 2511 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2512 2513 // CCValAssign - represent the assignment of the return value to a location. 2514 SmallVector<CCValAssign, 48> RVLocs; 2515 SmallVector<ISD::OutputArg, 48> Splits; 2516 2517 // CCState - Info about the registers and stack slots. 2518 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2519 *DAG.getContext()); 2520 2521 // Analyze outgoing return values. 2522 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2523 2524 SDValue Flag; 2525 SmallVector<SDValue, 48> RetOps; 2526 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2527 2528 // Add return address for callable functions. 2529 if (!Info->isEntryFunction()) { 2530 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2531 SDValue ReturnAddrReg = CreateLiveInRegister( 2532 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2533 2534 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2535 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2536 MVT::i64); 2537 Chain = 2538 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2539 Flag = Chain.getValue(1); 2540 RetOps.push_back(ReturnAddrVirtualReg); 2541 } 2542 2543 // Copy the result values into the output registers. 2544 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2545 ++I, ++RealRVLocIdx) { 2546 CCValAssign &VA = RVLocs[I]; 2547 assert(VA.isRegLoc() && "Can only return in registers!"); 2548 // TODO: Partially return in registers if return values don't fit. 2549 SDValue Arg = OutVals[RealRVLocIdx]; 2550 2551 // Copied from other backends. 2552 switch (VA.getLocInfo()) { 2553 case CCValAssign::Full: 2554 break; 2555 case CCValAssign::BCvt: 2556 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2557 break; 2558 case CCValAssign::SExt: 2559 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2560 break; 2561 case CCValAssign::ZExt: 2562 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2563 break; 2564 case CCValAssign::AExt: 2565 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2566 break; 2567 default: 2568 llvm_unreachable("Unknown loc info!"); 2569 } 2570 2571 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2572 Flag = Chain.getValue(1); 2573 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2574 } 2575 2576 // FIXME: Does sret work properly? 2577 if (!Info->isEntryFunction()) { 2578 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2579 const MCPhysReg *I = 2580 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2581 if (I) { 2582 for (; *I; ++I) { 2583 if (AMDGPU::SReg_64RegClass.contains(*I)) 2584 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2585 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2586 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2587 else 2588 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2589 } 2590 } 2591 } 2592 2593 // Update chain and glue. 2594 RetOps[0] = Chain; 2595 if (Flag.getNode()) 2596 RetOps.push_back(Flag); 2597 2598 unsigned Opc = AMDGPUISD::ENDPGM; 2599 if (!IsWaveEnd) 2600 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2601 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2602 } 2603 2604 SDValue SITargetLowering::LowerCallResult( 2605 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2606 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2607 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2608 SDValue ThisVal) const { 2609 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2610 2611 // Assign locations to each value returned by this call. 2612 SmallVector<CCValAssign, 16> RVLocs; 2613 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2614 *DAG.getContext()); 2615 CCInfo.AnalyzeCallResult(Ins, RetCC); 2616 2617 // Copy all of the result registers out of their specified physreg. 2618 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2619 CCValAssign VA = RVLocs[i]; 2620 SDValue Val; 2621 2622 if (VA.isRegLoc()) { 2623 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2624 Chain = Val.getValue(1); 2625 InFlag = Val.getValue(2); 2626 } else if (VA.isMemLoc()) { 2627 report_fatal_error("TODO: return values in memory"); 2628 } else 2629 llvm_unreachable("unknown argument location type"); 2630 2631 switch (VA.getLocInfo()) { 2632 case CCValAssign::Full: 2633 break; 2634 case CCValAssign::BCvt: 2635 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2636 break; 2637 case CCValAssign::ZExt: 2638 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2639 DAG.getValueType(VA.getValVT())); 2640 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2641 break; 2642 case CCValAssign::SExt: 2643 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2644 DAG.getValueType(VA.getValVT())); 2645 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2646 break; 2647 case CCValAssign::AExt: 2648 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2649 break; 2650 default: 2651 llvm_unreachable("Unknown loc info!"); 2652 } 2653 2654 InVals.push_back(Val); 2655 } 2656 2657 return Chain; 2658 } 2659 2660 // Add code to pass special inputs required depending on used features separate 2661 // from the explicit user arguments present in the IR. 2662 void SITargetLowering::passSpecialInputs( 2663 CallLoweringInfo &CLI, 2664 CCState &CCInfo, 2665 const SIMachineFunctionInfo &Info, 2666 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2667 SmallVectorImpl<SDValue> &MemOpChains, 2668 SDValue Chain) const { 2669 // If we don't have a call site, this was a call inserted by 2670 // legalization. These can never use special inputs. 2671 if (!CLI.CB) 2672 return; 2673 2674 SelectionDAG &DAG = CLI.DAG; 2675 const SDLoc &DL = CLI.DL; 2676 2677 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2678 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2679 2680 const AMDGPUFunctionArgInfo *CalleeArgInfo 2681 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2682 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2683 auto &ArgUsageInfo = 2684 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2685 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2686 } 2687 2688 // TODO: Unify with private memory register handling. This is complicated by 2689 // the fact that at least in kernels, the input argument is not necessarily 2690 // in the same location as the input. 2691 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2692 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2693 AMDGPUFunctionArgInfo::QUEUE_PTR, 2694 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2695 AMDGPUFunctionArgInfo::DISPATCH_ID, 2696 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2697 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2698 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2699 }; 2700 2701 for (auto InputID : InputRegs) { 2702 const ArgDescriptor *OutgoingArg; 2703 const TargetRegisterClass *ArgRC; 2704 LLT ArgTy; 2705 2706 std::tie(OutgoingArg, ArgRC, ArgTy) = 2707 CalleeArgInfo->getPreloadedValue(InputID); 2708 if (!OutgoingArg) 2709 continue; 2710 2711 const ArgDescriptor *IncomingArg; 2712 const TargetRegisterClass *IncomingArgRC; 2713 LLT Ty; 2714 std::tie(IncomingArg, IncomingArgRC, Ty) = 2715 CallerArgInfo.getPreloadedValue(InputID); 2716 assert(IncomingArgRC == ArgRC); 2717 2718 // All special arguments are ints for now. 2719 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2720 SDValue InputReg; 2721 2722 if (IncomingArg) { 2723 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2724 } else { 2725 // The implicit arg ptr is special because it doesn't have a corresponding 2726 // input for kernels, and is computed from the kernarg segment pointer. 2727 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2728 InputReg = getImplicitArgPtr(DAG, DL); 2729 } 2730 2731 if (OutgoingArg->isRegister()) { 2732 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2733 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2734 report_fatal_error("failed to allocate implicit input argument"); 2735 } else { 2736 unsigned SpecialArgOffset = 2737 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2738 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2739 SpecialArgOffset); 2740 MemOpChains.push_back(ArgStore); 2741 } 2742 } 2743 2744 // Pack workitem IDs into a single register or pass it as is if already 2745 // packed. 2746 const ArgDescriptor *OutgoingArg; 2747 const TargetRegisterClass *ArgRC; 2748 LLT Ty; 2749 2750 std::tie(OutgoingArg, ArgRC, Ty) = 2751 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2752 if (!OutgoingArg) 2753 std::tie(OutgoingArg, ArgRC, Ty) = 2754 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2755 if (!OutgoingArg) 2756 std::tie(OutgoingArg, ArgRC, Ty) = 2757 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2758 if (!OutgoingArg) 2759 return; 2760 2761 const ArgDescriptor *IncomingArgX = std::get<0>( 2762 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2763 const ArgDescriptor *IncomingArgY = std::get<0>( 2764 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2765 const ArgDescriptor *IncomingArgZ = std::get<0>( 2766 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2767 2768 SDValue InputReg; 2769 SDLoc SL; 2770 2771 // If incoming ids are not packed we need to pack them. 2772 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2773 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2774 2775 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2776 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2777 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2778 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2779 InputReg = InputReg.getNode() ? 2780 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2781 } 2782 2783 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2784 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2785 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2786 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2787 InputReg = InputReg.getNode() ? 2788 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2789 } 2790 2791 if (!InputReg.getNode()) { 2792 // Workitem ids are already packed, any of present incoming arguments 2793 // will carry all required fields. 2794 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2795 IncomingArgX ? *IncomingArgX : 2796 IncomingArgY ? *IncomingArgY : 2797 *IncomingArgZ, ~0u); 2798 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2799 } 2800 2801 if (OutgoingArg->isRegister()) { 2802 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2803 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2804 } else { 2805 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2806 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2807 SpecialArgOffset); 2808 MemOpChains.push_back(ArgStore); 2809 } 2810 } 2811 2812 static bool canGuaranteeTCO(CallingConv::ID CC) { 2813 return CC == CallingConv::Fast; 2814 } 2815 2816 /// Return true if we might ever do TCO for calls with this calling convention. 2817 static bool mayTailCallThisCC(CallingConv::ID CC) { 2818 switch (CC) { 2819 case CallingConv::C: 2820 return true; 2821 default: 2822 return canGuaranteeTCO(CC); 2823 } 2824 } 2825 2826 bool SITargetLowering::isEligibleForTailCallOptimization( 2827 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2828 const SmallVectorImpl<ISD::OutputArg> &Outs, 2829 const SmallVectorImpl<SDValue> &OutVals, 2830 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2831 if (!mayTailCallThisCC(CalleeCC)) 2832 return false; 2833 2834 MachineFunction &MF = DAG.getMachineFunction(); 2835 const Function &CallerF = MF.getFunction(); 2836 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2837 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2838 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2839 2840 // Kernels aren't callable, and don't have a live in return address so it 2841 // doesn't make sense to do a tail call with entry functions. 2842 if (!CallerPreserved) 2843 return false; 2844 2845 bool CCMatch = CallerCC == CalleeCC; 2846 2847 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2848 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2849 return true; 2850 return false; 2851 } 2852 2853 // TODO: Can we handle var args? 2854 if (IsVarArg) 2855 return false; 2856 2857 for (const Argument &Arg : CallerF.args()) { 2858 if (Arg.hasByValAttr()) 2859 return false; 2860 } 2861 2862 LLVMContext &Ctx = *DAG.getContext(); 2863 2864 // Check that the call results are passed in the same way. 2865 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2866 CCAssignFnForCall(CalleeCC, IsVarArg), 2867 CCAssignFnForCall(CallerCC, IsVarArg))) 2868 return false; 2869 2870 // The callee has to preserve all registers the caller needs to preserve. 2871 if (!CCMatch) { 2872 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2873 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2874 return false; 2875 } 2876 2877 // Nothing more to check if the callee is taking no arguments. 2878 if (Outs.empty()) 2879 return true; 2880 2881 SmallVector<CCValAssign, 16> ArgLocs; 2882 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2883 2884 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2885 2886 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2887 // If the stack arguments for this call do not fit into our own save area then 2888 // the call cannot be made tail. 2889 // TODO: Is this really necessary? 2890 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2891 return false; 2892 2893 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2894 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2895 } 2896 2897 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2898 if (!CI->isTailCall()) 2899 return false; 2900 2901 const Function *ParentFn = CI->getParent()->getParent(); 2902 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2903 return false; 2904 return true; 2905 } 2906 2907 // The wave scratch offset register is used as the global base pointer. 2908 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2909 SmallVectorImpl<SDValue> &InVals) const { 2910 SelectionDAG &DAG = CLI.DAG; 2911 const SDLoc &DL = CLI.DL; 2912 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2913 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2914 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2915 SDValue Chain = CLI.Chain; 2916 SDValue Callee = CLI.Callee; 2917 bool &IsTailCall = CLI.IsTailCall; 2918 CallingConv::ID CallConv = CLI.CallConv; 2919 bool IsVarArg = CLI.IsVarArg; 2920 bool IsSibCall = false; 2921 bool IsThisReturn = false; 2922 MachineFunction &MF = DAG.getMachineFunction(); 2923 2924 if (Callee.isUndef() || isNullConstant(Callee)) { 2925 if (!CLI.IsTailCall) { 2926 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2927 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2928 } 2929 2930 return Chain; 2931 } 2932 2933 if (IsVarArg) { 2934 return lowerUnhandledCall(CLI, InVals, 2935 "unsupported call to variadic function "); 2936 } 2937 2938 if (!CLI.CB) 2939 report_fatal_error("unsupported libcall legalization"); 2940 2941 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2942 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2943 return lowerUnhandledCall(CLI, InVals, 2944 "unsupported indirect call to function "); 2945 } 2946 2947 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2948 return lowerUnhandledCall(CLI, InVals, 2949 "unsupported required tail call to function "); 2950 } 2951 2952 if (AMDGPU::isShader(CallConv)) { 2953 // Note the issue is with the CC of the called function, not of the call 2954 // itself. 2955 return lowerUnhandledCall(CLI, InVals, 2956 "unsupported call to a shader function "); 2957 } 2958 2959 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2960 CallConv != CallingConv::AMDGPU_Gfx) { 2961 // Only allow calls with specific calling conventions. 2962 return lowerUnhandledCall(CLI, InVals, 2963 "unsupported calling convention for call from " 2964 "graphics shader of function "); 2965 } 2966 2967 if (IsTailCall) { 2968 IsTailCall = isEligibleForTailCallOptimization( 2969 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2970 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2971 report_fatal_error("failed to perform tail call elimination on a call " 2972 "site marked musttail"); 2973 } 2974 2975 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2976 2977 // A sibling call is one where we're under the usual C ABI and not planning 2978 // to change that but can still do a tail call: 2979 if (!TailCallOpt && IsTailCall) 2980 IsSibCall = true; 2981 2982 if (IsTailCall) 2983 ++NumTailCalls; 2984 } 2985 2986 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2987 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2988 SmallVector<SDValue, 8> MemOpChains; 2989 2990 // Analyze operands of the call, assigning locations to each operand. 2991 SmallVector<CCValAssign, 16> ArgLocs; 2992 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2993 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2994 2995 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 2996 CallConv != CallingConv::AMDGPU_Gfx) { 2997 // With a fixed ABI, allocate fixed registers before user arguments. 2998 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2999 } 3000 3001 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3002 3003 // Get a count of how many bytes are to be pushed on the stack. 3004 unsigned NumBytes = CCInfo.getNextStackOffset(); 3005 3006 if (IsSibCall) { 3007 // Since we're not changing the ABI to make this a tail call, the memory 3008 // operands are already available in the caller's incoming argument space. 3009 NumBytes = 0; 3010 } 3011 3012 // FPDiff is the byte offset of the call's argument area from the callee's. 3013 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3014 // by this amount for a tail call. In a sibling call it must be 0 because the 3015 // caller will deallocate the entire stack and the callee still expects its 3016 // arguments to begin at SP+0. Completely unused for non-tail calls. 3017 int32_t FPDiff = 0; 3018 MachineFrameInfo &MFI = MF.getFrameInfo(); 3019 3020 // Adjust the stack pointer for the new arguments... 3021 // These operations are automatically eliminated by the prolog/epilog pass 3022 if (!IsSibCall) { 3023 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3024 3025 if (!Subtarget->enableFlatScratch()) { 3026 SmallVector<SDValue, 4> CopyFromChains; 3027 3028 // In the HSA case, this should be an identity copy. 3029 SDValue ScratchRSrcReg 3030 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3031 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3032 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3033 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3034 } 3035 } 3036 3037 MVT PtrVT = MVT::i32; 3038 3039 // Walk the register/memloc assignments, inserting copies/loads. 3040 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3041 CCValAssign &VA = ArgLocs[i]; 3042 SDValue Arg = OutVals[i]; 3043 3044 // Promote the value if needed. 3045 switch (VA.getLocInfo()) { 3046 case CCValAssign::Full: 3047 break; 3048 case CCValAssign::BCvt: 3049 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3050 break; 3051 case CCValAssign::ZExt: 3052 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3053 break; 3054 case CCValAssign::SExt: 3055 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3056 break; 3057 case CCValAssign::AExt: 3058 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3059 break; 3060 case CCValAssign::FPExt: 3061 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3062 break; 3063 default: 3064 llvm_unreachable("Unknown loc info!"); 3065 } 3066 3067 if (VA.isRegLoc()) { 3068 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3069 } else { 3070 assert(VA.isMemLoc()); 3071 3072 SDValue DstAddr; 3073 MachinePointerInfo DstInfo; 3074 3075 unsigned LocMemOffset = VA.getLocMemOffset(); 3076 int32_t Offset = LocMemOffset; 3077 3078 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3079 MaybeAlign Alignment; 3080 3081 if (IsTailCall) { 3082 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3083 unsigned OpSize = Flags.isByVal() ? 3084 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3085 3086 // FIXME: We can have better than the minimum byval required alignment. 3087 Alignment = 3088 Flags.isByVal() 3089 ? Flags.getNonZeroByValAlign() 3090 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3091 3092 Offset = Offset + FPDiff; 3093 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3094 3095 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3096 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3097 3098 // Make sure any stack arguments overlapping with where we're storing 3099 // are loaded before this eventual operation. Otherwise they'll be 3100 // clobbered. 3101 3102 // FIXME: Why is this really necessary? This seems to just result in a 3103 // lot of code to copy the stack and write them back to the same 3104 // locations, which are supposed to be immutable? 3105 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3106 } else { 3107 DstAddr = PtrOff; 3108 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3109 Alignment = 3110 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3111 } 3112 3113 if (Outs[i].Flags.isByVal()) { 3114 SDValue SizeNode = 3115 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3116 SDValue Cpy = 3117 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3118 Outs[i].Flags.getNonZeroByValAlign(), 3119 /*isVol = */ false, /*AlwaysInline = */ true, 3120 /*isTailCall = */ false, DstInfo, 3121 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3122 3123 MemOpChains.push_back(Cpy); 3124 } else { 3125 SDValue Store = 3126 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3127 MemOpChains.push_back(Store); 3128 } 3129 } 3130 } 3131 3132 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3133 CallConv != CallingConv::AMDGPU_Gfx) { 3134 // Copy special input registers after user input arguments. 3135 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3136 } 3137 3138 if (!MemOpChains.empty()) 3139 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3140 3141 // Build a sequence of copy-to-reg nodes chained together with token chain 3142 // and flag operands which copy the outgoing args into the appropriate regs. 3143 SDValue InFlag; 3144 for (auto &RegToPass : RegsToPass) { 3145 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3146 RegToPass.second, InFlag); 3147 InFlag = Chain.getValue(1); 3148 } 3149 3150 3151 SDValue PhysReturnAddrReg; 3152 if (IsTailCall) { 3153 // Since the return is being combined with the call, we need to pass on the 3154 // return address. 3155 3156 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3157 SDValue ReturnAddrReg = CreateLiveInRegister( 3158 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3159 3160 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3161 MVT::i64); 3162 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3163 InFlag = Chain.getValue(1); 3164 } 3165 3166 // We don't usually want to end the call-sequence here because we would tidy 3167 // the frame up *after* the call, however in the ABI-changing tail-call case 3168 // we've carefully laid out the parameters so that when sp is reset they'll be 3169 // in the correct location. 3170 if (IsTailCall && !IsSibCall) { 3171 Chain = DAG.getCALLSEQ_END(Chain, 3172 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3173 DAG.getTargetConstant(0, DL, MVT::i32), 3174 InFlag, DL); 3175 InFlag = Chain.getValue(1); 3176 } 3177 3178 std::vector<SDValue> Ops; 3179 Ops.push_back(Chain); 3180 Ops.push_back(Callee); 3181 // Add a redundant copy of the callee global which will not be legalized, as 3182 // we need direct access to the callee later. 3183 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3184 const GlobalValue *GV = GSD->getGlobal(); 3185 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3186 } else { 3187 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3188 } 3189 3190 if (IsTailCall) { 3191 // Each tail call may have to adjust the stack by a different amount, so 3192 // this information must travel along with the operation for eventual 3193 // consumption by emitEpilogue. 3194 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3195 3196 Ops.push_back(PhysReturnAddrReg); 3197 } 3198 3199 // Add argument registers to the end of the list so that they are known live 3200 // into the call. 3201 for (auto &RegToPass : RegsToPass) { 3202 Ops.push_back(DAG.getRegister(RegToPass.first, 3203 RegToPass.second.getValueType())); 3204 } 3205 3206 // Add a register mask operand representing the call-preserved registers. 3207 3208 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3209 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3210 assert(Mask && "Missing call preserved mask for calling convention"); 3211 Ops.push_back(DAG.getRegisterMask(Mask)); 3212 3213 if (InFlag.getNode()) 3214 Ops.push_back(InFlag); 3215 3216 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3217 3218 // If we're doing a tall call, use a TC_RETURN here rather than an 3219 // actual call instruction. 3220 if (IsTailCall) { 3221 MFI.setHasTailCall(); 3222 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3223 } 3224 3225 // Returns a chain and a flag for retval copy to use. 3226 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3227 Chain = Call.getValue(0); 3228 InFlag = Call.getValue(1); 3229 3230 uint64_t CalleePopBytes = NumBytes; 3231 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3232 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3233 InFlag, DL); 3234 if (!Ins.empty()) 3235 InFlag = Chain.getValue(1); 3236 3237 // Handle result values, copying them out of physregs into vregs that we 3238 // return. 3239 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3240 InVals, IsThisReturn, 3241 IsThisReturn ? OutVals[0] : SDValue()); 3242 } 3243 3244 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3245 // except for applying the wave size scale to the increment amount. 3246 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3247 SDValue Op, SelectionDAG &DAG) const { 3248 const MachineFunction &MF = DAG.getMachineFunction(); 3249 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3250 3251 SDLoc dl(Op); 3252 EVT VT = Op.getValueType(); 3253 SDValue Tmp1 = Op; 3254 SDValue Tmp2 = Op.getValue(1); 3255 SDValue Tmp3 = Op.getOperand(2); 3256 SDValue Chain = Tmp1.getOperand(0); 3257 3258 Register SPReg = Info->getStackPtrOffsetReg(); 3259 3260 // Chain the dynamic stack allocation so that it doesn't modify the stack 3261 // pointer when other instructions are using the stack. 3262 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3263 3264 SDValue Size = Tmp2.getOperand(1); 3265 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3266 Chain = SP.getValue(1); 3267 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3268 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3269 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3270 unsigned Opc = 3271 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3272 ISD::ADD : ISD::SUB; 3273 3274 SDValue ScaledSize = DAG.getNode( 3275 ISD::SHL, dl, VT, Size, 3276 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3277 3278 Align StackAlign = TFL->getStackAlign(); 3279 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3280 if (Alignment && *Alignment > StackAlign) { 3281 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3282 DAG.getConstant(-(uint64_t)Alignment->value() 3283 << ST.getWavefrontSizeLog2(), 3284 dl, VT)); 3285 } 3286 3287 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3288 Tmp2 = DAG.getCALLSEQ_END( 3289 Chain, DAG.getIntPtrConstant(0, dl, true), 3290 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3291 3292 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3293 } 3294 3295 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3296 SelectionDAG &DAG) const { 3297 // We only handle constant sizes here to allow non-entry block, static sized 3298 // allocas. A truly dynamic value is more difficult to support because we 3299 // don't know if the size value is uniform or not. If the size isn't uniform, 3300 // we would need to do a wave reduction to get the maximum size to know how 3301 // much to increment the uniform stack pointer. 3302 SDValue Size = Op.getOperand(1); 3303 if (isa<ConstantSDNode>(Size)) 3304 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3305 3306 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3307 } 3308 3309 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3310 const MachineFunction &MF) const { 3311 Register Reg = StringSwitch<Register>(RegName) 3312 .Case("m0", AMDGPU::M0) 3313 .Case("exec", AMDGPU::EXEC) 3314 .Case("exec_lo", AMDGPU::EXEC_LO) 3315 .Case("exec_hi", AMDGPU::EXEC_HI) 3316 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3317 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3318 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3319 .Default(Register()); 3320 3321 if (Reg == AMDGPU::NoRegister) { 3322 report_fatal_error(Twine("invalid register name \"" 3323 + StringRef(RegName) + "\".")); 3324 3325 } 3326 3327 if (!Subtarget->hasFlatScrRegister() && 3328 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3329 report_fatal_error(Twine("invalid register \"" 3330 + StringRef(RegName) + "\" for subtarget.")); 3331 } 3332 3333 switch (Reg) { 3334 case AMDGPU::M0: 3335 case AMDGPU::EXEC_LO: 3336 case AMDGPU::EXEC_HI: 3337 case AMDGPU::FLAT_SCR_LO: 3338 case AMDGPU::FLAT_SCR_HI: 3339 if (VT.getSizeInBits() == 32) 3340 return Reg; 3341 break; 3342 case AMDGPU::EXEC: 3343 case AMDGPU::FLAT_SCR: 3344 if (VT.getSizeInBits() == 64) 3345 return Reg; 3346 break; 3347 default: 3348 llvm_unreachable("missing register type checking"); 3349 } 3350 3351 report_fatal_error(Twine("invalid type for register \"" 3352 + StringRef(RegName) + "\".")); 3353 } 3354 3355 // If kill is not the last instruction, split the block so kill is always a 3356 // proper terminator. 3357 MachineBasicBlock * 3358 SITargetLowering::splitKillBlock(MachineInstr &MI, 3359 MachineBasicBlock *BB) const { 3360 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3361 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3362 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3363 return SplitBB; 3364 } 3365 3366 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3367 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3368 // be the first instruction in the remainder block. 3369 // 3370 /// \returns { LoopBody, Remainder } 3371 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3372 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3373 MachineFunction *MF = MBB.getParent(); 3374 MachineBasicBlock::iterator I(&MI); 3375 3376 // To insert the loop we need to split the block. Move everything after this 3377 // point to a new block, and insert a new empty block between the two. 3378 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3379 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3380 MachineFunction::iterator MBBI(MBB); 3381 ++MBBI; 3382 3383 MF->insert(MBBI, LoopBB); 3384 MF->insert(MBBI, RemainderBB); 3385 3386 LoopBB->addSuccessor(LoopBB); 3387 LoopBB->addSuccessor(RemainderBB); 3388 3389 // Move the rest of the block into a new block. 3390 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3391 3392 if (InstInLoop) { 3393 auto Next = std::next(I); 3394 3395 // Move instruction to loop body. 3396 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3397 3398 // Move the rest of the block. 3399 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3400 } else { 3401 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3402 } 3403 3404 MBB.addSuccessor(LoopBB); 3405 3406 return std::make_pair(LoopBB, RemainderBB); 3407 } 3408 3409 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3410 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3411 MachineBasicBlock *MBB = MI.getParent(); 3412 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3413 auto I = MI.getIterator(); 3414 auto E = std::next(I); 3415 3416 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3417 .addImm(0); 3418 3419 MIBundleBuilder Bundler(*MBB, I, E); 3420 finalizeBundle(*MBB, Bundler.begin()); 3421 } 3422 3423 MachineBasicBlock * 3424 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3425 MachineBasicBlock *BB) const { 3426 const DebugLoc &DL = MI.getDebugLoc(); 3427 3428 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3429 3430 MachineBasicBlock *LoopBB; 3431 MachineBasicBlock *RemainderBB; 3432 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3433 3434 // Apparently kill flags are only valid if the def is in the same block? 3435 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3436 Src->setIsKill(false); 3437 3438 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3439 3440 MachineBasicBlock::iterator I = LoopBB->end(); 3441 3442 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3443 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3444 3445 // Clear TRAP_STS.MEM_VIOL 3446 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3447 .addImm(0) 3448 .addImm(EncodedReg); 3449 3450 bundleInstWithWaitcnt(MI); 3451 3452 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3453 3454 // Load and check TRAP_STS.MEM_VIOL 3455 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3456 .addImm(EncodedReg); 3457 3458 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3459 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3460 .addReg(Reg, RegState::Kill) 3461 .addImm(0); 3462 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3463 .addMBB(LoopBB); 3464 3465 return RemainderBB; 3466 } 3467 3468 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3469 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3470 // will only do one iteration. In the worst case, this will loop 64 times. 3471 // 3472 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3473 static MachineBasicBlock::iterator 3474 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3475 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3476 const DebugLoc &DL, const MachineOperand &Idx, 3477 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3478 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3479 Register &SGPRIdxReg) { 3480 3481 MachineFunction *MF = OrigBB.getParent(); 3482 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3483 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3484 MachineBasicBlock::iterator I = LoopBB.begin(); 3485 3486 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3487 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3488 Register NewExec = MRI.createVirtualRegister(BoolRC); 3489 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3490 Register CondReg = MRI.createVirtualRegister(BoolRC); 3491 3492 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3493 .addReg(InitReg) 3494 .addMBB(&OrigBB) 3495 .addReg(ResultReg) 3496 .addMBB(&LoopBB); 3497 3498 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3499 .addReg(InitSaveExecReg) 3500 .addMBB(&OrigBB) 3501 .addReg(NewExec) 3502 .addMBB(&LoopBB); 3503 3504 // Read the next variant <- also loop target. 3505 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3506 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3507 3508 // Compare the just read M0 value to all possible Idx values. 3509 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3510 .addReg(CurrentIdxReg) 3511 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3512 3513 // Update EXEC, save the original EXEC value to VCC. 3514 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3515 : AMDGPU::S_AND_SAVEEXEC_B64), 3516 NewExec) 3517 .addReg(CondReg, RegState::Kill); 3518 3519 MRI.setSimpleHint(NewExec, CondReg); 3520 3521 if (UseGPRIdxMode) { 3522 if (Offset == 0) { 3523 SGPRIdxReg = CurrentIdxReg; 3524 } else { 3525 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3526 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3527 .addReg(CurrentIdxReg, RegState::Kill) 3528 .addImm(Offset); 3529 } 3530 } else { 3531 // Move index from VCC into M0 3532 if (Offset == 0) { 3533 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3534 .addReg(CurrentIdxReg, RegState::Kill); 3535 } else { 3536 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3537 .addReg(CurrentIdxReg, RegState::Kill) 3538 .addImm(Offset); 3539 } 3540 } 3541 3542 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3543 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3544 MachineInstr *InsertPt = 3545 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3546 : AMDGPU::S_XOR_B64_term), Exec) 3547 .addReg(Exec) 3548 .addReg(NewExec); 3549 3550 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3551 // s_cbranch_scc0? 3552 3553 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3554 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3555 .addMBB(&LoopBB); 3556 3557 return InsertPt->getIterator(); 3558 } 3559 3560 // This has slightly sub-optimal regalloc when the source vector is killed by 3561 // the read. The register allocator does not understand that the kill is 3562 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3563 // subregister from it, using 1 more VGPR than necessary. This was saved when 3564 // this was expanded after register allocation. 3565 static MachineBasicBlock::iterator 3566 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3567 unsigned InitResultReg, unsigned PhiReg, int Offset, 3568 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3569 MachineFunction *MF = MBB.getParent(); 3570 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3571 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3572 MachineRegisterInfo &MRI = MF->getRegInfo(); 3573 const DebugLoc &DL = MI.getDebugLoc(); 3574 MachineBasicBlock::iterator I(&MI); 3575 3576 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3577 Register DstReg = MI.getOperand(0).getReg(); 3578 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3579 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3580 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3581 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3582 3583 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3584 3585 // Save the EXEC mask 3586 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3587 .addReg(Exec); 3588 3589 MachineBasicBlock *LoopBB; 3590 MachineBasicBlock *RemainderBB; 3591 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3592 3593 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3594 3595 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3596 InitResultReg, DstReg, PhiReg, TmpExec, 3597 Offset, UseGPRIdxMode, SGPRIdxReg); 3598 3599 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3600 MachineFunction::iterator MBBI(LoopBB); 3601 ++MBBI; 3602 MF->insert(MBBI, LandingPad); 3603 LoopBB->removeSuccessor(RemainderBB); 3604 LandingPad->addSuccessor(RemainderBB); 3605 LoopBB->addSuccessor(LandingPad); 3606 MachineBasicBlock::iterator First = LandingPad->begin(); 3607 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3608 .addReg(SaveExec); 3609 3610 return InsPt; 3611 } 3612 3613 // Returns subreg index, offset 3614 static std::pair<unsigned, int> 3615 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3616 const TargetRegisterClass *SuperRC, 3617 unsigned VecReg, 3618 int Offset) { 3619 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3620 3621 // Skip out of bounds offsets, or else we would end up using an undefined 3622 // register. 3623 if (Offset >= NumElts || Offset < 0) 3624 return std::make_pair(AMDGPU::sub0, Offset); 3625 3626 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3627 } 3628 3629 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3630 MachineRegisterInfo &MRI, MachineInstr &MI, 3631 int Offset) { 3632 MachineBasicBlock *MBB = MI.getParent(); 3633 const DebugLoc &DL = MI.getDebugLoc(); 3634 MachineBasicBlock::iterator I(&MI); 3635 3636 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3637 3638 assert(Idx->getReg() != AMDGPU::NoRegister); 3639 3640 if (Offset == 0) { 3641 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3642 } else { 3643 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3644 .add(*Idx) 3645 .addImm(Offset); 3646 } 3647 } 3648 3649 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3650 MachineRegisterInfo &MRI, MachineInstr &MI, 3651 int Offset) { 3652 MachineBasicBlock *MBB = MI.getParent(); 3653 const DebugLoc &DL = MI.getDebugLoc(); 3654 MachineBasicBlock::iterator I(&MI); 3655 3656 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3657 3658 if (Offset == 0) 3659 return Idx->getReg(); 3660 3661 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3662 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3663 .add(*Idx) 3664 .addImm(Offset); 3665 return Tmp; 3666 } 3667 3668 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3669 MachineBasicBlock &MBB, 3670 const GCNSubtarget &ST) { 3671 const SIInstrInfo *TII = ST.getInstrInfo(); 3672 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3673 MachineFunction *MF = MBB.getParent(); 3674 MachineRegisterInfo &MRI = MF->getRegInfo(); 3675 3676 Register Dst = MI.getOperand(0).getReg(); 3677 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3678 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3679 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3680 3681 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3682 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3683 3684 unsigned SubReg; 3685 std::tie(SubReg, Offset) 3686 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3687 3688 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3689 3690 // Check for a SGPR index. 3691 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3692 MachineBasicBlock::iterator I(&MI); 3693 const DebugLoc &DL = MI.getDebugLoc(); 3694 3695 if (UseGPRIdxMode) { 3696 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3697 // to avoid interfering with other uses, so probably requires a new 3698 // optimization pass. 3699 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3700 3701 const MCInstrDesc &GPRIDXDesc = 3702 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3703 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3704 .addReg(SrcReg) 3705 .addReg(Idx) 3706 .addImm(SubReg); 3707 } else { 3708 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3709 3710 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3711 .addReg(SrcReg, 0, SubReg) 3712 .addReg(SrcReg, RegState::Implicit); 3713 } 3714 3715 MI.eraseFromParent(); 3716 3717 return &MBB; 3718 } 3719 3720 // Control flow needs to be inserted if indexing with a VGPR. 3721 const DebugLoc &DL = MI.getDebugLoc(); 3722 MachineBasicBlock::iterator I(&MI); 3723 3724 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3725 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3726 3727 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3728 3729 Register SGPRIdxReg; 3730 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3731 UseGPRIdxMode, SGPRIdxReg); 3732 3733 MachineBasicBlock *LoopBB = InsPt->getParent(); 3734 3735 if (UseGPRIdxMode) { 3736 const MCInstrDesc &GPRIDXDesc = 3737 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3738 3739 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3740 .addReg(SrcReg) 3741 .addReg(SGPRIdxReg) 3742 .addImm(SubReg); 3743 } else { 3744 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3745 .addReg(SrcReg, 0, SubReg) 3746 .addReg(SrcReg, RegState::Implicit); 3747 } 3748 3749 MI.eraseFromParent(); 3750 3751 return LoopBB; 3752 } 3753 3754 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3755 MachineBasicBlock &MBB, 3756 const GCNSubtarget &ST) { 3757 const SIInstrInfo *TII = ST.getInstrInfo(); 3758 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3759 MachineFunction *MF = MBB.getParent(); 3760 MachineRegisterInfo &MRI = MF->getRegInfo(); 3761 3762 Register Dst = MI.getOperand(0).getReg(); 3763 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3764 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3765 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3766 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3767 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3768 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3769 3770 // This can be an immediate, but will be folded later. 3771 assert(Val->getReg()); 3772 3773 unsigned SubReg; 3774 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3775 SrcVec->getReg(), 3776 Offset); 3777 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3778 3779 if (Idx->getReg() == AMDGPU::NoRegister) { 3780 MachineBasicBlock::iterator I(&MI); 3781 const DebugLoc &DL = MI.getDebugLoc(); 3782 3783 assert(Offset == 0); 3784 3785 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3786 .add(*SrcVec) 3787 .add(*Val) 3788 .addImm(SubReg); 3789 3790 MI.eraseFromParent(); 3791 return &MBB; 3792 } 3793 3794 // Check for a SGPR index. 3795 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3796 MachineBasicBlock::iterator I(&MI); 3797 const DebugLoc &DL = MI.getDebugLoc(); 3798 3799 if (UseGPRIdxMode) { 3800 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3801 3802 const MCInstrDesc &GPRIDXDesc = 3803 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3804 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3805 .addReg(SrcVec->getReg()) 3806 .add(*Val) 3807 .addReg(Idx) 3808 .addImm(SubReg); 3809 } else { 3810 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3811 3812 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3813 TRI.getRegSizeInBits(*VecRC), 32, false); 3814 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3815 .addReg(SrcVec->getReg()) 3816 .add(*Val) 3817 .addImm(SubReg); 3818 } 3819 MI.eraseFromParent(); 3820 return &MBB; 3821 } 3822 3823 // Control flow needs to be inserted if indexing with a VGPR. 3824 if (Val->isReg()) 3825 MRI.clearKillFlags(Val->getReg()); 3826 3827 const DebugLoc &DL = MI.getDebugLoc(); 3828 3829 Register PhiReg = MRI.createVirtualRegister(VecRC); 3830 3831 Register SGPRIdxReg; 3832 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3833 UseGPRIdxMode, SGPRIdxReg); 3834 MachineBasicBlock *LoopBB = InsPt->getParent(); 3835 3836 if (UseGPRIdxMode) { 3837 const MCInstrDesc &GPRIDXDesc = 3838 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3839 3840 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3841 .addReg(PhiReg) 3842 .add(*Val) 3843 .addReg(SGPRIdxReg) 3844 .addImm(AMDGPU::sub0); 3845 } else { 3846 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3847 TRI.getRegSizeInBits(*VecRC), 32, false); 3848 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3849 .addReg(PhiReg) 3850 .add(*Val) 3851 .addImm(AMDGPU::sub0); 3852 } 3853 3854 MI.eraseFromParent(); 3855 return LoopBB; 3856 } 3857 3858 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3859 MachineInstr &MI, MachineBasicBlock *BB) const { 3860 3861 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3862 MachineFunction *MF = BB->getParent(); 3863 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3864 3865 switch (MI.getOpcode()) { 3866 case AMDGPU::S_UADDO_PSEUDO: 3867 case AMDGPU::S_USUBO_PSEUDO: { 3868 const DebugLoc &DL = MI.getDebugLoc(); 3869 MachineOperand &Dest0 = MI.getOperand(0); 3870 MachineOperand &Dest1 = MI.getOperand(1); 3871 MachineOperand &Src0 = MI.getOperand(2); 3872 MachineOperand &Src1 = MI.getOperand(3); 3873 3874 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3875 ? AMDGPU::S_ADD_I32 3876 : AMDGPU::S_SUB_I32; 3877 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3878 3879 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3880 .addImm(1) 3881 .addImm(0); 3882 3883 MI.eraseFromParent(); 3884 return BB; 3885 } 3886 case AMDGPU::S_ADD_U64_PSEUDO: 3887 case AMDGPU::S_SUB_U64_PSEUDO: { 3888 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3889 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3890 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3891 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3892 const DebugLoc &DL = MI.getDebugLoc(); 3893 3894 MachineOperand &Dest = MI.getOperand(0); 3895 MachineOperand &Src0 = MI.getOperand(1); 3896 MachineOperand &Src1 = MI.getOperand(2); 3897 3898 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3899 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3900 3901 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3902 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3903 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3904 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3905 3906 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3907 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3908 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3909 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3910 3911 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3912 3913 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3914 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3915 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3916 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3917 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3918 .addReg(DestSub0) 3919 .addImm(AMDGPU::sub0) 3920 .addReg(DestSub1) 3921 .addImm(AMDGPU::sub1); 3922 MI.eraseFromParent(); 3923 return BB; 3924 } 3925 case AMDGPU::V_ADD_U64_PSEUDO: 3926 case AMDGPU::V_SUB_U64_PSEUDO: { 3927 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3928 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3929 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3930 const DebugLoc &DL = MI.getDebugLoc(); 3931 3932 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3933 3934 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3935 3936 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3937 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3938 3939 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3940 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3941 3942 MachineOperand &Dest = MI.getOperand(0); 3943 MachineOperand &Src0 = MI.getOperand(1); 3944 MachineOperand &Src1 = MI.getOperand(2); 3945 3946 const TargetRegisterClass *Src0RC = Src0.isReg() 3947 ? MRI.getRegClass(Src0.getReg()) 3948 : &AMDGPU::VReg_64RegClass; 3949 const TargetRegisterClass *Src1RC = Src1.isReg() 3950 ? MRI.getRegClass(Src1.getReg()) 3951 : &AMDGPU::VReg_64RegClass; 3952 3953 const TargetRegisterClass *Src0SubRC = 3954 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3955 const TargetRegisterClass *Src1SubRC = 3956 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3957 3958 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3959 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3960 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3961 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3962 3963 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3964 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3965 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3966 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3967 3968 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3969 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3970 .addReg(CarryReg, RegState::Define) 3971 .add(SrcReg0Sub0) 3972 .add(SrcReg1Sub0) 3973 .addImm(0); // clamp bit 3974 3975 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3976 MachineInstr *HiHalf = 3977 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3978 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3979 .add(SrcReg0Sub1) 3980 .add(SrcReg1Sub1) 3981 .addReg(CarryReg, RegState::Kill) 3982 .addImm(0); // clamp bit 3983 3984 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3985 .addReg(DestSub0) 3986 .addImm(AMDGPU::sub0) 3987 .addReg(DestSub1) 3988 .addImm(AMDGPU::sub1); 3989 TII->legalizeOperands(*LoHalf); 3990 TII->legalizeOperands(*HiHalf); 3991 MI.eraseFromParent(); 3992 return BB; 3993 } 3994 case AMDGPU::S_ADD_CO_PSEUDO: 3995 case AMDGPU::S_SUB_CO_PSEUDO: { 3996 // This pseudo has a chance to be selected 3997 // only from uniform add/subcarry node. All the VGPR operands 3998 // therefore assumed to be splat vectors. 3999 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4000 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4001 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4002 MachineBasicBlock::iterator MII = MI; 4003 const DebugLoc &DL = MI.getDebugLoc(); 4004 MachineOperand &Dest = MI.getOperand(0); 4005 MachineOperand &CarryDest = MI.getOperand(1); 4006 MachineOperand &Src0 = MI.getOperand(2); 4007 MachineOperand &Src1 = MI.getOperand(3); 4008 MachineOperand &Src2 = MI.getOperand(4); 4009 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4010 ? AMDGPU::S_ADDC_U32 4011 : AMDGPU::S_SUBB_U32; 4012 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4013 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4014 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4015 .addReg(Src0.getReg()); 4016 Src0.setReg(RegOp0); 4017 } 4018 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4019 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4020 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4021 .addReg(Src1.getReg()); 4022 Src1.setReg(RegOp1); 4023 } 4024 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4025 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4026 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4027 .addReg(Src2.getReg()); 4028 Src2.setReg(RegOp2); 4029 } 4030 4031 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4032 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4033 if (ST.hasScalarCompareEq64()) { 4034 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4035 .addReg(Src2.getReg()) 4036 .addImm(0); 4037 } else { 4038 const TargetRegisterClass *SubRC = 4039 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4040 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4041 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4042 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4043 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4044 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4045 4046 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4047 .add(Src2Sub0) 4048 .add(Src2Sub1); 4049 4050 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4051 .addReg(Src2_32, RegState::Kill) 4052 .addImm(0); 4053 } 4054 } else { 4055 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4056 .addReg(Src2.getReg()) 4057 .addImm(0); 4058 } 4059 4060 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4061 4062 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4063 .addReg(AMDGPU::SCC); 4064 MI.eraseFromParent(); 4065 return BB; 4066 } 4067 case AMDGPU::SI_INIT_M0: { 4068 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4069 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4070 .add(MI.getOperand(0)); 4071 MI.eraseFromParent(); 4072 return BB; 4073 } 4074 case AMDGPU::SI_INIT_EXEC: 4075 // This should be before all vector instructions. 4076 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4077 AMDGPU::EXEC) 4078 .addImm(MI.getOperand(0).getImm()); 4079 MI.eraseFromParent(); 4080 return BB; 4081 4082 case AMDGPU::SI_INIT_EXEC_LO: 4083 // This should be before all vector instructions. 4084 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4085 AMDGPU::EXEC_LO) 4086 .addImm(MI.getOperand(0).getImm()); 4087 MI.eraseFromParent(); 4088 return BB; 4089 4090 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4091 // Extract the thread count from an SGPR input and set EXEC accordingly. 4092 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4093 // 4094 // S_BFE_U32 count, input, {shift, 7} 4095 // S_BFM_B64 exec, count, 0 4096 // S_CMP_EQ_U32 count, 64 4097 // S_CMOV_B64 exec, -1 4098 MachineInstr *FirstMI = &*BB->begin(); 4099 MachineRegisterInfo &MRI = MF->getRegInfo(); 4100 Register InputReg = MI.getOperand(0).getReg(); 4101 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4102 bool Found = false; 4103 4104 // Move the COPY of the input reg to the beginning, so that we can use it. 4105 for (auto I = BB->begin(); I != &MI; I++) { 4106 if (I->getOpcode() != TargetOpcode::COPY || 4107 I->getOperand(0).getReg() != InputReg) 4108 continue; 4109 4110 if (I == FirstMI) { 4111 FirstMI = &*++BB->begin(); 4112 } else { 4113 I->removeFromParent(); 4114 BB->insert(FirstMI, &*I); 4115 } 4116 Found = true; 4117 break; 4118 } 4119 assert(Found); 4120 (void)Found; 4121 4122 // This should be before all vector instructions. 4123 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4124 bool isWave32 = getSubtarget()->isWave32(); 4125 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4126 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4127 .addReg(InputReg) 4128 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4129 BuildMI(*BB, FirstMI, DebugLoc(), 4130 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4131 Exec) 4132 .addReg(CountReg) 4133 .addImm(0); 4134 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4135 .addReg(CountReg, RegState::Kill) 4136 .addImm(getSubtarget()->getWavefrontSize()); 4137 BuildMI(*BB, FirstMI, DebugLoc(), 4138 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4139 Exec) 4140 .addImm(-1); 4141 MI.eraseFromParent(); 4142 return BB; 4143 } 4144 4145 case AMDGPU::GET_GROUPSTATICSIZE: { 4146 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4147 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4148 DebugLoc DL = MI.getDebugLoc(); 4149 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4150 .add(MI.getOperand(0)) 4151 .addImm(MFI->getLDSSize()); 4152 MI.eraseFromParent(); 4153 return BB; 4154 } 4155 case AMDGPU::SI_INDIRECT_SRC_V1: 4156 case AMDGPU::SI_INDIRECT_SRC_V2: 4157 case AMDGPU::SI_INDIRECT_SRC_V4: 4158 case AMDGPU::SI_INDIRECT_SRC_V8: 4159 case AMDGPU::SI_INDIRECT_SRC_V16: 4160 case AMDGPU::SI_INDIRECT_SRC_V32: 4161 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4162 case AMDGPU::SI_INDIRECT_DST_V1: 4163 case AMDGPU::SI_INDIRECT_DST_V2: 4164 case AMDGPU::SI_INDIRECT_DST_V4: 4165 case AMDGPU::SI_INDIRECT_DST_V8: 4166 case AMDGPU::SI_INDIRECT_DST_V16: 4167 case AMDGPU::SI_INDIRECT_DST_V32: 4168 return emitIndirectDst(MI, *BB, *getSubtarget()); 4169 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4170 case AMDGPU::SI_KILL_I1_PSEUDO: 4171 return splitKillBlock(MI, BB); 4172 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4173 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4174 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4175 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4176 4177 Register Dst = MI.getOperand(0).getReg(); 4178 Register Src0 = MI.getOperand(1).getReg(); 4179 Register Src1 = MI.getOperand(2).getReg(); 4180 const DebugLoc &DL = MI.getDebugLoc(); 4181 Register SrcCond = MI.getOperand(3).getReg(); 4182 4183 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4184 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4185 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4186 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4187 4188 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4189 .addReg(SrcCond); 4190 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4191 .addImm(0) 4192 .addReg(Src0, 0, AMDGPU::sub0) 4193 .addImm(0) 4194 .addReg(Src1, 0, AMDGPU::sub0) 4195 .addReg(SrcCondCopy); 4196 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4197 .addImm(0) 4198 .addReg(Src0, 0, AMDGPU::sub1) 4199 .addImm(0) 4200 .addReg(Src1, 0, AMDGPU::sub1) 4201 .addReg(SrcCondCopy); 4202 4203 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4204 .addReg(DstLo) 4205 .addImm(AMDGPU::sub0) 4206 .addReg(DstHi) 4207 .addImm(AMDGPU::sub1); 4208 MI.eraseFromParent(); 4209 return BB; 4210 } 4211 case AMDGPU::SI_BR_UNDEF: { 4212 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4213 const DebugLoc &DL = MI.getDebugLoc(); 4214 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4215 .add(MI.getOperand(0)); 4216 Br->getOperand(1).setIsUndef(true); // read undef SCC 4217 MI.eraseFromParent(); 4218 return BB; 4219 } 4220 case AMDGPU::ADJCALLSTACKUP: 4221 case AMDGPU::ADJCALLSTACKDOWN: { 4222 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4223 MachineInstrBuilder MIB(*MF, &MI); 4224 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4225 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4226 return BB; 4227 } 4228 case AMDGPU::SI_CALL_ISEL: { 4229 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4230 const DebugLoc &DL = MI.getDebugLoc(); 4231 4232 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4233 4234 MachineInstrBuilder MIB; 4235 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4236 4237 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4238 MIB.add(MI.getOperand(I)); 4239 4240 MIB.cloneMemRefs(MI); 4241 MI.eraseFromParent(); 4242 return BB; 4243 } 4244 case AMDGPU::V_ADD_CO_U32_e32: 4245 case AMDGPU::V_SUB_CO_U32_e32: 4246 case AMDGPU::V_SUBREV_CO_U32_e32: { 4247 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4248 const DebugLoc &DL = MI.getDebugLoc(); 4249 unsigned Opc = MI.getOpcode(); 4250 4251 bool NeedClampOperand = false; 4252 if (TII->pseudoToMCOpcode(Opc) == -1) { 4253 Opc = AMDGPU::getVOPe64(Opc); 4254 NeedClampOperand = true; 4255 } 4256 4257 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4258 if (TII->isVOP3(*I)) { 4259 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4260 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4261 I.addReg(TRI->getVCC(), RegState::Define); 4262 } 4263 I.add(MI.getOperand(1)) 4264 .add(MI.getOperand(2)); 4265 if (NeedClampOperand) 4266 I.addImm(0); // clamp bit for e64 encoding 4267 4268 TII->legalizeOperands(*I); 4269 4270 MI.eraseFromParent(); 4271 return BB; 4272 } 4273 case AMDGPU::DS_GWS_INIT: 4274 case AMDGPU::DS_GWS_SEMA_V: 4275 case AMDGPU::DS_GWS_SEMA_BR: 4276 case AMDGPU::DS_GWS_SEMA_P: 4277 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4278 case AMDGPU::DS_GWS_BARRIER: 4279 // A s_waitcnt 0 is required to be the instruction immediately following. 4280 if (getSubtarget()->hasGWSAutoReplay()) { 4281 bundleInstWithWaitcnt(MI); 4282 return BB; 4283 } 4284 4285 return emitGWSMemViolTestLoop(MI, BB); 4286 case AMDGPU::S_SETREG_B32: { 4287 // Try to optimize cases that only set the denormal mode or rounding mode. 4288 // 4289 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4290 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4291 // instead. 4292 // 4293 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4294 // allow you to have a no side effect instruction in the output of a 4295 // sideeffecting pattern. 4296 unsigned ID, Offset, Width; 4297 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4298 if (ID != AMDGPU::Hwreg::ID_MODE) 4299 return BB; 4300 4301 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4302 const unsigned SetMask = WidthMask << Offset; 4303 4304 if (getSubtarget()->hasDenormModeInst()) { 4305 unsigned SetDenormOp = 0; 4306 unsigned SetRoundOp = 0; 4307 4308 // The dedicated instructions can only set the whole denorm or round mode 4309 // at once, not a subset of bits in either. 4310 if (SetMask == 4311 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4312 // If this fully sets both the round and denorm mode, emit the two 4313 // dedicated instructions for these. 4314 SetRoundOp = AMDGPU::S_ROUND_MODE; 4315 SetDenormOp = AMDGPU::S_DENORM_MODE; 4316 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4317 SetRoundOp = AMDGPU::S_ROUND_MODE; 4318 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4319 SetDenormOp = AMDGPU::S_DENORM_MODE; 4320 } 4321 4322 if (SetRoundOp || SetDenormOp) { 4323 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4324 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4325 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4326 unsigned ImmVal = Def->getOperand(1).getImm(); 4327 if (SetRoundOp) { 4328 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4329 .addImm(ImmVal & 0xf); 4330 4331 // If we also have the denorm mode, get just the denorm mode bits. 4332 ImmVal >>= 4; 4333 } 4334 4335 if (SetDenormOp) { 4336 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4337 .addImm(ImmVal & 0xf); 4338 } 4339 4340 MI.eraseFromParent(); 4341 return BB; 4342 } 4343 } 4344 } 4345 4346 // If only FP bits are touched, used the no side effects pseudo. 4347 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4348 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4349 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4350 4351 return BB; 4352 } 4353 default: 4354 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4355 } 4356 } 4357 4358 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4359 return isTypeLegal(VT.getScalarType()); 4360 } 4361 4362 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4363 // This currently forces unfolding various combinations of fsub into fma with 4364 // free fneg'd operands. As long as we have fast FMA (controlled by 4365 // isFMAFasterThanFMulAndFAdd), we should perform these. 4366 4367 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4368 // most of these combines appear to be cycle neutral but save on instruction 4369 // count / code size. 4370 return true; 4371 } 4372 4373 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4374 EVT VT) const { 4375 if (!VT.isVector()) { 4376 return MVT::i1; 4377 } 4378 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4379 } 4380 4381 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4382 // TODO: Should i16 be used always if legal? For now it would force VALU 4383 // shifts. 4384 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4385 } 4386 4387 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4388 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4389 ? Ty.changeElementSize(16) 4390 : Ty.changeElementSize(32); 4391 } 4392 4393 // Answering this is somewhat tricky and depends on the specific device which 4394 // have different rates for fma or all f64 operations. 4395 // 4396 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4397 // regardless of which device (although the number of cycles differs between 4398 // devices), so it is always profitable for f64. 4399 // 4400 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4401 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4402 // which we can always do even without fused FP ops since it returns the same 4403 // result as the separate operations and since it is always full 4404 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4405 // however does not support denormals, so we do report fma as faster if we have 4406 // a fast fma device and require denormals. 4407 // 4408 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4409 EVT VT) const { 4410 VT = VT.getScalarType(); 4411 4412 switch (VT.getSimpleVT().SimpleTy) { 4413 case MVT::f32: { 4414 // If mad is not available this depends only on if f32 fma is full rate. 4415 if (!Subtarget->hasMadMacF32Insts()) 4416 return Subtarget->hasFastFMAF32(); 4417 4418 // Otherwise f32 mad is always full rate and returns the same result as 4419 // the separate operations so should be preferred over fma. 4420 // However does not support denomals. 4421 if (hasFP32Denormals(MF)) 4422 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4423 4424 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4425 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4426 } 4427 case MVT::f64: 4428 return true; 4429 case MVT::f16: 4430 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4431 default: 4432 break; 4433 } 4434 4435 return false; 4436 } 4437 4438 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4439 const SDNode *N) const { 4440 // TODO: Check future ftz flag 4441 // v_mad_f32/v_mac_f32 do not support denormals. 4442 EVT VT = N->getValueType(0); 4443 if (VT == MVT::f32) 4444 return Subtarget->hasMadMacF32Insts() && 4445 !hasFP32Denormals(DAG.getMachineFunction()); 4446 if (VT == MVT::f16) { 4447 return Subtarget->hasMadF16() && 4448 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4449 } 4450 4451 return false; 4452 } 4453 4454 //===----------------------------------------------------------------------===// 4455 // Custom DAG Lowering Operations 4456 //===----------------------------------------------------------------------===// 4457 4458 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4459 // wider vector type is legal. 4460 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4461 SelectionDAG &DAG) const { 4462 unsigned Opc = Op.getOpcode(); 4463 EVT VT = Op.getValueType(); 4464 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4465 4466 SDValue Lo, Hi; 4467 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4468 4469 SDLoc SL(Op); 4470 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4471 Op->getFlags()); 4472 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4473 Op->getFlags()); 4474 4475 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4476 } 4477 4478 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4479 // wider vector type is legal. 4480 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4481 SelectionDAG &DAG) const { 4482 unsigned Opc = Op.getOpcode(); 4483 EVT VT = Op.getValueType(); 4484 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4485 4486 SDValue Lo0, Hi0; 4487 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4488 SDValue Lo1, Hi1; 4489 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4490 4491 SDLoc SL(Op); 4492 4493 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4494 Op->getFlags()); 4495 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4496 Op->getFlags()); 4497 4498 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4499 } 4500 4501 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4502 SelectionDAG &DAG) const { 4503 unsigned Opc = Op.getOpcode(); 4504 EVT VT = Op.getValueType(); 4505 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4506 4507 SDValue Lo0, Hi0; 4508 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4509 SDValue Lo1, Hi1; 4510 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4511 SDValue Lo2, Hi2; 4512 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4513 4514 SDLoc SL(Op); 4515 4516 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4517 Op->getFlags()); 4518 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4519 Op->getFlags()); 4520 4521 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4522 } 4523 4524 4525 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4526 switch (Op.getOpcode()) { 4527 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4528 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4529 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4530 case ISD::LOAD: { 4531 SDValue Result = LowerLOAD(Op, DAG); 4532 assert((!Result.getNode() || 4533 Result.getNode()->getNumValues() == 2) && 4534 "Load should return a value and a chain"); 4535 return Result; 4536 } 4537 4538 case ISD::FSIN: 4539 case ISD::FCOS: 4540 return LowerTrig(Op, DAG); 4541 case ISD::SELECT: return LowerSELECT(Op, DAG); 4542 case ISD::FDIV: return LowerFDIV(Op, DAG); 4543 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4544 case ISD::STORE: return LowerSTORE(Op, DAG); 4545 case ISD::GlobalAddress: { 4546 MachineFunction &MF = DAG.getMachineFunction(); 4547 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4548 return LowerGlobalAddress(MFI, Op, DAG); 4549 } 4550 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4551 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4552 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4553 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4554 case ISD::INSERT_SUBVECTOR: 4555 return lowerINSERT_SUBVECTOR(Op, DAG); 4556 case ISD::INSERT_VECTOR_ELT: 4557 return lowerINSERT_VECTOR_ELT(Op, DAG); 4558 case ISD::EXTRACT_VECTOR_ELT: 4559 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4560 case ISD::VECTOR_SHUFFLE: 4561 return lowerVECTOR_SHUFFLE(Op, DAG); 4562 case ISD::BUILD_VECTOR: 4563 return lowerBUILD_VECTOR(Op, DAG); 4564 case ISD::FP_ROUND: 4565 return lowerFP_ROUND(Op, DAG); 4566 case ISD::TRAP: 4567 return lowerTRAP(Op, DAG); 4568 case ISD::DEBUGTRAP: 4569 return lowerDEBUGTRAP(Op, DAG); 4570 case ISD::FABS: 4571 case ISD::FNEG: 4572 case ISD::FCANONICALIZE: 4573 case ISD::BSWAP: 4574 return splitUnaryVectorOp(Op, DAG); 4575 case ISD::FMINNUM: 4576 case ISD::FMAXNUM: 4577 return lowerFMINNUM_FMAXNUM(Op, DAG); 4578 case ISD::FMA: 4579 return splitTernaryVectorOp(Op, DAG); 4580 case ISD::SHL: 4581 case ISD::SRA: 4582 case ISD::SRL: 4583 case ISD::ADD: 4584 case ISD::SUB: 4585 case ISD::MUL: 4586 case ISD::SMIN: 4587 case ISD::SMAX: 4588 case ISD::UMIN: 4589 case ISD::UMAX: 4590 case ISD::FADD: 4591 case ISD::FMUL: 4592 case ISD::FMINNUM_IEEE: 4593 case ISD::FMAXNUM_IEEE: 4594 case ISD::UADDSAT: 4595 case ISD::USUBSAT: 4596 case ISD::SADDSAT: 4597 case ISD::SSUBSAT: 4598 return splitBinaryVectorOp(Op, DAG); 4599 case ISD::SMULO: 4600 case ISD::UMULO: 4601 return lowerXMULO(Op, DAG); 4602 case ISD::DYNAMIC_STACKALLOC: 4603 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4604 } 4605 return SDValue(); 4606 } 4607 4608 // Used for D16: Casts the result of an instruction into the right vector, 4609 // packs values if loads return unpacked values. 4610 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4611 const SDLoc &DL, 4612 SelectionDAG &DAG, bool Unpacked) { 4613 if (!LoadVT.isVector()) 4614 return Result; 4615 4616 // Cast back to the original packed type or to a larger type that is a 4617 // multiple of 32 bit for D16. Widening the return type is a required for 4618 // legalization. 4619 EVT FittingLoadVT = LoadVT; 4620 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4621 FittingLoadVT = 4622 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4623 LoadVT.getVectorNumElements() + 1); 4624 } 4625 4626 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4627 // Truncate to v2i16/v4i16. 4628 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4629 4630 // Workaround legalizer not scalarizing truncate after vector op 4631 // legalization but not creating intermediate vector trunc. 4632 SmallVector<SDValue, 4> Elts; 4633 DAG.ExtractVectorElements(Result, Elts); 4634 for (SDValue &Elt : Elts) 4635 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4636 4637 // Pad illegal v1i16/v3fi6 to v4i16 4638 if ((LoadVT.getVectorNumElements() % 2) == 1) 4639 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4640 4641 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4642 4643 // Bitcast to original type (v2f16/v4f16). 4644 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4645 } 4646 4647 // Cast back to the original packed type. 4648 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4649 } 4650 4651 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4652 MemSDNode *M, 4653 SelectionDAG &DAG, 4654 ArrayRef<SDValue> Ops, 4655 bool IsIntrinsic) const { 4656 SDLoc DL(M); 4657 4658 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4659 EVT LoadVT = M->getValueType(0); 4660 4661 EVT EquivLoadVT = LoadVT; 4662 if (LoadVT.isVector()) { 4663 if (Unpacked) { 4664 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4665 LoadVT.getVectorNumElements()); 4666 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4667 // Widen v3f16 to legal type 4668 EquivLoadVT = 4669 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4670 LoadVT.getVectorNumElements() + 1); 4671 } 4672 } 4673 4674 // Change from v4f16/v2f16 to EquivLoadVT. 4675 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4676 4677 SDValue Load 4678 = DAG.getMemIntrinsicNode( 4679 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4680 VTList, Ops, M->getMemoryVT(), 4681 M->getMemOperand()); 4682 4683 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4684 4685 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4686 } 4687 4688 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4689 SelectionDAG &DAG, 4690 ArrayRef<SDValue> Ops) const { 4691 SDLoc DL(M); 4692 EVT LoadVT = M->getValueType(0); 4693 EVT EltType = LoadVT.getScalarType(); 4694 EVT IntVT = LoadVT.changeTypeToInteger(); 4695 4696 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4697 4698 unsigned Opc = 4699 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4700 4701 if (IsD16) { 4702 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4703 } 4704 4705 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4706 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4707 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4708 4709 if (isTypeLegal(LoadVT)) { 4710 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4711 M->getMemOperand(), DAG); 4712 } 4713 4714 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4715 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4716 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4717 M->getMemOperand(), DAG); 4718 return DAG.getMergeValues( 4719 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4720 DL); 4721 } 4722 4723 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4724 SDNode *N, SelectionDAG &DAG) { 4725 EVT VT = N->getValueType(0); 4726 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4727 unsigned CondCode = CD->getZExtValue(); 4728 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4729 return DAG.getUNDEF(VT); 4730 4731 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4732 4733 SDValue LHS = N->getOperand(1); 4734 SDValue RHS = N->getOperand(2); 4735 4736 SDLoc DL(N); 4737 4738 EVT CmpVT = LHS.getValueType(); 4739 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4740 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4741 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4742 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4743 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4744 } 4745 4746 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4747 4748 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4749 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4750 4751 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4752 DAG.getCondCode(CCOpcode)); 4753 if (VT.bitsEq(CCVT)) 4754 return SetCC; 4755 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4756 } 4757 4758 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4759 SDNode *N, SelectionDAG &DAG) { 4760 EVT VT = N->getValueType(0); 4761 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4762 4763 unsigned CondCode = CD->getZExtValue(); 4764 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4765 return DAG.getUNDEF(VT); 4766 4767 SDValue Src0 = N->getOperand(1); 4768 SDValue Src1 = N->getOperand(2); 4769 EVT CmpVT = Src0.getValueType(); 4770 SDLoc SL(N); 4771 4772 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4773 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4774 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4775 } 4776 4777 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4778 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4779 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4780 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4781 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4782 Src1, DAG.getCondCode(CCOpcode)); 4783 if (VT.bitsEq(CCVT)) 4784 return SetCC; 4785 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4786 } 4787 4788 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4789 SelectionDAG &DAG) { 4790 EVT VT = N->getValueType(0); 4791 SDValue Src = N->getOperand(1); 4792 SDLoc SL(N); 4793 4794 if (Src.getOpcode() == ISD::SETCC) { 4795 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4796 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4797 Src.getOperand(1), Src.getOperand(2)); 4798 } 4799 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4800 // (ballot 0) -> 0 4801 if (Arg->isNullValue()) 4802 return DAG.getConstant(0, SL, VT); 4803 4804 // (ballot 1) -> EXEC/EXEC_LO 4805 if (Arg->isOne()) { 4806 Register Exec; 4807 if (VT.getScalarSizeInBits() == 32) 4808 Exec = AMDGPU::EXEC_LO; 4809 else if (VT.getScalarSizeInBits() == 64) 4810 Exec = AMDGPU::EXEC; 4811 else 4812 return SDValue(); 4813 4814 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4815 } 4816 } 4817 4818 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4819 // ISD::SETNE) 4820 return DAG.getNode( 4821 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4822 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4823 } 4824 4825 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4826 SmallVectorImpl<SDValue> &Results, 4827 SelectionDAG &DAG) const { 4828 switch (N->getOpcode()) { 4829 case ISD::INSERT_VECTOR_ELT: { 4830 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4831 Results.push_back(Res); 4832 return; 4833 } 4834 case ISD::EXTRACT_VECTOR_ELT: { 4835 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4836 Results.push_back(Res); 4837 return; 4838 } 4839 case ISD::INTRINSIC_WO_CHAIN: { 4840 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4841 switch (IID) { 4842 case Intrinsic::amdgcn_cvt_pkrtz: { 4843 SDValue Src0 = N->getOperand(1); 4844 SDValue Src1 = N->getOperand(2); 4845 SDLoc SL(N); 4846 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4847 Src0, Src1); 4848 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4849 return; 4850 } 4851 case Intrinsic::amdgcn_cvt_pknorm_i16: 4852 case Intrinsic::amdgcn_cvt_pknorm_u16: 4853 case Intrinsic::amdgcn_cvt_pk_i16: 4854 case Intrinsic::amdgcn_cvt_pk_u16: { 4855 SDValue Src0 = N->getOperand(1); 4856 SDValue Src1 = N->getOperand(2); 4857 SDLoc SL(N); 4858 unsigned Opcode; 4859 4860 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4861 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4862 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4863 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4864 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4865 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4866 else 4867 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4868 4869 EVT VT = N->getValueType(0); 4870 if (isTypeLegal(VT)) 4871 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4872 else { 4873 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4874 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4875 } 4876 return; 4877 } 4878 } 4879 break; 4880 } 4881 case ISD::INTRINSIC_W_CHAIN: { 4882 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4883 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4884 // FIXME: Hacky 4885 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4886 Results.push_back(Res.getOperand(I)); 4887 } 4888 } else { 4889 Results.push_back(Res); 4890 Results.push_back(Res.getValue(1)); 4891 } 4892 return; 4893 } 4894 4895 break; 4896 } 4897 case ISD::SELECT: { 4898 SDLoc SL(N); 4899 EVT VT = N->getValueType(0); 4900 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4901 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4902 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4903 4904 EVT SelectVT = NewVT; 4905 if (NewVT.bitsLT(MVT::i32)) { 4906 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4907 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4908 SelectVT = MVT::i32; 4909 } 4910 4911 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4912 N->getOperand(0), LHS, RHS); 4913 4914 if (NewVT != SelectVT) 4915 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4916 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4917 return; 4918 } 4919 case ISD::FNEG: { 4920 if (N->getValueType(0) != MVT::v2f16) 4921 break; 4922 4923 SDLoc SL(N); 4924 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4925 4926 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4927 BC, 4928 DAG.getConstant(0x80008000, SL, MVT::i32)); 4929 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4930 return; 4931 } 4932 case ISD::FABS: { 4933 if (N->getValueType(0) != MVT::v2f16) 4934 break; 4935 4936 SDLoc SL(N); 4937 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4938 4939 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4940 BC, 4941 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4942 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4943 return; 4944 } 4945 default: 4946 break; 4947 } 4948 } 4949 4950 /// Helper function for LowerBRCOND 4951 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4952 4953 SDNode *Parent = Value.getNode(); 4954 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4955 I != E; ++I) { 4956 4957 if (I.getUse().get() != Value) 4958 continue; 4959 4960 if (I->getOpcode() == Opcode) 4961 return *I; 4962 } 4963 return nullptr; 4964 } 4965 4966 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4967 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4968 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4969 case Intrinsic::amdgcn_if: 4970 return AMDGPUISD::IF; 4971 case Intrinsic::amdgcn_else: 4972 return AMDGPUISD::ELSE; 4973 case Intrinsic::amdgcn_loop: 4974 return AMDGPUISD::LOOP; 4975 case Intrinsic::amdgcn_end_cf: 4976 llvm_unreachable("should not occur"); 4977 default: 4978 return 0; 4979 } 4980 } 4981 4982 // break, if_break, else_break are all only used as inputs to loop, not 4983 // directly as branch conditions. 4984 return 0; 4985 } 4986 4987 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4988 const Triple &TT = getTargetMachine().getTargetTriple(); 4989 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4990 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4991 AMDGPU::shouldEmitConstantsToTextSection(TT); 4992 } 4993 4994 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4995 // FIXME: Either avoid relying on address space here or change the default 4996 // address space for functions to avoid the explicit check. 4997 return (GV->getValueType()->isFunctionTy() || 4998 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4999 !shouldEmitFixup(GV) && 5000 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5001 } 5002 5003 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5004 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5005 } 5006 5007 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5008 if (!GV->hasExternalLinkage()) 5009 return true; 5010 5011 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5012 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5013 } 5014 5015 /// This transforms the control flow intrinsics to get the branch destination as 5016 /// last parameter, also switches branch target with BR if the need arise 5017 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5018 SelectionDAG &DAG) const { 5019 SDLoc DL(BRCOND); 5020 5021 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5022 SDValue Target = BRCOND.getOperand(2); 5023 SDNode *BR = nullptr; 5024 SDNode *SetCC = nullptr; 5025 5026 if (Intr->getOpcode() == ISD::SETCC) { 5027 // As long as we negate the condition everything is fine 5028 SetCC = Intr; 5029 Intr = SetCC->getOperand(0).getNode(); 5030 5031 } else { 5032 // Get the target from BR if we don't negate the condition 5033 BR = findUser(BRCOND, ISD::BR); 5034 assert(BR && "brcond missing unconditional branch user"); 5035 Target = BR->getOperand(1); 5036 } 5037 5038 unsigned CFNode = isCFIntrinsic(Intr); 5039 if (CFNode == 0) { 5040 // This is a uniform branch so we don't need to legalize. 5041 return BRCOND; 5042 } 5043 5044 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5045 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5046 5047 assert(!SetCC || 5048 (SetCC->getConstantOperandVal(1) == 1 && 5049 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5050 ISD::SETNE)); 5051 5052 // operands of the new intrinsic call 5053 SmallVector<SDValue, 4> Ops; 5054 if (HaveChain) 5055 Ops.push_back(BRCOND.getOperand(0)); 5056 5057 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5058 Ops.push_back(Target); 5059 5060 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5061 5062 // build the new intrinsic call 5063 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5064 5065 if (!HaveChain) { 5066 SDValue Ops[] = { 5067 SDValue(Result, 0), 5068 BRCOND.getOperand(0) 5069 }; 5070 5071 Result = DAG.getMergeValues(Ops, DL).getNode(); 5072 } 5073 5074 if (BR) { 5075 // Give the branch instruction our target 5076 SDValue Ops[] = { 5077 BR->getOperand(0), 5078 BRCOND.getOperand(2) 5079 }; 5080 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5081 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5082 } 5083 5084 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5085 5086 // Copy the intrinsic results to registers 5087 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5088 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5089 if (!CopyToReg) 5090 continue; 5091 5092 Chain = DAG.getCopyToReg( 5093 Chain, DL, 5094 CopyToReg->getOperand(1), 5095 SDValue(Result, i - 1), 5096 SDValue()); 5097 5098 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5099 } 5100 5101 // Remove the old intrinsic from the chain 5102 DAG.ReplaceAllUsesOfValueWith( 5103 SDValue(Intr, Intr->getNumValues() - 1), 5104 Intr->getOperand(0)); 5105 5106 return Chain; 5107 } 5108 5109 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5110 SelectionDAG &DAG) const { 5111 MVT VT = Op.getSimpleValueType(); 5112 SDLoc DL(Op); 5113 // Checking the depth 5114 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5115 return DAG.getConstant(0, DL, VT); 5116 5117 MachineFunction &MF = DAG.getMachineFunction(); 5118 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5119 // Check for kernel and shader functions 5120 if (Info->isEntryFunction()) 5121 return DAG.getConstant(0, DL, VT); 5122 5123 MachineFrameInfo &MFI = MF.getFrameInfo(); 5124 // There is a call to @llvm.returnaddress in this function 5125 MFI.setReturnAddressIsTaken(true); 5126 5127 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5128 // Get the return address reg and mark it as an implicit live-in 5129 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5130 5131 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5132 } 5133 5134 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5135 SDValue Op, 5136 const SDLoc &DL, 5137 EVT VT) const { 5138 return Op.getValueType().bitsLE(VT) ? 5139 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5140 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5141 DAG.getTargetConstant(0, DL, MVT::i32)); 5142 } 5143 5144 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5145 assert(Op.getValueType() == MVT::f16 && 5146 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5147 5148 SDValue Src = Op.getOperand(0); 5149 EVT SrcVT = Src.getValueType(); 5150 if (SrcVT != MVT::f64) 5151 return Op; 5152 5153 SDLoc DL(Op); 5154 5155 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5156 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5157 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5158 } 5159 5160 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5161 SelectionDAG &DAG) const { 5162 EVT VT = Op.getValueType(); 5163 const MachineFunction &MF = DAG.getMachineFunction(); 5164 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5165 bool IsIEEEMode = Info->getMode().IEEE; 5166 5167 // FIXME: Assert during selection that this is only selected for 5168 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5169 // mode functions, but this happens to be OK since it's only done in cases 5170 // where there is known no sNaN. 5171 if (IsIEEEMode) 5172 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5173 5174 if (VT == MVT::v4f16) 5175 return splitBinaryVectorOp(Op, DAG); 5176 return Op; 5177 } 5178 5179 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5180 EVT VT = Op.getValueType(); 5181 SDLoc SL(Op); 5182 SDValue LHS = Op.getOperand(0); 5183 SDValue RHS = Op.getOperand(1); 5184 bool isSigned = Op.getOpcode() == ISD::SMULO; 5185 5186 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5187 const APInt &C = RHSC->getAPIntValue(); 5188 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5189 if (C.isPowerOf2()) { 5190 // smulo(x, signed_min) is same as umulo(x, signed_min). 5191 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5192 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5193 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5194 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5195 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5196 SL, VT, Result, ShiftAmt), 5197 LHS, ISD::SETNE); 5198 return DAG.getMergeValues({ Result, Overflow }, SL); 5199 } 5200 } 5201 5202 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5203 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5204 SL, VT, LHS, RHS); 5205 5206 SDValue Sign = isSigned 5207 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5208 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5209 : DAG.getConstant(0, SL, VT); 5210 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5211 5212 return DAG.getMergeValues({ Result, Overflow }, SL); 5213 } 5214 5215 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5216 SDLoc SL(Op); 5217 SDValue Chain = Op.getOperand(0); 5218 5219 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5220 !Subtarget->isTrapHandlerEnabled()) 5221 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5222 5223 MachineFunction &MF = DAG.getMachineFunction(); 5224 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5225 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5226 assert(UserSGPR != AMDGPU::NoRegister); 5227 SDValue QueuePtr = CreateLiveInRegister( 5228 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5229 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5230 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5231 QueuePtr, SDValue()); 5232 SDValue Ops[] = { 5233 ToReg, 5234 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5235 SGPR01, 5236 ToReg.getValue(1) 5237 }; 5238 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5239 } 5240 5241 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5242 SDLoc SL(Op); 5243 SDValue Chain = Op.getOperand(0); 5244 MachineFunction &MF = DAG.getMachineFunction(); 5245 5246 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5247 !Subtarget->isTrapHandlerEnabled()) { 5248 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5249 "debugtrap handler not supported", 5250 Op.getDebugLoc(), 5251 DS_Warning); 5252 LLVMContext &Ctx = MF.getFunction().getContext(); 5253 Ctx.diagnose(NoTrap); 5254 return Chain; 5255 } 5256 5257 SDValue Ops[] = { 5258 Chain, 5259 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5260 }; 5261 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5262 } 5263 5264 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5265 SelectionDAG &DAG) const { 5266 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5267 if (Subtarget->hasApertureRegs()) { 5268 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5269 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5270 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5271 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5272 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5273 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5274 unsigned Encoding = 5275 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5276 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5277 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5278 5279 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5280 SDValue ApertureReg = SDValue( 5281 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5282 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5283 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5284 } 5285 5286 MachineFunction &MF = DAG.getMachineFunction(); 5287 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5288 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5289 assert(UserSGPR != AMDGPU::NoRegister); 5290 5291 SDValue QueuePtr = CreateLiveInRegister( 5292 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5293 5294 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5295 // private_segment_aperture_base_hi. 5296 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5297 5298 SDValue Ptr = 5299 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5300 5301 // TODO: Use custom target PseudoSourceValue. 5302 // TODO: We should use the value from the IR intrinsic call, but it might not 5303 // be available and how do we get it? 5304 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5305 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5306 commonAlignment(Align(64), StructOffset), 5307 MachineMemOperand::MODereferenceable | 5308 MachineMemOperand::MOInvariant); 5309 } 5310 5311 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5312 SelectionDAG &DAG) const { 5313 SDLoc SL(Op); 5314 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5315 5316 SDValue Src = ASC->getOperand(0); 5317 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5318 5319 const AMDGPUTargetMachine &TM = 5320 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5321 5322 // flat -> local/private 5323 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5324 unsigned DestAS = ASC->getDestAddressSpace(); 5325 5326 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5327 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5328 unsigned NullVal = TM.getNullPointerValue(DestAS); 5329 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5330 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5331 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5332 5333 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5334 NonNull, Ptr, SegmentNullPtr); 5335 } 5336 } 5337 5338 // local/private -> flat 5339 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5340 unsigned SrcAS = ASC->getSrcAddressSpace(); 5341 5342 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5343 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5344 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5345 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5346 5347 SDValue NonNull 5348 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5349 5350 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5351 SDValue CvtPtr 5352 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5353 5354 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5355 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5356 FlatNullPtr); 5357 } 5358 } 5359 5360 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5361 Src.getValueType() == MVT::i64) 5362 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5363 5364 // global <-> flat are no-ops and never emitted. 5365 5366 const MachineFunction &MF = DAG.getMachineFunction(); 5367 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5368 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5369 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5370 5371 return DAG.getUNDEF(ASC->getValueType(0)); 5372 } 5373 5374 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5375 // the small vector and inserting them into the big vector. That is better than 5376 // the default expansion of doing it via a stack slot. Even though the use of 5377 // the stack slot would be optimized away afterwards, the stack slot itself 5378 // remains. 5379 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5380 SelectionDAG &DAG) const { 5381 SDValue Vec = Op.getOperand(0); 5382 SDValue Ins = Op.getOperand(1); 5383 SDValue Idx = Op.getOperand(2); 5384 EVT VecVT = Vec.getValueType(); 5385 EVT InsVT = Ins.getValueType(); 5386 EVT EltVT = VecVT.getVectorElementType(); 5387 unsigned InsNumElts = InsVT.getVectorNumElements(); 5388 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5389 SDLoc SL(Op); 5390 5391 for (unsigned I = 0; I != InsNumElts; ++I) { 5392 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5393 DAG.getConstant(I, SL, MVT::i32)); 5394 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5395 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5396 } 5397 return Vec; 5398 } 5399 5400 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5401 SelectionDAG &DAG) const { 5402 SDValue Vec = Op.getOperand(0); 5403 SDValue InsVal = Op.getOperand(1); 5404 SDValue Idx = Op.getOperand(2); 5405 EVT VecVT = Vec.getValueType(); 5406 EVT EltVT = VecVT.getVectorElementType(); 5407 unsigned VecSize = VecVT.getSizeInBits(); 5408 unsigned EltSize = EltVT.getSizeInBits(); 5409 5410 5411 assert(VecSize <= 64); 5412 5413 unsigned NumElts = VecVT.getVectorNumElements(); 5414 SDLoc SL(Op); 5415 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5416 5417 if (NumElts == 4 && EltSize == 16 && KIdx) { 5418 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5419 5420 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5421 DAG.getConstant(0, SL, MVT::i32)); 5422 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5423 DAG.getConstant(1, SL, MVT::i32)); 5424 5425 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5426 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5427 5428 unsigned Idx = KIdx->getZExtValue(); 5429 bool InsertLo = Idx < 2; 5430 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5431 InsertLo ? LoVec : HiVec, 5432 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5433 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5434 5435 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5436 5437 SDValue Concat = InsertLo ? 5438 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5439 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5440 5441 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5442 } 5443 5444 if (isa<ConstantSDNode>(Idx)) 5445 return SDValue(); 5446 5447 MVT IntVT = MVT::getIntegerVT(VecSize); 5448 5449 // Avoid stack access for dynamic indexing. 5450 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5451 5452 // Create a congruent vector with the target value in each element so that 5453 // the required element can be masked and ORed into the target vector. 5454 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5455 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5456 5457 assert(isPowerOf2_32(EltSize)); 5458 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5459 5460 // Convert vector index to bit-index. 5461 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5462 5463 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5464 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5465 DAG.getConstant(0xffff, SL, IntVT), 5466 ScaledIdx); 5467 5468 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5469 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5470 DAG.getNOT(SL, BFM, IntVT), BCVec); 5471 5472 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5473 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5474 } 5475 5476 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5477 SelectionDAG &DAG) const { 5478 SDLoc SL(Op); 5479 5480 EVT ResultVT = Op.getValueType(); 5481 SDValue Vec = Op.getOperand(0); 5482 SDValue Idx = Op.getOperand(1); 5483 EVT VecVT = Vec.getValueType(); 5484 unsigned VecSize = VecVT.getSizeInBits(); 5485 EVT EltVT = VecVT.getVectorElementType(); 5486 assert(VecSize <= 64); 5487 5488 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5489 5490 // Make sure we do any optimizations that will make it easier to fold 5491 // source modifiers before obscuring it with bit operations. 5492 5493 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5494 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5495 return Combined; 5496 5497 unsigned EltSize = EltVT.getSizeInBits(); 5498 assert(isPowerOf2_32(EltSize)); 5499 5500 MVT IntVT = MVT::getIntegerVT(VecSize); 5501 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5502 5503 // Convert vector index to bit-index (* EltSize) 5504 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5505 5506 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5507 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5508 5509 if (ResultVT == MVT::f16) { 5510 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5511 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5512 } 5513 5514 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5515 } 5516 5517 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5518 assert(Elt % 2 == 0); 5519 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5520 } 5521 5522 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5523 SelectionDAG &DAG) const { 5524 SDLoc SL(Op); 5525 EVT ResultVT = Op.getValueType(); 5526 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5527 5528 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5529 EVT EltVT = PackVT.getVectorElementType(); 5530 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5531 5532 // vector_shuffle <0,1,6,7> lhs, rhs 5533 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5534 // 5535 // vector_shuffle <6,7,2,3> lhs, rhs 5536 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5537 // 5538 // vector_shuffle <6,7,0,1> lhs, rhs 5539 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5540 5541 // Avoid scalarizing when both halves are reading from consecutive elements. 5542 SmallVector<SDValue, 4> Pieces; 5543 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5544 if (elementPairIsContiguous(SVN->getMask(), I)) { 5545 const int Idx = SVN->getMaskElt(I); 5546 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5547 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5548 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5549 PackVT, SVN->getOperand(VecIdx), 5550 DAG.getConstant(EltIdx, SL, MVT::i32)); 5551 Pieces.push_back(SubVec); 5552 } else { 5553 const int Idx0 = SVN->getMaskElt(I); 5554 const int Idx1 = SVN->getMaskElt(I + 1); 5555 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5556 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5557 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5558 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5559 5560 SDValue Vec0 = SVN->getOperand(VecIdx0); 5561 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5562 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5563 5564 SDValue Vec1 = SVN->getOperand(VecIdx1); 5565 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5566 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5567 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5568 } 5569 } 5570 5571 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5572 } 5573 5574 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5575 SelectionDAG &DAG) const { 5576 SDLoc SL(Op); 5577 EVT VT = Op.getValueType(); 5578 5579 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5580 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5581 5582 // Turn into pair of packed build_vectors. 5583 // TODO: Special case for constants that can be materialized with s_mov_b64. 5584 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5585 { Op.getOperand(0), Op.getOperand(1) }); 5586 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5587 { Op.getOperand(2), Op.getOperand(3) }); 5588 5589 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5590 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5591 5592 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5593 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5594 } 5595 5596 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5597 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5598 5599 SDValue Lo = Op.getOperand(0); 5600 SDValue Hi = Op.getOperand(1); 5601 5602 // Avoid adding defined bits with the zero_extend. 5603 if (Hi.isUndef()) { 5604 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5605 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5606 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5607 } 5608 5609 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5610 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5611 5612 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5613 DAG.getConstant(16, SL, MVT::i32)); 5614 if (Lo.isUndef()) 5615 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5616 5617 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5618 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5619 5620 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5621 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5622 } 5623 5624 bool 5625 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5626 // We can fold offsets for anything that doesn't require a GOT relocation. 5627 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5628 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5629 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5630 !shouldEmitGOTReloc(GA->getGlobal()); 5631 } 5632 5633 static SDValue 5634 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5635 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5636 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5637 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5638 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5639 // lowered to the following code sequence: 5640 // 5641 // For constant address space: 5642 // s_getpc_b64 s[0:1] 5643 // s_add_u32 s0, s0, $symbol 5644 // s_addc_u32 s1, s1, 0 5645 // 5646 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5647 // a fixup or relocation is emitted to replace $symbol with a literal 5648 // constant, which is a pc-relative offset from the encoding of the $symbol 5649 // operand to the global variable. 5650 // 5651 // For global address space: 5652 // s_getpc_b64 s[0:1] 5653 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5654 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5655 // 5656 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5657 // fixups or relocations are emitted to replace $symbol@*@lo and 5658 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5659 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5660 // operand to the global variable. 5661 // 5662 // What we want here is an offset from the value returned by s_getpc 5663 // (which is the address of the s_add_u32 instruction) to the global 5664 // variable, but since the encoding of $symbol starts 4 bytes after the start 5665 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5666 // small. This requires us to add 4 to the global variable offset in order to 5667 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5668 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5669 // instruction. 5670 SDValue PtrLo = 5671 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5672 SDValue PtrHi; 5673 if (GAFlags == SIInstrInfo::MO_NONE) { 5674 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5675 } else { 5676 PtrHi = 5677 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5678 } 5679 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5680 } 5681 5682 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5683 SDValue Op, 5684 SelectionDAG &DAG) const { 5685 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5686 SDLoc DL(GSD); 5687 EVT PtrVT = Op.getValueType(); 5688 5689 const GlobalValue *GV = GSD->getGlobal(); 5690 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5691 shouldUseLDSConstAddress(GV)) || 5692 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5693 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5694 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5695 GV->hasExternalLinkage()) { 5696 Type *Ty = GV->getValueType(); 5697 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5698 // zero-sized type in other languages to declare the dynamic shared 5699 // memory which size is not known at the compile time. They will be 5700 // allocated by the runtime and placed directly after the static 5701 // allocated ones. They all share the same offset. 5702 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5703 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5704 // Adjust alignment for that dynamic shared memory array. 5705 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5706 return SDValue( 5707 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5708 } 5709 } 5710 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5711 } 5712 5713 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5714 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5715 SIInstrInfo::MO_ABS32_LO); 5716 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5717 } 5718 5719 if (shouldEmitFixup(GV)) 5720 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5721 else if (shouldEmitPCReloc(GV)) 5722 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5723 SIInstrInfo::MO_REL32); 5724 5725 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5726 SIInstrInfo::MO_GOTPCREL32); 5727 5728 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5729 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5730 const DataLayout &DataLayout = DAG.getDataLayout(); 5731 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5732 MachinePointerInfo PtrInfo 5733 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5734 5735 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5736 MachineMemOperand::MODereferenceable | 5737 MachineMemOperand::MOInvariant); 5738 } 5739 5740 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5741 const SDLoc &DL, SDValue V) const { 5742 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5743 // the destination register. 5744 // 5745 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5746 // so we will end up with redundant moves to m0. 5747 // 5748 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5749 5750 // A Null SDValue creates a glue result. 5751 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5752 V, Chain); 5753 return SDValue(M0, 0); 5754 } 5755 5756 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5757 SDValue Op, 5758 MVT VT, 5759 unsigned Offset) const { 5760 SDLoc SL(Op); 5761 SDValue Param = lowerKernargMemParameter( 5762 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5763 // The local size values will have the hi 16-bits as zero. 5764 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5765 DAG.getValueType(VT)); 5766 } 5767 5768 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5769 EVT VT) { 5770 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5771 "non-hsa intrinsic with hsa target", 5772 DL.getDebugLoc()); 5773 DAG.getContext()->diagnose(BadIntrin); 5774 return DAG.getUNDEF(VT); 5775 } 5776 5777 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5778 EVT VT) { 5779 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5780 "intrinsic not supported on subtarget", 5781 DL.getDebugLoc()); 5782 DAG.getContext()->diagnose(BadIntrin); 5783 return DAG.getUNDEF(VT); 5784 } 5785 5786 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5787 ArrayRef<SDValue> Elts) { 5788 assert(!Elts.empty()); 5789 MVT Type; 5790 unsigned NumElts; 5791 5792 if (Elts.size() == 1) { 5793 Type = MVT::f32; 5794 NumElts = 1; 5795 } else if (Elts.size() == 2) { 5796 Type = MVT::v2f32; 5797 NumElts = 2; 5798 } else if (Elts.size() == 3) { 5799 Type = MVT::v3f32; 5800 NumElts = 3; 5801 } else if (Elts.size() <= 4) { 5802 Type = MVT::v4f32; 5803 NumElts = 4; 5804 } else if (Elts.size() <= 8) { 5805 Type = MVT::v8f32; 5806 NumElts = 8; 5807 } else { 5808 assert(Elts.size() <= 16); 5809 Type = MVT::v16f32; 5810 NumElts = 16; 5811 } 5812 5813 SmallVector<SDValue, 16> VecElts(NumElts); 5814 for (unsigned i = 0; i < Elts.size(); ++i) { 5815 SDValue Elt = Elts[i]; 5816 if (Elt.getValueType() != MVT::f32) 5817 Elt = DAG.getBitcast(MVT::f32, Elt); 5818 VecElts[i] = Elt; 5819 } 5820 for (unsigned i = Elts.size(); i < NumElts; ++i) 5821 VecElts[i] = DAG.getUNDEF(MVT::f32); 5822 5823 if (NumElts == 1) 5824 return VecElts[0]; 5825 return DAG.getBuildVector(Type, DL, VecElts); 5826 } 5827 5828 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5829 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5830 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5831 5832 uint64_t Value = CachePolicyConst->getZExtValue(); 5833 SDLoc DL(CachePolicy); 5834 if (GLC) { 5835 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5836 Value &= ~(uint64_t)0x1; 5837 } 5838 if (SLC) { 5839 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5840 Value &= ~(uint64_t)0x2; 5841 } 5842 if (DLC) { 5843 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5844 Value &= ~(uint64_t)0x4; 5845 } 5846 5847 return Value == 0; 5848 } 5849 5850 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5851 SDValue Src, int ExtraElts) { 5852 EVT SrcVT = Src.getValueType(); 5853 5854 SmallVector<SDValue, 8> Elts; 5855 5856 if (SrcVT.isVector()) 5857 DAG.ExtractVectorElements(Src, Elts); 5858 else 5859 Elts.push_back(Src); 5860 5861 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5862 while (ExtraElts--) 5863 Elts.push_back(Undef); 5864 5865 return DAG.getBuildVector(CastVT, DL, Elts); 5866 } 5867 5868 // Re-construct the required return value for a image load intrinsic. 5869 // This is more complicated due to the optional use TexFailCtrl which means the required 5870 // return type is an aggregate 5871 static SDValue constructRetValue(SelectionDAG &DAG, 5872 MachineSDNode *Result, 5873 ArrayRef<EVT> ResultTypes, 5874 bool IsTexFail, bool Unpacked, bool IsD16, 5875 int DMaskPop, int NumVDataDwords, 5876 const SDLoc &DL, LLVMContext &Context) { 5877 // Determine the required return type. This is the same regardless of IsTexFail flag 5878 EVT ReqRetVT = ResultTypes[0]; 5879 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5880 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5881 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5882 5883 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5884 DMaskPop : (DMaskPop + 1) / 2; 5885 5886 MVT DataDwordVT = NumDataDwords == 1 ? 5887 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5888 5889 MVT MaskPopVT = MaskPopDwords == 1 ? 5890 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5891 5892 SDValue Data(Result, 0); 5893 SDValue TexFail; 5894 5895 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5896 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5897 if (MaskPopVT.isVector()) { 5898 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5899 SDValue(Result, 0), ZeroIdx); 5900 } else { 5901 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5902 SDValue(Result, 0), ZeroIdx); 5903 } 5904 } 5905 5906 if (DataDwordVT.isVector()) 5907 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5908 NumDataDwords - MaskPopDwords); 5909 5910 if (IsD16) 5911 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5912 5913 EVT LegalReqRetVT = ReqRetVT; 5914 if (!ReqRetVT.isVector()) { 5915 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5916 } else { 5917 // We need to widen the return vector to a legal type 5918 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5919 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5920 LegalReqRetVT = 5921 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5922 ReqRetVT.getVectorNumElements() + 1); 5923 } 5924 } 5925 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5926 5927 if (IsTexFail) { 5928 TexFail = 5929 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5930 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5931 5932 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5933 } 5934 5935 if (Result->getNumValues() == 1) 5936 return Data; 5937 5938 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5939 } 5940 5941 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5942 SDValue *LWE, bool &IsTexFail) { 5943 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5944 5945 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5946 if (Value) { 5947 IsTexFail = true; 5948 } 5949 5950 SDLoc DL(TexFailCtrlConst); 5951 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5952 Value &= ~(uint64_t)0x1; 5953 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5954 Value &= ~(uint64_t)0x2; 5955 5956 return Value == 0; 5957 } 5958 5959 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5960 MVT PackVectorVT, 5961 SmallVectorImpl<SDValue> &PackedAddrs, 5962 unsigned DimIdx, unsigned EndIdx, 5963 unsigned NumGradients) { 5964 SDLoc DL(Op); 5965 for (unsigned I = DimIdx; I < EndIdx; I++) { 5966 SDValue Addr = Op.getOperand(I); 5967 5968 // Gradients are packed with undef for each coordinate. 5969 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5970 // 1D: undef,dx/dh; undef,dx/dv 5971 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5972 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5973 if (((I + 1) >= EndIdx) || 5974 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5975 I == DimIdx + NumGradients - 1))) { 5976 if (Addr.getValueType() != MVT::i16) 5977 Addr = DAG.getBitcast(MVT::i16, Addr); 5978 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5979 } else { 5980 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5981 I++; 5982 } 5983 Addr = DAG.getBitcast(MVT::f32, Addr); 5984 PackedAddrs.push_back(Addr); 5985 } 5986 } 5987 5988 SDValue SITargetLowering::lowerImage(SDValue Op, 5989 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5990 SelectionDAG &DAG, bool WithChain) const { 5991 SDLoc DL(Op); 5992 MachineFunction &MF = DAG.getMachineFunction(); 5993 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5994 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5995 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5996 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5997 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5998 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5999 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6000 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6001 unsigned IntrOpcode = Intr->BaseOpcode; 6002 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6003 6004 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 6005 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 6006 bool IsD16 = false; 6007 bool IsG16 = false; 6008 bool IsA16 = false; 6009 SDValue VData; 6010 int NumVDataDwords; 6011 bool AdjustRetType = false; 6012 6013 // Offset of intrinsic arguments 6014 const unsigned ArgOffset = WithChain ? 2 : 1; 6015 6016 unsigned DMask; 6017 unsigned DMaskLanes = 0; 6018 6019 if (BaseOpcode->Atomic) { 6020 VData = Op.getOperand(2); 6021 6022 bool Is64Bit = VData.getValueType() == MVT::i64; 6023 if (BaseOpcode->AtomicX2) { 6024 SDValue VData2 = Op.getOperand(3); 6025 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6026 {VData, VData2}); 6027 if (Is64Bit) 6028 VData = DAG.getBitcast(MVT::v4i32, VData); 6029 6030 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6031 DMask = Is64Bit ? 0xf : 0x3; 6032 NumVDataDwords = Is64Bit ? 4 : 2; 6033 } else { 6034 DMask = Is64Bit ? 0x3 : 0x1; 6035 NumVDataDwords = Is64Bit ? 2 : 1; 6036 } 6037 } else { 6038 auto *DMaskConst = 6039 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6040 DMask = DMaskConst->getZExtValue(); 6041 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6042 6043 if (BaseOpcode->Store) { 6044 VData = Op.getOperand(2); 6045 6046 MVT StoreVT = VData.getSimpleValueType(); 6047 if (StoreVT.getScalarType() == MVT::f16) { 6048 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6049 return Op; // D16 is unsupported for this instruction 6050 6051 IsD16 = true; 6052 VData = handleD16VData(VData, DAG, true); 6053 } 6054 6055 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6056 } else { 6057 // Work out the num dwords based on the dmask popcount and underlying type 6058 // and whether packing is supported. 6059 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6060 if (LoadVT.getScalarType() == MVT::f16) { 6061 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6062 return Op; // D16 is unsupported for this instruction 6063 6064 IsD16 = true; 6065 } 6066 6067 // Confirm that the return type is large enough for the dmask specified 6068 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6069 (!LoadVT.isVector() && DMaskLanes > 1)) 6070 return Op; 6071 6072 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6073 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6074 // instructions. 6075 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6076 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6077 NumVDataDwords = (DMaskLanes + 1) / 2; 6078 else 6079 NumVDataDwords = DMaskLanes; 6080 6081 AdjustRetType = true; 6082 } 6083 } 6084 6085 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6086 SmallVector<SDValue, 4> VAddrs; 6087 6088 // Optimize _L to _LZ when _L is zero 6089 if (LZMappingInfo) { 6090 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6091 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6092 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6093 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6094 VAddrEnd--; // remove 'lod' 6095 } 6096 } 6097 } 6098 6099 // Optimize _mip away, when 'lod' is zero 6100 if (MIPMappingInfo) { 6101 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6102 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6103 if (ConstantLod->isNullValue()) { 6104 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6105 VAddrEnd--; // remove 'mip' 6106 } 6107 } 6108 } 6109 6110 // Push back extra arguments. 6111 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6112 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6113 6114 // Check for 16 bit addresses or derivatives and pack if true. 6115 MVT VAddrVT = 6116 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6117 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6118 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6119 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6120 6121 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6122 VAddrScalarVT = VAddrVT.getScalarType(); 6123 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6124 if (IsA16 || IsG16) { 6125 if (IsA16) { 6126 if (!ST->hasA16()) { 6127 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6128 "support 16 bit addresses\n"); 6129 return Op; 6130 } 6131 if (!IsG16) { 6132 LLVM_DEBUG( 6133 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6134 "need 16 bit derivatives but got 32 bit derivatives\n"); 6135 return Op; 6136 } 6137 } else if (!ST->hasG16()) { 6138 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6139 "support 16 bit derivatives\n"); 6140 return Op; 6141 } 6142 6143 if (BaseOpcode->Gradients && !IsA16) { 6144 if (!ST->hasG16()) { 6145 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6146 "support 16 bit derivatives\n"); 6147 return Op; 6148 } 6149 // Activate g16 6150 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6151 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6152 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6153 } 6154 6155 // Don't compress addresses for G16 6156 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6157 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6158 ArgOffset + Intr->GradientStart, PackEndIdx, 6159 Intr->NumGradients); 6160 6161 if (!IsA16) { 6162 // Add uncompressed address 6163 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6164 VAddrs.push_back(Op.getOperand(I)); 6165 } 6166 } else { 6167 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6168 VAddrs.push_back(Op.getOperand(I)); 6169 } 6170 6171 // If the register allocator cannot place the address registers contiguously 6172 // without introducing moves, then using the non-sequential address encoding 6173 // is always preferable, since it saves VALU instructions and is usually a 6174 // wash in terms of code size or even better. 6175 // 6176 // However, we currently have no way of hinting to the register allocator that 6177 // MIMG addresses should be placed contiguously when it is possible to do so, 6178 // so force non-NSA for the common 2-address case as a heuristic. 6179 // 6180 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6181 // allocation when possible. 6182 bool UseNSA = 6183 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6184 SDValue VAddr; 6185 if (!UseNSA) 6186 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6187 6188 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6189 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6190 SDValue Unorm; 6191 if (!BaseOpcode->Sampler) { 6192 Unorm = True; 6193 } else { 6194 auto UnormConst = 6195 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6196 6197 Unorm = UnormConst->getZExtValue() ? True : False; 6198 } 6199 6200 SDValue TFE; 6201 SDValue LWE; 6202 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6203 bool IsTexFail = false; 6204 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6205 return Op; 6206 6207 if (IsTexFail) { 6208 if (!DMaskLanes) { 6209 // Expecting to get an error flag since TFC is on - and dmask is 0 6210 // Force dmask to be at least 1 otherwise the instruction will fail 6211 DMask = 0x1; 6212 DMaskLanes = 1; 6213 NumVDataDwords = 1; 6214 } 6215 NumVDataDwords += 1; 6216 AdjustRetType = true; 6217 } 6218 6219 // Has something earlier tagged that the return type needs adjusting 6220 // This happens if the instruction is a load or has set TexFailCtrl flags 6221 if (AdjustRetType) { 6222 // NumVDataDwords reflects the true number of dwords required in the return type 6223 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6224 // This is a no-op load. This can be eliminated 6225 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6226 if (isa<MemSDNode>(Op)) 6227 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6228 return Undef; 6229 } 6230 6231 EVT NewVT = NumVDataDwords > 1 ? 6232 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6233 : MVT::i32; 6234 6235 ResultTypes[0] = NewVT; 6236 if (ResultTypes.size() == 3) { 6237 // Original result was aggregate type used for TexFailCtrl results 6238 // The actual instruction returns as a vector type which has now been 6239 // created. Remove the aggregate result. 6240 ResultTypes.erase(&ResultTypes[1]); 6241 } 6242 } 6243 6244 SDValue GLC; 6245 SDValue SLC; 6246 SDValue DLC; 6247 if (BaseOpcode->Atomic) { 6248 GLC = True; // TODO no-return optimization 6249 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6250 DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6251 return Op; 6252 } else { 6253 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6254 DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6255 return Op; 6256 } 6257 6258 SmallVector<SDValue, 26> Ops; 6259 if (BaseOpcode->Store || BaseOpcode->Atomic) 6260 Ops.push_back(VData); // vdata 6261 if (UseNSA) { 6262 for (const SDValue &Addr : VAddrs) 6263 Ops.push_back(Addr); 6264 } else { 6265 Ops.push_back(VAddr); 6266 } 6267 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6268 if (BaseOpcode->Sampler) 6269 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6270 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6271 if (IsGFX10Plus) 6272 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6273 Ops.push_back(Unorm); 6274 if (IsGFX10Plus) 6275 Ops.push_back(DLC); 6276 Ops.push_back(GLC); 6277 Ops.push_back(SLC); 6278 Ops.push_back(IsA16 && // r128, a16 for gfx9 6279 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6280 if (IsGFX10Plus) 6281 Ops.push_back(IsA16 ? True : False); 6282 Ops.push_back(TFE); 6283 Ops.push_back(LWE); 6284 if (!IsGFX10Plus) 6285 Ops.push_back(DimInfo->DA ? True : False); 6286 if (BaseOpcode->HasD16) 6287 Ops.push_back(IsD16 ? True : False); 6288 if (isa<MemSDNode>(Op)) 6289 Ops.push_back(Op.getOperand(0)); // chain 6290 6291 int NumVAddrDwords = 6292 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6293 int Opcode = -1; 6294 6295 if (IsGFX10Plus) { 6296 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6297 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6298 : AMDGPU::MIMGEncGfx10Default, 6299 NumVDataDwords, NumVAddrDwords); 6300 } else { 6301 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6302 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6303 NumVDataDwords, NumVAddrDwords); 6304 if (Opcode == -1) 6305 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6306 NumVDataDwords, NumVAddrDwords); 6307 } 6308 assert(Opcode != -1); 6309 6310 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6311 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6312 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6313 DAG.setNodeMemRefs(NewNode, {MemRef}); 6314 } 6315 6316 if (BaseOpcode->AtomicX2) { 6317 SmallVector<SDValue, 1> Elt; 6318 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6319 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6320 } else if (!BaseOpcode->Store) { 6321 return constructRetValue(DAG, NewNode, 6322 OrigResultTypes, IsTexFail, 6323 Subtarget->hasUnpackedD16VMem(), IsD16, 6324 DMaskLanes, NumVDataDwords, DL, 6325 *DAG.getContext()); 6326 } 6327 6328 return SDValue(NewNode, 0); 6329 } 6330 6331 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6332 SDValue Offset, SDValue CachePolicy, 6333 SelectionDAG &DAG) const { 6334 MachineFunction &MF = DAG.getMachineFunction(); 6335 6336 const DataLayout &DataLayout = DAG.getDataLayout(); 6337 Align Alignment = 6338 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6339 6340 MachineMemOperand *MMO = MF.getMachineMemOperand( 6341 MachinePointerInfo(), 6342 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6343 MachineMemOperand::MOInvariant, 6344 VT.getStoreSize(), Alignment); 6345 6346 if (!Offset->isDivergent()) { 6347 SDValue Ops[] = { 6348 Rsrc, 6349 Offset, // Offset 6350 CachePolicy 6351 }; 6352 6353 // Widen vec3 load to vec4. 6354 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6355 EVT WidenedVT = 6356 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6357 auto WidenedOp = DAG.getMemIntrinsicNode( 6358 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6359 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6360 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6361 DAG.getVectorIdxConstant(0, DL)); 6362 return Subvector; 6363 } 6364 6365 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6366 DAG.getVTList(VT), Ops, VT, MMO); 6367 } 6368 6369 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6370 // assume that the buffer is unswizzled. 6371 SmallVector<SDValue, 4> Loads; 6372 unsigned NumLoads = 1; 6373 MVT LoadVT = VT.getSimpleVT(); 6374 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6375 assert((LoadVT.getScalarType() == MVT::i32 || 6376 LoadVT.getScalarType() == MVT::f32)); 6377 6378 if (NumElts == 8 || NumElts == 16) { 6379 NumLoads = NumElts / 4; 6380 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6381 } 6382 6383 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6384 SDValue Ops[] = { 6385 DAG.getEntryNode(), // Chain 6386 Rsrc, // rsrc 6387 DAG.getConstant(0, DL, MVT::i32), // vindex 6388 {}, // voffset 6389 {}, // soffset 6390 {}, // offset 6391 CachePolicy, // cachepolicy 6392 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6393 }; 6394 6395 // Use the alignment to ensure that the required offsets will fit into the 6396 // immediate offsets. 6397 setBufferOffsets(Offset, DAG, &Ops[3], 6398 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6399 6400 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6401 for (unsigned i = 0; i < NumLoads; ++i) { 6402 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6403 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6404 LoadVT, MMO, DAG)); 6405 } 6406 6407 if (NumElts == 8 || NumElts == 16) 6408 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6409 6410 return Loads[0]; 6411 } 6412 6413 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6414 SelectionDAG &DAG) const { 6415 MachineFunction &MF = DAG.getMachineFunction(); 6416 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6417 6418 EVT VT = Op.getValueType(); 6419 SDLoc DL(Op); 6420 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6421 6422 // TODO: Should this propagate fast-math-flags? 6423 6424 switch (IntrinsicID) { 6425 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6426 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6427 return emitNonHSAIntrinsicError(DAG, DL, VT); 6428 return getPreloadedValue(DAG, *MFI, VT, 6429 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6430 } 6431 case Intrinsic::amdgcn_dispatch_ptr: 6432 case Intrinsic::amdgcn_queue_ptr: { 6433 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6434 DiagnosticInfoUnsupported BadIntrin( 6435 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6436 DL.getDebugLoc()); 6437 DAG.getContext()->diagnose(BadIntrin); 6438 return DAG.getUNDEF(VT); 6439 } 6440 6441 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6442 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6443 return getPreloadedValue(DAG, *MFI, VT, RegID); 6444 } 6445 case Intrinsic::amdgcn_implicitarg_ptr: { 6446 if (MFI->isEntryFunction()) 6447 return getImplicitArgPtr(DAG, DL); 6448 return getPreloadedValue(DAG, *MFI, VT, 6449 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6450 } 6451 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6452 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6453 // This only makes sense to call in a kernel, so just lower to null. 6454 return DAG.getConstant(0, DL, VT); 6455 } 6456 6457 return getPreloadedValue(DAG, *MFI, VT, 6458 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6459 } 6460 case Intrinsic::amdgcn_dispatch_id: { 6461 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6462 } 6463 case Intrinsic::amdgcn_rcp: 6464 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6465 case Intrinsic::amdgcn_rsq: 6466 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6467 case Intrinsic::amdgcn_rsq_legacy: 6468 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6469 return emitRemovedIntrinsicError(DAG, DL, VT); 6470 return SDValue(); 6471 case Intrinsic::amdgcn_rcp_legacy: 6472 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6473 return emitRemovedIntrinsicError(DAG, DL, VT); 6474 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6475 case Intrinsic::amdgcn_rsq_clamp: { 6476 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6477 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6478 6479 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6480 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6481 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6482 6483 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6484 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6485 DAG.getConstantFP(Max, DL, VT)); 6486 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6487 DAG.getConstantFP(Min, DL, VT)); 6488 } 6489 case Intrinsic::r600_read_ngroups_x: 6490 if (Subtarget->isAmdHsaOS()) 6491 return emitNonHSAIntrinsicError(DAG, DL, VT); 6492 6493 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6494 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6495 false); 6496 case Intrinsic::r600_read_ngroups_y: 6497 if (Subtarget->isAmdHsaOS()) 6498 return emitNonHSAIntrinsicError(DAG, DL, VT); 6499 6500 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6501 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6502 false); 6503 case Intrinsic::r600_read_ngroups_z: 6504 if (Subtarget->isAmdHsaOS()) 6505 return emitNonHSAIntrinsicError(DAG, DL, VT); 6506 6507 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6508 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6509 false); 6510 case Intrinsic::r600_read_global_size_x: 6511 if (Subtarget->isAmdHsaOS()) 6512 return emitNonHSAIntrinsicError(DAG, DL, VT); 6513 6514 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6515 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6516 Align(4), false); 6517 case Intrinsic::r600_read_global_size_y: 6518 if (Subtarget->isAmdHsaOS()) 6519 return emitNonHSAIntrinsicError(DAG, DL, VT); 6520 6521 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6522 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6523 Align(4), false); 6524 case Intrinsic::r600_read_global_size_z: 6525 if (Subtarget->isAmdHsaOS()) 6526 return emitNonHSAIntrinsicError(DAG, DL, VT); 6527 6528 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6529 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6530 Align(4), false); 6531 case Intrinsic::r600_read_local_size_x: 6532 if (Subtarget->isAmdHsaOS()) 6533 return emitNonHSAIntrinsicError(DAG, DL, VT); 6534 6535 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6536 SI::KernelInputOffsets::LOCAL_SIZE_X); 6537 case Intrinsic::r600_read_local_size_y: 6538 if (Subtarget->isAmdHsaOS()) 6539 return emitNonHSAIntrinsicError(DAG, DL, VT); 6540 6541 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6542 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6543 case Intrinsic::r600_read_local_size_z: 6544 if (Subtarget->isAmdHsaOS()) 6545 return emitNonHSAIntrinsicError(DAG, DL, VT); 6546 6547 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6548 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6549 case Intrinsic::amdgcn_workgroup_id_x: 6550 return getPreloadedValue(DAG, *MFI, VT, 6551 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6552 case Intrinsic::amdgcn_workgroup_id_y: 6553 return getPreloadedValue(DAG, *MFI, VT, 6554 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6555 case Intrinsic::amdgcn_workgroup_id_z: 6556 return getPreloadedValue(DAG, *MFI, VT, 6557 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6558 case Intrinsic::amdgcn_workitem_id_x: 6559 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6560 SDLoc(DAG.getEntryNode()), 6561 MFI->getArgInfo().WorkItemIDX); 6562 case Intrinsic::amdgcn_workitem_id_y: 6563 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6564 SDLoc(DAG.getEntryNode()), 6565 MFI->getArgInfo().WorkItemIDY); 6566 case Intrinsic::amdgcn_workitem_id_z: 6567 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6568 SDLoc(DAG.getEntryNode()), 6569 MFI->getArgInfo().WorkItemIDZ); 6570 case Intrinsic::amdgcn_wavefrontsize: 6571 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6572 SDLoc(Op), MVT::i32); 6573 case Intrinsic::amdgcn_s_buffer_load: { 6574 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6575 SDValue GLC; 6576 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6577 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6578 IsGFX10Plus ? &DLC : nullptr)) 6579 return Op; 6580 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6581 DAG); 6582 } 6583 case Intrinsic::amdgcn_fdiv_fast: 6584 return lowerFDIV_FAST(Op, DAG); 6585 case Intrinsic::amdgcn_sin: 6586 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6587 6588 case Intrinsic::amdgcn_cos: 6589 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6590 6591 case Intrinsic::amdgcn_mul_u24: 6592 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6593 case Intrinsic::amdgcn_mul_i24: 6594 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6595 6596 case Intrinsic::amdgcn_log_clamp: { 6597 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6598 return SDValue(); 6599 6600 return emitRemovedIntrinsicError(DAG, DL, VT); 6601 } 6602 case Intrinsic::amdgcn_ldexp: 6603 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6604 Op.getOperand(1), Op.getOperand(2)); 6605 6606 case Intrinsic::amdgcn_fract: 6607 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6608 6609 case Intrinsic::amdgcn_class: 6610 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6611 Op.getOperand(1), Op.getOperand(2)); 6612 case Intrinsic::amdgcn_div_fmas: 6613 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6615 Op.getOperand(4)); 6616 6617 case Intrinsic::amdgcn_div_fixup: 6618 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6619 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6620 6621 case Intrinsic::amdgcn_div_scale: { 6622 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6623 6624 // Translate to the operands expected by the machine instruction. The 6625 // first parameter must be the same as the first instruction. 6626 SDValue Numerator = Op.getOperand(1); 6627 SDValue Denominator = Op.getOperand(2); 6628 6629 // Note this order is opposite of the machine instruction's operations, 6630 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6631 // intrinsic has the numerator as the first operand to match a normal 6632 // division operation. 6633 6634 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6635 6636 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6637 Denominator, Numerator); 6638 } 6639 case Intrinsic::amdgcn_icmp: { 6640 // There is a Pat that handles this variant, so return it as-is. 6641 if (Op.getOperand(1).getValueType() == MVT::i1 && 6642 Op.getConstantOperandVal(2) == 0 && 6643 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6644 return Op; 6645 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6646 } 6647 case Intrinsic::amdgcn_fcmp: { 6648 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6649 } 6650 case Intrinsic::amdgcn_ballot: 6651 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6652 case Intrinsic::amdgcn_fmed3: 6653 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6654 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6655 case Intrinsic::amdgcn_fdot2: 6656 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6657 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6658 Op.getOperand(4)); 6659 case Intrinsic::amdgcn_fmul_legacy: 6660 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6661 Op.getOperand(1), Op.getOperand(2)); 6662 case Intrinsic::amdgcn_sffbh: 6663 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6664 case Intrinsic::amdgcn_sbfe: 6665 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6666 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6667 case Intrinsic::amdgcn_ubfe: 6668 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6669 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6670 case Intrinsic::amdgcn_cvt_pkrtz: 6671 case Intrinsic::amdgcn_cvt_pknorm_i16: 6672 case Intrinsic::amdgcn_cvt_pknorm_u16: 6673 case Intrinsic::amdgcn_cvt_pk_i16: 6674 case Intrinsic::amdgcn_cvt_pk_u16: { 6675 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6676 EVT VT = Op.getValueType(); 6677 unsigned Opcode; 6678 6679 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6680 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6681 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6682 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6683 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6684 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6685 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6686 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6687 else 6688 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6689 6690 if (isTypeLegal(VT)) 6691 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6692 6693 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6694 Op.getOperand(1), Op.getOperand(2)); 6695 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6696 } 6697 case Intrinsic::amdgcn_fmad_ftz: 6698 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6699 Op.getOperand(2), Op.getOperand(3)); 6700 6701 case Intrinsic::amdgcn_if_break: 6702 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6703 Op->getOperand(1), Op->getOperand(2)), 0); 6704 6705 case Intrinsic::amdgcn_groupstaticsize: { 6706 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6707 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6708 return Op; 6709 6710 const Module *M = MF.getFunction().getParent(); 6711 const GlobalValue *GV = 6712 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6713 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6714 SIInstrInfo::MO_ABS32_LO); 6715 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6716 } 6717 case Intrinsic::amdgcn_is_shared: 6718 case Intrinsic::amdgcn_is_private: { 6719 SDLoc SL(Op); 6720 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6721 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6722 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6723 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6724 Op.getOperand(1)); 6725 6726 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6727 DAG.getConstant(1, SL, MVT::i32)); 6728 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6729 } 6730 case Intrinsic::amdgcn_alignbit: 6731 return DAG.getNode(ISD::FSHR, DL, VT, 6732 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6733 case Intrinsic::amdgcn_reloc_constant: { 6734 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6735 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6736 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6737 auto RelocSymbol = cast<GlobalVariable>( 6738 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6739 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6740 SIInstrInfo::MO_ABS32_LO); 6741 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6742 } 6743 default: 6744 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6745 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6746 return lowerImage(Op, ImageDimIntr, DAG, false); 6747 6748 return Op; 6749 } 6750 } 6751 6752 // This function computes an appropriate offset to pass to 6753 // MachineMemOperand::setOffset() based on the offset inputs to 6754 // an intrinsic. If any of the offsets are non-contstant or 6755 // if VIndex is non-zero then this function returns 0. Otherwise, 6756 // it returns the sum of VOffset, SOffset, and Offset. 6757 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6758 SDValue SOffset, 6759 SDValue Offset, 6760 SDValue VIndex = SDValue()) { 6761 6762 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6763 !isa<ConstantSDNode>(Offset)) 6764 return 0; 6765 6766 if (VIndex) { 6767 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6768 return 0; 6769 } 6770 6771 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6772 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6773 cast<ConstantSDNode>(Offset)->getSExtValue(); 6774 } 6775 6776 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6777 SelectionDAG &DAG, 6778 unsigned NewOpcode) const { 6779 SDLoc DL(Op); 6780 6781 SDValue VData = Op.getOperand(2); 6782 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6783 SDValue Ops[] = { 6784 Op.getOperand(0), // Chain 6785 VData, // vdata 6786 Op.getOperand(3), // rsrc 6787 DAG.getConstant(0, DL, MVT::i32), // vindex 6788 Offsets.first, // voffset 6789 Op.getOperand(5), // soffset 6790 Offsets.second, // offset 6791 Op.getOperand(6), // cachepolicy 6792 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6793 }; 6794 6795 auto *M = cast<MemSDNode>(Op); 6796 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6797 6798 EVT MemVT = VData.getValueType(); 6799 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6800 M->getMemOperand()); 6801 } 6802 6803 SDValue 6804 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6805 unsigned NewOpcode) const { 6806 SDLoc DL(Op); 6807 6808 SDValue VData = Op.getOperand(2); 6809 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6810 SDValue Ops[] = { 6811 Op.getOperand(0), // Chain 6812 VData, // vdata 6813 Op.getOperand(3), // rsrc 6814 Op.getOperand(4), // vindex 6815 Offsets.first, // voffset 6816 Op.getOperand(6), // soffset 6817 Offsets.second, // offset 6818 Op.getOperand(7), // cachepolicy 6819 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6820 }; 6821 6822 auto *M = cast<MemSDNode>(Op); 6823 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6824 Ops[3])); 6825 6826 EVT MemVT = VData.getValueType(); 6827 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6828 M->getMemOperand()); 6829 } 6830 6831 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6832 SelectionDAG &DAG) const { 6833 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6834 SDLoc DL(Op); 6835 6836 switch (IntrID) { 6837 case Intrinsic::amdgcn_ds_ordered_add: 6838 case Intrinsic::amdgcn_ds_ordered_swap: { 6839 MemSDNode *M = cast<MemSDNode>(Op); 6840 SDValue Chain = M->getOperand(0); 6841 SDValue M0 = M->getOperand(2); 6842 SDValue Value = M->getOperand(3); 6843 unsigned IndexOperand = M->getConstantOperandVal(7); 6844 unsigned WaveRelease = M->getConstantOperandVal(8); 6845 unsigned WaveDone = M->getConstantOperandVal(9); 6846 6847 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6848 IndexOperand &= ~0x3f; 6849 unsigned CountDw = 0; 6850 6851 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6852 CountDw = (IndexOperand >> 24) & 0xf; 6853 IndexOperand &= ~(0xf << 24); 6854 6855 if (CountDw < 1 || CountDw > 4) { 6856 report_fatal_error( 6857 "ds_ordered_count: dword count must be between 1 and 4"); 6858 } 6859 } 6860 6861 if (IndexOperand) 6862 report_fatal_error("ds_ordered_count: bad index operand"); 6863 6864 if (WaveDone && !WaveRelease) 6865 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6866 6867 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6868 unsigned ShaderType = 6869 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6870 unsigned Offset0 = OrderedCountIndex << 2; 6871 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6872 (Instruction << 4); 6873 6874 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6875 Offset1 |= (CountDw - 1) << 6; 6876 6877 unsigned Offset = Offset0 | (Offset1 << 8); 6878 6879 SDValue Ops[] = { 6880 Chain, 6881 Value, 6882 DAG.getTargetConstant(Offset, DL, MVT::i16), 6883 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6884 }; 6885 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6886 M->getVTList(), Ops, M->getMemoryVT(), 6887 M->getMemOperand()); 6888 } 6889 case Intrinsic::amdgcn_ds_fadd: { 6890 MemSDNode *M = cast<MemSDNode>(Op); 6891 unsigned Opc; 6892 switch (IntrID) { 6893 case Intrinsic::amdgcn_ds_fadd: 6894 Opc = ISD::ATOMIC_LOAD_FADD; 6895 break; 6896 } 6897 6898 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6899 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6900 M->getMemOperand()); 6901 } 6902 case Intrinsic::amdgcn_atomic_inc: 6903 case Intrinsic::amdgcn_atomic_dec: 6904 case Intrinsic::amdgcn_ds_fmin: 6905 case Intrinsic::amdgcn_ds_fmax: { 6906 MemSDNode *M = cast<MemSDNode>(Op); 6907 unsigned Opc; 6908 switch (IntrID) { 6909 case Intrinsic::amdgcn_atomic_inc: 6910 Opc = AMDGPUISD::ATOMIC_INC; 6911 break; 6912 case Intrinsic::amdgcn_atomic_dec: 6913 Opc = AMDGPUISD::ATOMIC_DEC; 6914 break; 6915 case Intrinsic::amdgcn_ds_fmin: 6916 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6917 break; 6918 case Intrinsic::amdgcn_ds_fmax: 6919 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6920 break; 6921 default: 6922 llvm_unreachable("Unknown intrinsic!"); 6923 } 6924 SDValue Ops[] = { 6925 M->getOperand(0), // Chain 6926 M->getOperand(2), // Ptr 6927 M->getOperand(3) // Value 6928 }; 6929 6930 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6931 M->getMemoryVT(), M->getMemOperand()); 6932 } 6933 case Intrinsic::amdgcn_buffer_load: 6934 case Intrinsic::amdgcn_buffer_load_format: { 6935 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6936 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6937 unsigned IdxEn = 1; 6938 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6939 IdxEn = Idx->getZExtValue() != 0; 6940 SDValue Ops[] = { 6941 Op.getOperand(0), // Chain 6942 Op.getOperand(2), // rsrc 6943 Op.getOperand(3), // vindex 6944 SDValue(), // voffset -- will be set by setBufferOffsets 6945 SDValue(), // soffset -- will be set by setBufferOffsets 6946 SDValue(), // offset -- will be set by setBufferOffsets 6947 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6948 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6949 }; 6950 6951 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6952 // We don't know the offset if vindex is non-zero, so clear it. 6953 if (IdxEn) 6954 Offset = 0; 6955 6956 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6957 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6958 6959 EVT VT = Op.getValueType(); 6960 EVT IntVT = VT.changeTypeToInteger(); 6961 auto *M = cast<MemSDNode>(Op); 6962 M->getMemOperand()->setOffset(Offset); 6963 EVT LoadVT = Op.getValueType(); 6964 6965 if (LoadVT.getScalarType() == MVT::f16) 6966 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6967 M, DAG, Ops); 6968 6969 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6970 if (LoadVT.getScalarType() == MVT::i8 || 6971 LoadVT.getScalarType() == MVT::i16) 6972 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6973 6974 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6975 M->getMemOperand(), DAG); 6976 } 6977 case Intrinsic::amdgcn_raw_buffer_load: 6978 case Intrinsic::amdgcn_raw_buffer_load_format: { 6979 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6980 6981 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6982 SDValue Ops[] = { 6983 Op.getOperand(0), // Chain 6984 Op.getOperand(2), // rsrc 6985 DAG.getConstant(0, DL, MVT::i32), // vindex 6986 Offsets.first, // voffset 6987 Op.getOperand(4), // soffset 6988 Offsets.second, // offset 6989 Op.getOperand(5), // cachepolicy, swizzled buffer 6990 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6991 }; 6992 6993 auto *M = cast<MemSDNode>(Op); 6994 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6995 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6996 } 6997 case Intrinsic::amdgcn_struct_buffer_load: 6998 case Intrinsic::amdgcn_struct_buffer_load_format: { 6999 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7000 7001 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7002 SDValue Ops[] = { 7003 Op.getOperand(0), // Chain 7004 Op.getOperand(2), // rsrc 7005 Op.getOperand(3), // vindex 7006 Offsets.first, // voffset 7007 Op.getOperand(5), // soffset 7008 Offsets.second, // offset 7009 Op.getOperand(6), // cachepolicy, swizzled buffer 7010 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7011 }; 7012 7013 auto *M = cast<MemSDNode>(Op); 7014 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 7015 Ops[2])); 7016 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7017 } 7018 case Intrinsic::amdgcn_tbuffer_load: { 7019 MemSDNode *M = cast<MemSDNode>(Op); 7020 EVT LoadVT = Op.getValueType(); 7021 7022 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7023 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7024 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7025 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7026 unsigned IdxEn = 1; 7027 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7028 IdxEn = Idx->getZExtValue() != 0; 7029 SDValue Ops[] = { 7030 Op.getOperand(0), // Chain 7031 Op.getOperand(2), // rsrc 7032 Op.getOperand(3), // vindex 7033 Op.getOperand(4), // voffset 7034 Op.getOperand(5), // soffset 7035 Op.getOperand(6), // offset 7036 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7037 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7038 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7039 }; 7040 7041 if (LoadVT.getScalarType() == MVT::f16) 7042 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7043 M, DAG, Ops); 7044 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7045 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7046 DAG); 7047 } 7048 case Intrinsic::amdgcn_raw_tbuffer_load: { 7049 MemSDNode *M = cast<MemSDNode>(Op); 7050 EVT LoadVT = Op.getValueType(); 7051 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7052 7053 SDValue Ops[] = { 7054 Op.getOperand(0), // Chain 7055 Op.getOperand(2), // rsrc 7056 DAG.getConstant(0, DL, MVT::i32), // vindex 7057 Offsets.first, // voffset 7058 Op.getOperand(4), // soffset 7059 Offsets.second, // offset 7060 Op.getOperand(5), // format 7061 Op.getOperand(6), // cachepolicy, swizzled buffer 7062 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7063 }; 7064 7065 if (LoadVT.getScalarType() == MVT::f16) 7066 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7067 M, DAG, Ops); 7068 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7069 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7070 DAG); 7071 } 7072 case Intrinsic::amdgcn_struct_tbuffer_load: { 7073 MemSDNode *M = cast<MemSDNode>(Op); 7074 EVT LoadVT = Op.getValueType(); 7075 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7076 7077 SDValue Ops[] = { 7078 Op.getOperand(0), // Chain 7079 Op.getOperand(2), // rsrc 7080 Op.getOperand(3), // vindex 7081 Offsets.first, // voffset 7082 Op.getOperand(5), // soffset 7083 Offsets.second, // offset 7084 Op.getOperand(6), // format 7085 Op.getOperand(7), // cachepolicy, swizzled buffer 7086 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7087 }; 7088 7089 if (LoadVT.getScalarType() == MVT::f16) 7090 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7091 M, DAG, Ops); 7092 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7093 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7094 DAG); 7095 } 7096 case Intrinsic::amdgcn_buffer_atomic_swap: 7097 case Intrinsic::amdgcn_buffer_atomic_add: 7098 case Intrinsic::amdgcn_buffer_atomic_sub: 7099 case Intrinsic::amdgcn_buffer_atomic_csub: 7100 case Intrinsic::amdgcn_buffer_atomic_smin: 7101 case Intrinsic::amdgcn_buffer_atomic_umin: 7102 case Intrinsic::amdgcn_buffer_atomic_smax: 7103 case Intrinsic::amdgcn_buffer_atomic_umax: 7104 case Intrinsic::amdgcn_buffer_atomic_and: 7105 case Intrinsic::amdgcn_buffer_atomic_or: 7106 case Intrinsic::amdgcn_buffer_atomic_xor: 7107 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7108 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7109 unsigned IdxEn = 1; 7110 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7111 IdxEn = Idx->getZExtValue() != 0; 7112 SDValue Ops[] = { 7113 Op.getOperand(0), // Chain 7114 Op.getOperand(2), // vdata 7115 Op.getOperand(3), // rsrc 7116 Op.getOperand(4), // vindex 7117 SDValue(), // voffset -- will be set by setBufferOffsets 7118 SDValue(), // soffset -- will be set by setBufferOffsets 7119 SDValue(), // offset -- will be set by setBufferOffsets 7120 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7121 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7122 }; 7123 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7124 // We don't know the offset if vindex is non-zero, so clear it. 7125 if (IdxEn) 7126 Offset = 0; 7127 EVT VT = Op.getValueType(); 7128 7129 auto *M = cast<MemSDNode>(Op); 7130 M->getMemOperand()->setOffset(Offset); 7131 unsigned Opcode = 0; 7132 7133 switch (IntrID) { 7134 case Intrinsic::amdgcn_buffer_atomic_swap: 7135 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7136 break; 7137 case Intrinsic::amdgcn_buffer_atomic_add: 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7139 break; 7140 case Intrinsic::amdgcn_buffer_atomic_sub: 7141 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7142 break; 7143 case Intrinsic::amdgcn_buffer_atomic_csub: 7144 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7145 break; 7146 case Intrinsic::amdgcn_buffer_atomic_smin: 7147 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7148 break; 7149 case Intrinsic::amdgcn_buffer_atomic_umin: 7150 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7151 break; 7152 case Intrinsic::amdgcn_buffer_atomic_smax: 7153 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7154 break; 7155 case Intrinsic::amdgcn_buffer_atomic_umax: 7156 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7157 break; 7158 case Intrinsic::amdgcn_buffer_atomic_and: 7159 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7160 break; 7161 case Intrinsic::amdgcn_buffer_atomic_or: 7162 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7163 break; 7164 case Intrinsic::amdgcn_buffer_atomic_xor: 7165 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7166 break; 7167 case Intrinsic::amdgcn_buffer_atomic_fadd: 7168 if (!Op.getValue(0).use_empty()) { 7169 DiagnosticInfoUnsupported 7170 NoFpRet(DAG.getMachineFunction().getFunction(), 7171 "return versions of fp atomics not supported", 7172 DL.getDebugLoc(), DS_Error); 7173 DAG.getContext()->diagnose(NoFpRet); 7174 return SDValue(); 7175 } 7176 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7177 break; 7178 default: 7179 llvm_unreachable("unhandled atomic opcode"); 7180 } 7181 7182 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7183 M->getMemOperand()); 7184 } 7185 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7186 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7187 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7188 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7189 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7190 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7191 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7192 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7193 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7194 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7195 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7196 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7197 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7198 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7199 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7200 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7201 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7202 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7203 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7204 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7205 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7206 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7207 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7208 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7209 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7210 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7211 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7212 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7213 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7214 return lowerStructBufferAtomicIntrin(Op, DAG, 7215 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7216 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7217 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7218 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7219 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7220 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7221 return lowerStructBufferAtomicIntrin(Op, DAG, 7222 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7223 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7224 return lowerStructBufferAtomicIntrin(Op, DAG, 7225 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7226 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7227 return lowerStructBufferAtomicIntrin(Op, DAG, 7228 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7229 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7230 return lowerStructBufferAtomicIntrin(Op, DAG, 7231 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7232 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7233 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7234 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7235 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7236 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7237 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7238 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7239 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7240 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7241 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7242 7243 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7244 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7245 unsigned IdxEn = 1; 7246 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7247 IdxEn = Idx->getZExtValue() != 0; 7248 SDValue Ops[] = { 7249 Op.getOperand(0), // Chain 7250 Op.getOperand(2), // src 7251 Op.getOperand(3), // cmp 7252 Op.getOperand(4), // rsrc 7253 Op.getOperand(5), // vindex 7254 SDValue(), // voffset -- will be set by setBufferOffsets 7255 SDValue(), // soffset -- will be set by setBufferOffsets 7256 SDValue(), // offset -- will be set by setBufferOffsets 7257 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7258 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7259 }; 7260 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7261 // We don't know the offset if vindex is non-zero, so clear it. 7262 if (IdxEn) 7263 Offset = 0; 7264 EVT VT = Op.getValueType(); 7265 auto *M = cast<MemSDNode>(Op); 7266 M->getMemOperand()->setOffset(Offset); 7267 7268 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7269 Op->getVTList(), Ops, VT, M->getMemOperand()); 7270 } 7271 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7272 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7273 SDValue Ops[] = { 7274 Op.getOperand(0), // Chain 7275 Op.getOperand(2), // src 7276 Op.getOperand(3), // cmp 7277 Op.getOperand(4), // rsrc 7278 DAG.getConstant(0, DL, MVT::i32), // vindex 7279 Offsets.first, // voffset 7280 Op.getOperand(6), // soffset 7281 Offsets.second, // offset 7282 Op.getOperand(7), // cachepolicy 7283 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7284 }; 7285 EVT VT = Op.getValueType(); 7286 auto *M = cast<MemSDNode>(Op); 7287 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7288 7289 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7290 Op->getVTList(), Ops, VT, M->getMemOperand()); 7291 } 7292 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7293 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7294 SDValue Ops[] = { 7295 Op.getOperand(0), // Chain 7296 Op.getOperand(2), // src 7297 Op.getOperand(3), // cmp 7298 Op.getOperand(4), // rsrc 7299 Op.getOperand(5), // vindex 7300 Offsets.first, // voffset 7301 Op.getOperand(7), // soffset 7302 Offsets.second, // offset 7303 Op.getOperand(8), // cachepolicy 7304 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7305 }; 7306 EVT VT = Op.getValueType(); 7307 auto *M = cast<MemSDNode>(Op); 7308 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7309 Ops[4])); 7310 7311 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7312 Op->getVTList(), Ops, VT, M->getMemOperand()); 7313 } 7314 case Intrinsic::amdgcn_global_atomic_fadd: { 7315 if (!Op.getValue(0).use_empty()) { 7316 DiagnosticInfoUnsupported 7317 NoFpRet(DAG.getMachineFunction().getFunction(), 7318 "return versions of fp atomics not supported", 7319 DL.getDebugLoc(), DS_Error); 7320 DAG.getContext()->diagnose(NoFpRet); 7321 return SDValue(); 7322 } 7323 MemSDNode *M = cast<MemSDNode>(Op); 7324 SDValue Ops[] = { 7325 M->getOperand(0), // Chain 7326 M->getOperand(2), // Ptr 7327 M->getOperand(3) // Value 7328 }; 7329 7330 EVT VT = Op.getOperand(3).getValueType(); 7331 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7332 DAG.getVTList(VT, MVT::Other), Ops, 7333 M->getMemOperand()); 7334 } 7335 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7336 SDLoc DL(Op); 7337 MemSDNode *M = cast<MemSDNode>(Op); 7338 SDValue NodePtr = M->getOperand(2); 7339 SDValue RayExtent = M->getOperand(3); 7340 SDValue RayOrigin = M->getOperand(4); 7341 SDValue RayDir = M->getOperand(5); 7342 SDValue RayInvDir = M->getOperand(6); 7343 SDValue TDescr = M->getOperand(7); 7344 7345 assert(NodePtr.getValueType() == MVT::i32 || 7346 NodePtr.getValueType() == MVT::i64); 7347 assert(RayDir.getValueType() == MVT::v4f16 || 7348 RayDir.getValueType() == MVT::v4f32); 7349 7350 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7351 bool Is64 = NodePtr.getValueType() == MVT::i64; 7352 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7353 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7354 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7355 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7356 7357 SmallVector<SDValue, 16> Ops; 7358 7359 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7360 SmallVector<SDValue, 3> Lanes; 7361 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7362 if (Lanes[0].getValueSizeInBits() == 32) { 7363 for (unsigned I = 0; I < 3; ++I) 7364 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7365 } else { 7366 if (IsAligned) { 7367 Ops.push_back( 7368 DAG.getBitcast(MVT::i32, 7369 DAG.getBuildVector(MVT::v2f16, DL, 7370 { Lanes[0], Lanes[1] }))); 7371 Ops.push_back(Lanes[2]); 7372 } else { 7373 SDValue Elt0 = Ops.pop_back_val(); 7374 Ops.push_back( 7375 DAG.getBitcast(MVT::i32, 7376 DAG.getBuildVector(MVT::v2f16, DL, 7377 { Elt0, Lanes[0] }))); 7378 Ops.push_back( 7379 DAG.getBitcast(MVT::i32, 7380 DAG.getBuildVector(MVT::v2f16, DL, 7381 { Lanes[1], Lanes[2] }))); 7382 } 7383 } 7384 }; 7385 7386 if (Is64) 7387 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7388 else 7389 Ops.push_back(NodePtr); 7390 7391 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7392 packLanes(RayOrigin, true); 7393 packLanes(RayDir, true); 7394 packLanes(RayInvDir, false); 7395 Ops.push_back(TDescr); 7396 if (IsA16) 7397 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7398 Ops.push_back(M->getChain()); 7399 7400 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7401 MachineMemOperand *MemRef = M->getMemOperand(); 7402 DAG.setNodeMemRefs(NewNode, {MemRef}); 7403 return SDValue(NewNode, 0); 7404 } 7405 default: 7406 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7407 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7408 return lowerImage(Op, ImageDimIntr, DAG, true); 7409 7410 return SDValue(); 7411 } 7412 } 7413 7414 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7415 // dwordx4 if on SI. 7416 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7417 SDVTList VTList, 7418 ArrayRef<SDValue> Ops, EVT MemVT, 7419 MachineMemOperand *MMO, 7420 SelectionDAG &DAG) const { 7421 EVT VT = VTList.VTs[0]; 7422 EVT WidenedVT = VT; 7423 EVT WidenedMemVT = MemVT; 7424 if (!Subtarget->hasDwordx3LoadStores() && 7425 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7426 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7427 WidenedVT.getVectorElementType(), 4); 7428 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7429 WidenedMemVT.getVectorElementType(), 4); 7430 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7431 } 7432 7433 assert(VTList.NumVTs == 2); 7434 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7435 7436 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7437 WidenedMemVT, MMO); 7438 if (WidenedVT != VT) { 7439 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7440 DAG.getVectorIdxConstant(0, DL)); 7441 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7442 } 7443 return NewOp; 7444 } 7445 7446 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7447 bool ImageStore) const { 7448 EVT StoreVT = VData.getValueType(); 7449 7450 // No change for f16 and legal vector D16 types. 7451 if (!StoreVT.isVector()) 7452 return VData; 7453 7454 SDLoc DL(VData); 7455 unsigned NumElements = StoreVT.getVectorNumElements(); 7456 7457 if (Subtarget->hasUnpackedD16VMem()) { 7458 // We need to unpack the packed data to store. 7459 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7460 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7461 7462 EVT EquivStoreVT = 7463 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7464 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7465 return DAG.UnrollVectorOp(ZExt.getNode()); 7466 } 7467 7468 // The sq block of gfx8.1 does not estimate register use correctly for d16 7469 // image store instructions. The data operand is computed as if it were not a 7470 // d16 image instruction. 7471 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7472 // Bitcast to i16 7473 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7474 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7475 7476 // Decompose into scalars 7477 SmallVector<SDValue, 4> Elts; 7478 DAG.ExtractVectorElements(IntVData, Elts); 7479 7480 // Group pairs of i16 into v2i16 and bitcast to i32 7481 SmallVector<SDValue, 4> PackedElts; 7482 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7483 SDValue Pair = 7484 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7485 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7486 PackedElts.push_back(IntPair); 7487 } 7488 if ((NumElements % 2) == 1) { 7489 // Handle v3i16 7490 unsigned I = Elts.size() / 2; 7491 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7492 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7493 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7494 PackedElts.push_back(IntPair); 7495 } 7496 7497 // Pad using UNDEF 7498 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7499 7500 // Build final vector 7501 EVT VecVT = 7502 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7503 return DAG.getBuildVector(VecVT, DL, PackedElts); 7504 } 7505 7506 if (NumElements == 3) { 7507 EVT IntStoreVT = 7508 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7509 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7510 7511 EVT WidenedStoreVT = EVT::getVectorVT( 7512 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7513 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7514 WidenedStoreVT.getStoreSizeInBits()); 7515 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7516 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7517 } 7518 7519 assert(isTypeLegal(StoreVT)); 7520 return VData; 7521 } 7522 7523 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7524 SelectionDAG &DAG) const { 7525 SDLoc DL(Op); 7526 SDValue Chain = Op.getOperand(0); 7527 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7528 MachineFunction &MF = DAG.getMachineFunction(); 7529 7530 switch (IntrinsicID) { 7531 case Intrinsic::amdgcn_exp_compr: { 7532 SDValue Src0 = Op.getOperand(4); 7533 SDValue Src1 = Op.getOperand(5); 7534 // Hack around illegal type on SI by directly selecting it. 7535 if (isTypeLegal(Src0.getValueType())) 7536 return SDValue(); 7537 7538 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7539 SDValue Undef = DAG.getUNDEF(MVT::f32); 7540 const SDValue Ops[] = { 7541 Op.getOperand(2), // tgt 7542 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7543 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7544 Undef, // src2 7545 Undef, // src3 7546 Op.getOperand(7), // vm 7547 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7548 Op.getOperand(3), // en 7549 Op.getOperand(0) // Chain 7550 }; 7551 7552 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7553 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7554 } 7555 case Intrinsic::amdgcn_s_barrier: { 7556 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7557 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7558 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7559 if (WGSize <= ST.getWavefrontSize()) 7560 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7561 Op.getOperand(0)), 0); 7562 } 7563 return SDValue(); 7564 }; 7565 case Intrinsic::amdgcn_tbuffer_store: { 7566 SDValue VData = Op.getOperand(2); 7567 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7568 if (IsD16) 7569 VData = handleD16VData(VData, DAG); 7570 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7571 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7572 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7573 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7574 unsigned IdxEn = 1; 7575 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7576 IdxEn = Idx->getZExtValue() != 0; 7577 SDValue Ops[] = { 7578 Chain, 7579 VData, // vdata 7580 Op.getOperand(3), // rsrc 7581 Op.getOperand(4), // vindex 7582 Op.getOperand(5), // voffset 7583 Op.getOperand(6), // soffset 7584 Op.getOperand(7), // offset 7585 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7586 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7587 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7588 }; 7589 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7590 AMDGPUISD::TBUFFER_STORE_FORMAT; 7591 MemSDNode *M = cast<MemSDNode>(Op); 7592 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7593 M->getMemoryVT(), M->getMemOperand()); 7594 } 7595 7596 case Intrinsic::amdgcn_struct_tbuffer_store: { 7597 SDValue VData = Op.getOperand(2); 7598 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7599 if (IsD16) 7600 VData = handleD16VData(VData, DAG); 7601 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7602 SDValue Ops[] = { 7603 Chain, 7604 VData, // vdata 7605 Op.getOperand(3), // rsrc 7606 Op.getOperand(4), // vindex 7607 Offsets.first, // voffset 7608 Op.getOperand(6), // soffset 7609 Offsets.second, // offset 7610 Op.getOperand(7), // format 7611 Op.getOperand(8), // cachepolicy, swizzled buffer 7612 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7613 }; 7614 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7615 AMDGPUISD::TBUFFER_STORE_FORMAT; 7616 MemSDNode *M = cast<MemSDNode>(Op); 7617 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7618 M->getMemoryVT(), M->getMemOperand()); 7619 } 7620 7621 case Intrinsic::amdgcn_raw_tbuffer_store: { 7622 SDValue VData = Op.getOperand(2); 7623 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7624 if (IsD16) 7625 VData = handleD16VData(VData, DAG); 7626 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7627 SDValue Ops[] = { 7628 Chain, 7629 VData, // vdata 7630 Op.getOperand(3), // rsrc 7631 DAG.getConstant(0, DL, MVT::i32), // vindex 7632 Offsets.first, // voffset 7633 Op.getOperand(5), // soffset 7634 Offsets.second, // offset 7635 Op.getOperand(6), // format 7636 Op.getOperand(7), // cachepolicy, swizzled buffer 7637 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7638 }; 7639 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7640 AMDGPUISD::TBUFFER_STORE_FORMAT; 7641 MemSDNode *M = cast<MemSDNode>(Op); 7642 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7643 M->getMemoryVT(), M->getMemOperand()); 7644 } 7645 7646 case Intrinsic::amdgcn_buffer_store: 7647 case Intrinsic::amdgcn_buffer_store_format: { 7648 SDValue VData = Op.getOperand(2); 7649 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7650 if (IsD16) 7651 VData = handleD16VData(VData, DAG); 7652 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7653 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7654 unsigned IdxEn = 1; 7655 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7656 IdxEn = Idx->getZExtValue() != 0; 7657 SDValue Ops[] = { 7658 Chain, 7659 VData, 7660 Op.getOperand(3), // rsrc 7661 Op.getOperand(4), // vindex 7662 SDValue(), // voffset -- will be set by setBufferOffsets 7663 SDValue(), // soffset -- will be set by setBufferOffsets 7664 SDValue(), // offset -- will be set by setBufferOffsets 7665 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7666 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7667 }; 7668 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7669 // We don't know the offset if vindex is non-zero, so clear it. 7670 if (IdxEn) 7671 Offset = 0; 7672 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7673 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7674 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7675 MemSDNode *M = cast<MemSDNode>(Op); 7676 M->getMemOperand()->setOffset(Offset); 7677 7678 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7679 EVT VDataType = VData.getValueType().getScalarType(); 7680 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7681 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7682 7683 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7684 M->getMemoryVT(), M->getMemOperand()); 7685 } 7686 7687 case Intrinsic::amdgcn_raw_buffer_store: 7688 case Intrinsic::amdgcn_raw_buffer_store_format: { 7689 const bool IsFormat = 7690 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7691 7692 SDValue VData = Op.getOperand(2); 7693 EVT VDataVT = VData.getValueType(); 7694 EVT EltType = VDataVT.getScalarType(); 7695 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7696 if (IsD16) { 7697 VData = handleD16VData(VData, DAG); 7698 VDataVT = VData.getValueType(); 7699 } 7700 7701 if (!isTypeLegal(VDataVT)) { 7702 VData = 7703 DAG.getNode(ISD::BITCAST, DL, 7704 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7705 } 7706 7707 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7708 SDValue Ops[] = { 7709 Chain, 7710 VData, 7711 Op.getOperand(3), // rsrc 7712 DAG.getConstant(0, DL, MVT::i32), // vindex 7713 Offsets.first, // voffset 7714 Op.getOperand(5), // soffset 7715 Offsets.second, // offset 7716 Op.getOperand(6), // cachepolicy, swizzled buffer 7717 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7718 }; 7719 unsigned Opc = 7720 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7721 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7722 MemSDNode *M = cast<MemSDNode>(Op); 7723 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7724 7725 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7726 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7727 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7728 7729 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7730 M->getMemoryVT(), M->getMemOperand()); 7731 } 7732 7733 case Intrinsic::amdgcn_struct_buffer_store: 7734 case Intrinsic::amdgcn_struct_buffer_store_format: { 7735 const bool IsFormat = 7736 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7737 7738 SDValue VData = Op.getOperand(2); 7739 EVT VDataVT = VData.getValueType(); 7740 EVT EltType = VDataVT.getScalarType(); 7741 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7742 7743 if (IsD16) { 7744 VData = handleD16VData(VData, DAG); 7745 VDataVT = VData.getValueType(); 7746 } 7747 7748 if (!isTypeLegal(VDataVT)) { 7749 VData = 7750 DAG.getNode(ISD::BITCAST, DL, 7751 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7752 } 7753 7754 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7755 SDValue Ops[] = { 7756 Chain, 7757 VData, 7758 Op.getOperand(3), // rsrc 7759 Op.getOperand(4), // vindex 7760 Offsets.first, // voffset 7761 Op.getOperand(6), // soffset 7762 Offsets.second, // offset 7763 Op.getOperand(7), // cachepolicy, swizzled buffer 7764 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7765 }; 7766 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7767 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7768 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7769 MemSDNode *M = cast<MemSDNode>(Op); 7770 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7771 Ops[3])); 7772 7773 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7774 EVT VDataType = VData.getValueType().getScalarType(); 7775 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7776 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7777 7778 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7779 M->getMemoryVT(), M->getMemOperand()); 7780 } 7781 case Intrinsic::amdgcn_end_cf: 7782 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7783 Op->getOperand(2), Chain), 0); 7784 7785 default: { 7786 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7787 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7788 return lowerImage(Op, ImageDimIntr, DAG, true); 7789 7790 return Op; 7791 } 7792 } 7793 } 7794 7795 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7796 // offset (the offset that is included in bounds checking and swizzling, to be 7797 // split between the instruction's voffset and immoffset fields) and soffset 7798 // (the offset that is excluded from bounds checking and swizzling, to go in 7799 // the instruction's soffset field). This function takes the first kind of 7800 // offset and figures out how to split it between voffset and immoffset. 7801 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7802 SDValue Offset, SelectionDAG &DAG) const { 7803 SDLoc DL(Offset); 7804 const unsigned MaxImm = 4095; 7805 SDValue N0 = Offset; 7806 ConstantSDNode *C1 = nullptr; 7807 7808 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7809 N0 = SDValue(); 7810 else if (DAG.isBaseWithConstantOffset(N0)) { 7811 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7812 N0 = N0.getOperand(0); 7813 } 7814 7815 if (C1) { 7816 unsigned ImmOffset = C1->getZExtValue(); 7817 // If the immediate value is too big for the immoffset field, put the value 7818 // and -4096 into the immoffset field so that the value that is copied/added 7819 // for the voffset field is a multiple of 4096, and it stands more chance 7820 // of being CSEd with the copy/add for another similar load/store. 7821 // However, do not do that rounding down to a multiple of 4096 if that is a 7822 // negative number, as it appears to be illegal to have a negative offset 7823 // in the vgpr, even if adding the immediate offset makes it positive. 7824 unsigned Overflow = ImmOffset & ~MaxImm; 7825 ImmOffset -= Overflow; 7826 if ((int32_t)Overflow < 0) { 7827 Overflow += ImmOffset; 7828 ImmOffset = 0; 7829 } 7830 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7831 if (Overflow) { 7832 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7833 if (!N0) 7834 N0 = OverflowVal; 7835 else { 7836 SDValue Ops[] = { N0, OverflowVal }; 7837 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7838 } 7839 } 7840 } 7841 if (!N0) 7842 N0 = DAG.getConstant(0, DL, MVT::i32); 7843 if (!C1) 7844 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7845 return {N0, SDValue(C1, 0)}; 7846 } 7847 7848 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7849 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7850 // pointed to by Offsets. 7851 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7852 SelectionDAG &DAG, SDValue *Offsets, 7853 Align Alignment) const { 7854 SDLoc DL(CombinedOffset); 7855 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7856 uint32_t Imm = C->getZExtValue(); 7857 uint32_t SOffset, ImmOffset; 7858 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7859 Alignment)) { 7860 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7861 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7862 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7863 return SOffset + ImmOffset; 7864 } 7865 } 7866 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7867 SDValue N0 = CombinedOffset.getOperand(0); 7868 SDValue N1 = CombinedOffset.getOperand(1); 7869 uint32_t SOffset, ImmOffset; 7870 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7871 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7872 Subtarget, Alignment)) { 7873 Offsets[0] = N0; 7874 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7875 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7876 return 0; 7877 } 7878 } 7879 Offsets[0] = CombinedOffset; 7880 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7881 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7882 return 0; 7883 } 7884 7885 // Handle 8 bit and 16 bit buffer loads 7886 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7887 EVT LoadVT, SDLoc DL, 7888 ArrayRef<SDValue> Ops, 7889 MemSDNode *M) const { 7890 EVT IntVT = LoadVT.changeTypeToInteger(); 7891 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7892 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7893 7894 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7895 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7896 Ops, IntVT, 7897 M->getMemOperand()); 7898 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7899 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7900 7901 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7902 } 7903 7904 // Handle 8 bit and 16 bit buffer stores 7905 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7906 EVT VDataType, SDLoc DL, 7907 SDValue Ops[], 7908 MemSDNode *M) const { 7909 if (VDataType == MVT::f16) 7910 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7911 7912 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7913 Ops[1] = BufferStoreExt; 7914 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7915 AMDGPUISD::BUFFER_STORE_SHORT; 7916 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7917 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7918 M->getMemOperand()); 7919 } 7920 7921 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7922 ISD::LoadExtType ExtType, SDValue Op, 7923 const SDLoc &SL, EVT VT) { 7924 if (VT.bitsLT(Op.getValueType())) 7925 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7926 7927 switch (ExtType) { 7928 case ISD::SEXTLOAD: 7929 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7930 case ISD::ZEXTLOAD: 7931 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7932 case ISD::EXTLOAD: 7933 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7934 case ISD::NON_EXTLOAD: 7935 return Op; 7936 } 7937 7938 llvm_unreachable("invalid ext type"); 7939 } 7940 7941 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7942 SelectionDAG &DAG = DCI.DAG; 7943 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7944 return SDValue(); 7945 7946 // FIXME: Constant loads should all be marked invariant. 7947 unsigned AS = Ld->getAddressSpace(); 7948 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7949 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7950 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7951 return SDValue(); 7952 7953 // Don't do this early, since it may interfere with adjacent load merging for 7954 // illegal types. We can avoid losing alignment information for exotic types 7955 // pre-legalize. 7956 EVT MemVT = Ld->getMemoryVT(); 7957 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7958 MemVT.getSizeInBits() >= 32) 7959 return SDValue(); 7960 7961 SDLoc SL(Ld); 7962 7963 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7964 "unexpected vector extload"); 7965 7966 // TODO: Drop only high part of range. 7967 SDValue Ptr = Ld->getBasePtr(); 7968 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7969 MVT::i32, SL, Ld->getChain(), Ptr, 7970 Ld->getOffset(), 7971 Ld->getPointerInfo(), MVT::i32, 7972 Ld->getAlignment(), 7973 Ld->getMemOperand()->getFlags(), 7974 Ld->getAAInfo(), 7975 nullptr); // Drop ranges 7976 7977 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7978 if (MemVT.isFloatingPoint()) { 7979 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7980 "unexpected fp extload"); 7981 TruncVT = MemVT.changeTypeToInteger(); 7982 } 7983 7984 SDValue Cvt = NewLoad; 7985 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7986 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7987 DAG.getValueType(TruncVT)); 7988 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7989 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7990 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7991 } else { 7992 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7993 } 7994 7995 EVT VT = Ld->getValueType(0); 7996 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7997 7998 DCI.AddToWorklist(Cvt.getNode()); 7999 8000 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8001 // the appropriate extension from the 32-bit load. 8002 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8003 DCI.AddToWorklist(Cvt.getNode()); 8004 8005 // Handle conversion back to floating point if necessary. 8006 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8007 8008 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8009 } 8010 8011 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8012 SDLoc DL(Op); 8013 LoadSDNode *Load = cast<LoadSDNode>(Op); 8014 ISD::LoadExtType ExtType = Load->getExtensionType(); 8015 EVT MemVT = Load->getMemoryVT(); 8016 8017 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8018 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8019 return SDValue(); 8020 8021 // FIXME: Copied from PPC 8022 // First, load into 32 bits, then truncate to 1 bit. 8023 8024 SDValue Chain = Load->getChain(); 8025 SDValue BasePtr = Load->getBasePtr(); 8026 MachineMemOperand *MMO = Load->getMemOperand(); 8027 8028 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8029 8030 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8031 BasePtr, RealMemVT, MMO); 8032 8033 if (!MemVT.isVector()) { 8034 SDValue Ops[] = { 8035 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8036 NewLD.getValue(1) 8037 }; 8038 8039 return DAG.getMergeValues(Ops, DL); 8040 } 8041 8042 SmallVector<SDValue, 3> Elts; 8043 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8044 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8045 DAG.getConstant(I, DL, MVT::i32)); 8046 8047 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8048 } 8049 8050 SDValue Ops[] = { 8051 DAG.getBuildVector(MemVT, DL, Elts), 8052 NewLD.getValue(1) 8053 }; 8054 8055 return DAG.getMergeValues(Ops, DL); 8056 } 8057 8058 if (!MemVT.isVector()) 8059 return SDValue(); 8060 8061 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8062 "Custom lowering for non-i32 vectors hasn't been implemented."); 8063 8064 unsigned Alignment = Load->getAlignment(); 8065 unsigned AS = Load->getAddressSpace(); 8066 if (Subtarget->hasLDSMisalignedBug() && 8067 AS == AMDGPUAS::FLAT_ADDRESS && 8068 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8069 return SplitVectorLoad(Op, DAG); 8070 } 8071 8072 MachineFunction &MF = DAG.getMachineFunction(); 8073 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8074 // If there is a possibilty that flat instruction access scratch memory 8075 // then we need to use the same legalization rules we use for private. 8076 if (AS == AMDGPUAS::FLAT_ADDRESS && 8077 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8078 AS = MFI->hasFlatScratchInit() ? 8079 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8080 8081 unsigned NumElements = MemVT.getVectorNumElements(); 8082 8083 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8084 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8085 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8086 if (MemVT.isPow2VectorType()) 8087 return SDValue(); 8088 return WidenOrSplitVectorLoad(Op, DAG); 8089 } 8090 // Non-uniform loads will be selected to MUBUF instructions, so they 8091 // have the same legalization requirements as global and private 8092 // loads. 8093 // 8094 } 8095 8096 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8097 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8098 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8099 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8100 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8101 Alignment >= 4 && NumElements < 32) { 8102 if (MemVT.isPow2VectorType()) 8103 return SDValue(); 8104 return WidenOrSplitVectorLoad(Op, DAG); 8105 } 8106 // Non-uniform loads will be selected to MUBUF instructions, so they 8107 // have the same legalization requirements as global and private 8108 // loads. 8109 // 8110 } 8111 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8112 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8113 AS == AMDGPUAS::GLOBAL_ADDRESS || 8114 AS == AMDGPUAS::FLAT_ADDRESS) { 8115 if (NumElements > 4) 8116 return SplitVectorLoad(Op, DAG); 8117 // v3 loads not supported on SI. 8118 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8119 return WidenOrSplitVectorLoad(Op, DAG); 8120 8121 // v3 and v4 loads are supported for private and global memory. 8122 return SDValue(); 8123 } 8124 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8125 // Depending on the setting of the private_element_size field in the 8126 // resource descriptor, we can only make private accesses up to a certain 8127 // size. 8128 switch (Subtarget->getMaxPrivateElementSize()) { 8129 case 4: { 8130 SDValue Ops[2]; 8131 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8132 return DAG.getMergeValues(Ops, DL); 8133 } 8134 case 8: 8135 if (NumElements > 2) 8136 return SplitVectorLoad(Op, DAG); 8137 return SDValue(); 8138 case 16: 8139 // Same as global/flat 8140 if (NumElements > 4) 8141 return SplitVectorLoad(Op, DAG); 8142 // v3 loads not supported on SI. 8143 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8144 return WidenOrSplitVectorLoad(Op, DAG); 8145 8146 return SDValue(); 8147 default: 8148 llvm_unreachable("unsupported private_element_size"); 8149 } 8150 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8151 // Use ds_read_b128 or ds_read_b96 when possible. 8152 if (Subtarget->hasDS96AndDS128() && 8153 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8154 MemVT.getStoreSize() == 12) && 8155 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8156 Load->getAlign())) 8157 return SDValue(); 8158 8159 if (NumElements > 2) 8160 return SplitVectorLoad(Op, DAG); 8161 8162 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8163 // address is negative, then the instruction is incorrectly treated as 8164 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8165 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8166 // load later in the SILoadStoreOptimizer. 8167 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8168 NumElements == 2 && MemVT.getStoreSize() == 8 && 8169 Load->getAlignment() < 8) { 8170 return SplitVectorLoad(Op, DAG); 8171 } 8172 } 8173 8174 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8175 MemVT, *Load->getMemOperand())) { 8176 SDValue Ops[2]; 8177 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8178 return DAG.getMergeValues(Ops, DL); 8179 } 8180 8181 return SDValue(); 8182 } 8183 8184 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8185 EVT VT = Op.getValueType(); 8186 assert(VT.getSizeInBits() == 64); 8187 8188 SDLoc DL(Op); 8189 SDValue Cond = Op.getOperand(0); 8190 8191 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8192 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8193 8194 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8195 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8196 8197 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8198 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8199 8200 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8201 8202 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8203 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8204 8205 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8206 8207 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8208 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8209 } 8210 8211 // Catch division cases where we can use shortcuts with rcp and rsq 8212 // instructions. 8213 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8214 SelectionDAG &DAG) const { 8215 SDLoc SL(Op); 8216 SDValue LHS = Op.getOperand(0); 8217 SDValue RHS = Op.getOperand(1); 8218 EVT VT = Op.getValueType(); 8219 const SDNodeFlags Flags = Op->getFlags(); 8220 8221 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8222 Flags.hasApproximateFuncs(); 8223 8224 // Without !fpmath accuracy information, we can't do more because we don't 8225 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8226 if (!AllowInaccurateRcp) 8227 return SDValue(); 8228 8229 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8230 if (CLHS->isExactlyValue(1.0)) { 8231 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8232 // the CI documentation has a worst case error of 1 ulp. 8233 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8234 // use it as long as we aren't trying to use denormals. 8235 // 8236 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8237 8238 // 1.0 / sqrt(x) -> rsq(x) 8239 8240 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8241 // error seems really high at 2^29 ULP. 8242 if (RHS.getOpcode() == ISD::FSQRT) 8243 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8244 8245 // 1.0 / x -> rcp(x) 8246 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8247 } 8248 8249 // Same as for 1.0, but expand the sign out of the constant. 8250 if (CLHS->isExactlyValue(-1.0)) { 8251 // -1.0 / x -> rcp (fneg x) 8252 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8253 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8254 } 8255 } 8256 8257 // Turn into multiply by the reciprocal. 8258 // x / y -> x * (1.0 / y) 8259 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8260 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8261 } 8262 8263 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8264 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8265 SDNodeFlags Flags) { 8266 if (GlueChain->getNumValues() <= 1) { 8267 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8268 } 8269 8270 assert(GlueChain->getNumValues() == 3); 8271 8272 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8273 switch (Opcode) { 8274 default: llvm_unreachable("no chain equivalent for opcode"); 8275 case ISD::FMUL: 8276 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8277 break; 8278 } 8279 8280 return DAG.getNode(Opcode, SL, VTList, 8281 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8282 Flags); 8283 } 8284 8285 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8286 EVT VT, SDValue A, SDValue B, SDValue C, 8287 SDValue GlueChain, SDNodeFlags Flags) { 8288 if (GlueChain->getNumValues() <= 1) { 8289 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8290 } 8291 8292 assert(GlueChain->getNumValues() == 3); 8293 8294 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8295 switch (Opcode) { 8296 default: llvm_unreachable("no chain equivalent for opcode"); 8297 case ISD::FMA: 8298 Opcode = AMDGPUISD::FMA_W_CHAIN; 8299 break; 8300 } 8301 8302 return DAG.getNode(Opcode, SL, VTList, 8303 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8304 Flags); 8305 } 8306 8307 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8308 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8309 return FastLowered; 8310 8311 SDLoc SL(Op); 8312 SDValue Src0 = Op.getOperand(0); 8313 SDValue Src1 = Op.getOperand(1); 8314 8315 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8316 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8317 8318 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8319 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8320 8321 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8322 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8323 8324 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8325 } 8326 8327 // Faster 2.5 ULP division that does not support denormals. 8328 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8329 SDLoc SL(Op); 8330 SDValue LHS = Op.getOperand(1); 8331 SDValue RHS = Op.getOperand(2); 8332 8333 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8334 8335 const APFloat K0Val(BitsToFloat(0x6f800000)); 8336 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8337 8338 const APFloat K1Val(BitsToFloat(0x2f800000)); 8339 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8340 8341 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8342 8343 EVT SetCCVT = 8344 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8345 8346 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8347 8348 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8349 8350 // TODO: Should this propagate fast-math-flags? 8351 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8352 8353 // rcp does not support denormals. 8354 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8355 8356 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8357 8358 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8359 } 8360 8361 // Returns immediate value for setting the F32 denorm mode when using the 8362 // S_DENORM_MODE instruction. 8363 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8364 const SDLoc &SL, const GCNSubtarget *ST) { 8365 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8366 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8367 ? FP_DENORM_FLUSH_NONE 8368 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8369 8370 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8371 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8372 } 8373 8374 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8375 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8376 return FastLowered; 8377 8378 // The selection matcher assumes anything with a chain selecting to a 8379 // mayRaiseFPException machine instruction. Since we're introducing a chain 8380 // here, we need to explicitly report nofpexcept for the regular fdiv 8381 // lowering. 8382 SDNodeFlags Flags = Op->getFlags(); 8383 Flags.setNoFPExcept(true); 8384 8385 SDLoc SL(Op); 8386 SDValue LHS = Op.getOperand(0); 8387 SDValue RHS = Op.getOperand(1); 8388 8389 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8390 8391 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8392 8393 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8394 {RHS, RHS, LHS}, Flags); 8395 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8396 {LHS, RHS, LHS}, Flags); 8397 8398 // Denominator is scaled to not be denormal, so using rcp is ok. 8399 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8400 DenominatorScaled, Flags); 8401 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8402 DenominatorScaled, Flags); 8403 8404 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8405 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8406 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8407 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8408 8409 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8410 8411 if (!HasFP32Denormals) { 8412 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8413 // lowering. The chain dependence is insufficient, and we need glue. We do 8414 // not need the glue variants in a strictfp function. 8415 8416 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8417 8418 SDNode *EnableDenorm; 8419 if (Subtarget->hasDenormModeInst()) { 8420 const SDValue EnableDenormValue = 8421 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8422 8423 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8424 DAG.getEntryNode(), EnableDenormValue).getNode(); 8425 } else { 8426 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8427 SL, MVT::i32); 8428 EnableDenorm = 8429 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8430 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8431 } 8432 8433 SDValue Ops[3] = { 8434 NegDivScale0, 8435 SDValue(EnableDenorm, 0), 8436 SDValue(EnableDenorm, 1) 8437 }; 8438 8439 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8440 } 8441 8442 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8443 ApproxRcp, One, NegDivScale0, Flags); 8444 8445 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8446 ApproxRcp, Fma0, Flags); 8447 8448 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8449 Fma1, Fma1, Flags); 8450 8451 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8452 NumeratorScaled, Mul, Flags); 8453 8454 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8455 Fma2, Fma1, Mul, Fma2, Flags); 8456 8457 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8458 NumeratorScaled, Fma3, Flags); 8459 8460 if (!HasFP32Denormals) { 8461 SDNode *DisableDenorm; 8462 if (Subtarget->hasDenormModeInst()) { 8463 const SDValue DisableDenormValue = 8464 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8465 8466 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8467 Fma4.getValue(1), DisableDenormValue, 8468 Fma4.getValue(2)).getNode(); 8469 } else { 8470 const SDValue DisableDenormValue = 8471 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8472 8473 DisableDenorm = DAG.getMachineNode( 8474 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8475 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8476 } 8477 8478 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8479 SDValue(DisableDenorm, 0), DAG.getRoot()); 8480 DAG.setRoot(OutputChain); 8481 } 8482 8483 SDValue Scale = NumeratorScaled.getValue(1); 8484 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8485 {Fma4, Fma1, Fma3, Scale}, Flags); 8486 8487 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8488 } 8489 8490 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8491 if (DAG.getTarget().Options.UnsafeFPMath) 8492 return lowerFastUnsafeFDIV(Op, DAG); 8493 8494 SDLoc SL(Op); 8495 SDValue X = Op.getOperand(0); 8496 SDValue Y = Op.getOperand(1); 8497 8498 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8499 8500 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8501 8502 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8503 8504 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8505 8506 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8507 8508 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8509 8510 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8511 8512 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8513 8514 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8515 8516 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8517 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8518 8519 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8520 NegDivScale0, Mul, DivScale1); 8521 8522 SDValue Scale; 8523 8524 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8525 // Workaround a hardware bug on SI where the condition output from div_scale 8526 // is not usable. 8527 8528 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8529 8530 // Figure out if the scale to use for div_fmas. 8531 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8532 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8533 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8534 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8535 8536 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8537 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8538 8539 SDValue Scale0Hi 8540 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8541 SDValue Scale1Hi 8542 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8543 8544 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8545 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8546 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8547 } else { 8548 Scale = DivScale1.getValue(1); 8549 } 8550 8551 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8552 Fma4, Fma3, Mul, Scale); 8553 8554 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8555 } 8556 8557 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8558 EVT VT = Op.getValueType(); 8559 8560 if (VT == MVT::f32) 8561 return LowerFDIV32(Op, DAG); 8562 8563 if (VT == MVT::f64) 8564 return LowerFDIV64(Op, DAG); 8565 8566 if (VT == MVT::f16) 8567 return LowerFDIV16(Op, DAG); 8568 8569 llvm_unreachable("Unexpected type for fdiv"); 8570 } 8571 8572 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8573 SDLoc DL(Op); 8574 StoreSDNode *Store = cast<StoreSDNode>(Op); 8575 EVT VT = Store->getMemoryVT(); 8576 8577 if (VT == MVT::i1) { 8578 return DAG.getTruncStore(Store->getChain(), DL, 8579 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8580 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8581 } 8582 8583 assert(VT.isVector() && 8584 Store->getValue().getValueType().getScalarType() == MVT::i32); 8585 8586 unsigned AS = Store->getAddressSpace(); 8587 if (Subtarget->hasLDSMisalignedBug() && 8588 AS == AMDGPUAS::FLAT_ADDRESS && 8589 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8590 return SplitVectorStore(Op, DAG); 8591 } 8592 8593 MachineFunction &MF = DAG.getMachineFunction(); 8594 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8595 // If there is a possibilty that flat instruction access scratch memory 8596 // then we need to use the same legalization rules we use for private. 8597 if (AS == AMDGPUAS::FLAT_ADDRESS && 8598 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8599 AS = MFI->hasFlatScratchInit() ? 8600 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8601 8602 unsigned NumElements = VT.getVectorNumElements(); 8603 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8604 AS == AMDGPUAS::FLAT_ADDRESS) { 8605 if (NumElements > 4) 8606 return SplitVectorStore(Op, DAG); 8607 // v3 stores not supported on SI. 8608 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8609 return SplitVectorStore(Op, DAG); 8610 8611 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8612 VT, *Store->getMemOperand())) 8613 return expandUnalignedStore(Store, DAG); 8614 8615 return SDValue(); 8616 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8617 switch (Subtarget->getMaxPrivateElementSize()) { 8618 case 4: 8619 return scalarizeVectorStore(Store, DAG); 8620 case 8: 8621 if (NumElements > 2) 8622 return SplitVectorStore(Op, DAG); 8623 return SDValue(); 8624 case 16: 8625 if (NumElements > 4 || 8626 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8627 return SplitVectorStore(Op, DAG); 8628 return SDValue(); 8629 default: 8630 llvm_unreachable("unsupported private_element_size"); 8631 } 8632 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8633 // Use ds_write_b128 or ds_write_b96 when possible. 8634 if (Subtarget->hasDS96AndDS128() && 8635 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8636 (VT.getStoreSize() == 12)) && 8637 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8638 Store->getAlign())) 8639 return SDValue(); 8640 8641 if (NumElements > 2) 8642 return SplitVectorStore(Op, DAG); 8643 8644 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8645 // address is negative, then the instruction is incorrectly treated as 8646 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8647 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8648 // store later in the SILoadStoreOptimizer. 8649 if (!Subtarget->hasUsableDSOffset() && 8650 NumElements == 2 && VT.getStoreSize() == 8 && 8651 Store->getAlignment() < 8) { 8652 return SplitVectorStore(Op, DAG); 8653 } 8654 8655 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8656 VT, *Store->getMemOperand())) { 8657 if (VT.isVector()) 8658 return SplitVectorStore(Op, DAG); 8659 return expandUnalignedStore(Store, DAG); 8660 } 8661 8662 return SDValue(); 8663 } else { 8664 llvm_unreachable("unhandled address space"); 8665 } 8666 } 8667 8668 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8669 SDLoc DL(Op); 8670 EVT VT = Op.getValueType(); 8671 SDValue Arg = Op.getOperand(0); 8672 SDValue TrigVal; 8673 8674 // Propagate fast-math flags so that the multiply we introduce can be folded 8675 // if Arg is already the result of a multiply by constant. 8676 auto Flags = Op->getFlags(); 8677 8678 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8679 8680 if (Subtarget->hasTrigReducedRange()) { 8681 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8682 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8683 } else { 8684 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8685 } 8686 8687 switch (Op.getOpcode()) { 8688 case ISD::FCOS: 8689 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8690 case ISD::FSIN: 8691 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8692 default: 8693 llvm_unreachable("Wrong trig opcode"); 8694 } 8695 } 8696 8697 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8698 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8699 assert(AtomicNode->isCompareAndSwap()); 8700 unsigned AS = AtomicNode->getAddressSpace(); 8701 8702 // No custom lowering required for local address space 8703 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8704 return Op; 8705 8706 // Non-local address space requires custom lowering for atomic compare 8707 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8708 SDLoc DL(Op); 8709 SDValue ChainIn = Op.getOperand(0); 8710 SDValue Addr = Op.getOperand(1); 8711 SDValue Old = Op.getOperand(2); 8712 SDValue New = Op.getOperand(3); 8713 EVT VT = Op.getValueType(); 8714 MVT SimpleVT = VT.getSimpleVT(); 8715 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8716 8717 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8718 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8719 8720 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8721 Ops, VT, AtomicNode->getMemOperand()); 8722 } 8723 8724 //===----------------------------------------------------------------------===// 8725 // Custom DAG optimizations 8726 //===----------------------------------------------------------------------===// 8727 8728 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8729 DAGCombinerInfo &DCI) const { 8730 EVT VT = N->getValueType(0); 8731 EVT ScalarVT = VT.getScalarType(); 8732 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8733 return SDValue(); 8734 8735 SelectionDAG &DAG = DCI.DAG; 8736 SDLoc DL(N); 8737 8738 SDValue Src = N->getOperand(0); 8739 EVT SrcVT = Src.getValueType(); 8740 8741 // TODO: We could try to match extracting the higher bytes, which would be 8742 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8743 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8744 // about in practice. 8745 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8746 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8747 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8748 DCI.AddToWorklist(Cvt.getNode()); 8749 8750 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8751 if (ScalarVT != MVT::f32) { 8752 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8753 DAG.getTargetConstant(0, DL, MVT::i32)); 8754 } 8755 return Cvt; 8756 } 8757 } 8758 8759 return SDValue(); 8760 } 8761 8762 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8763 8764 // This is a variant of 8765 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8766 // 8767 // The normal DAG combiner will do this, but only if the add has one use since 8768 // that would increase the number of instructions. 8769 // 8770 // This prevents us from seeing a constant offset that can be folded into a 8771 // memory instruction's addressing mode. If we know the resulting add offset of 8772 // a pointer can be folded into an addressing offset, we can replace the pointer 8773 // operand with the add of new constant offset. This eliminates one of the uses, 8774 // and may allow the remaining use to also be simplified. 8775 // 8776 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8777 unsigned AddrSpace, 8778 EVT MemVT, 8779 DAGCombinerInfo &DCI) const { 8780 SDValue N0 = N->getOperand(0); 8781 SDValue N1 = N->getOperand(1); 8782 8783 // We only do this to handle cases where it's profitable when there are 8784 // multiple uses of the add, so defer to the standard combine. 8785 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8786 N0->hasOneUse()) 8787 return SDValue(); 8788 8789 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8790 if (!CN1) 8791 return SDValue(); 8792 8793 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8794 if (!CAdd) 8795 return SDValue(); 8796 8797 // If the resulting offset is too large, we can't fold it into the addressing 8798 // mode offset. 8799 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8800 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8801 8802 AddrMode AM; 8803 AM.HasBaseReg = true; 8804 AM.BaseOffs = Offset.getSExtValue(); 8805 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8806 return SDValue(); 8807 8808 SelectionDAG &DAG = DCI.DAG; 8809 SDLoc SL(N); 8810 EVT VT = N->getValueType(0); 8811 8812 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8813 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8814 8815 SDNodeFlags Flags; 8816 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8817 (N0.getOpcode() == ISD::OR || 8818 N0->getFlags().hasNoUnsignedWrap())); 8819 8820 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8821 } 8822 8823 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8824 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8825 /// specific intrinsic, but they all place the pointer operand first. 8826 static unsigned getBasePtrIndex(const MemSDNode *N) { 8827 switch (N->getOpcode()) { 8828 case ISD::STORE: 8829 case ISD::INTRINSIC_W_CHAIN: 8830 case ISD::INTRINSIC_VOID: 8831 return 2; 8832 default: 8833 return 1; 8834 } 8835 } 8836 8837 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8838 DAGCombinerInfo &DCI) const { 8839 SelectionDAG &DAG = DCI.DAG; 8840 SDLoc SL(N); 8841 8842 unsigned PtrIdx = getBasePtrIndex(N); 8843 SDValue Ptr = N->getOperand(PtrIdx); 8844 8845 // TODO: We could also do this for multiplies. 8846 if (Ptr.getOpcode() == ISD::SHL) { 8847 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8848 N->getMemoryVT(), DCI); 8849 if (NewPtr) { 8850 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8851 8852 NewOps[PtrIdx] = NewPtr; 8853 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8854 } 8855 } 8856 8857 return SDValue(); 8858 } 8859 8860 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8861 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8862 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8863 (Opc == ISD::XOR && Val == 0); 8864 } 8865 8866 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8867 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8868 // integer combine opportunities since most 64-bit operations are decomposed 8869 // this way. TODO: We won't want this for SALU especially if it is an inline 8870 // immediate. 8871 SDValue SITargetLowering::splitBinaryBitConstantOp( 8872 DAGCombinerInfo &DCI, 8873 const SDLoc &SL, 8874 unsigned Opc, SDValue LHS, 8875 const ConstantSDNode *CRHS) const { 8876 uint64_t Val = CRHS->getZExtValue(); 8877 uint32_t ValLo = Lo_32(Val); 8878 uint32_t ValHi = Hi_32(Val); 8879 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8880 8881 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8882 bitOpWithConstantIsReducible(Opc, ValHi)) || 8883 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8884 // If we need to materialize a 64-bit immediate, it will be split up later 8885 // anyway. Avoid creating the harder to understand 64-bit immediate 8886 // materialization. 8887 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8888 } 8889 8890 return SDValue(); 8891 } 8892 8893 // Returns true if argument is a boolean value which is not serialized into 8894 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8895 static bool isBoolSGPR(SDValue V) { 8896 if (V.getValueType() != MVT::i1) 8897 return false; 8898 switch (V.getOpcode()) { 8899 default: break; 8900 case ISD::SETCC: 8901 case ISD::AND: 8902 case ISD::OR: 8903 case ISD::XOR: 8904 case AMDGPUISD::FP_CLASS: 8905 return true; 8906 } 8907 return false; 8908 } 8909 8910 // If a constant has all zeroes or all ones within each byte return it. 8911 // Otherwise return 0. 8912 static uint32_t getConstantPermuteMask(uint32_t C) { 8913 // 0xff for any zero byte in the mask 8914 uint32_t ZeroByteMask = 0; 8915 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8916 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8917 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8918 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8919 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8920 if ((NonZeroByteMask & C) != NonZeroByteMask) 8921 return 0; // Partial bytes selected. 8922 return C; 8923 } 8924 8925 // Check if a node selects whole bytes from its operand 0 starting at a byte 8926 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8927 // or -1 if not succeeded. 8928 // Note byte select encoding: 8929 // value 0-3 selects corresponding source byte; 8930 // value 0xc selects zero; 8931 // value 0xff selects 0xff. 8932 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8933 assert(V.getValueSizeInBits() == 32); 8934 8935 if (V.getNumOperands() != 2) 8936 return ~0; 8937 8938 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8939 if (!N1) 8940 return ~0; 8941 8942 uint32_t C = N1->getZExtValue(); 8943 8944 switch (V.getOpcode()) { 8945 default: 8946 break; 8947 case ISD::AND: 8948 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8949 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8950 } 8951 break; 8952 8953 case ISD::OR: 8954 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8955 return (0x03020100 & ~ConstMask) | ConstMask; 8956 } 8957 break; 8958 8959 case ISD::SHL: 8960 if (C % 8) 8961 return ~0; 8962 8963 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8964 8965 case ISD::SRL: 8966 if (C % 8) 8967 return ~0; 8968 8969 return uint32_t(0x0c0c0c0c03020100ull >> C); 8970 } 8971 8972 return ~0; 8973 } 8974 8975 SDValue SITargetLowering::performAndCombine(SDNode *N, 8976 DAGCombinerInfo &DCI) const { 8977 if (DCI.isBeforeLegalize()) 8978 return SDValue(); 8979 8980 SelectionDAG &DAG = DCI.DAG; 8981 EVT VT = N->getValueType(0); 8982 SDValue LHS = N->getOperand(0); 8983 SDValue RHS = N->getOperand(1); 8984 8985 8986 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8987 if (VT == MVT::i64 && CRHS) { 8988 if (SDValue Split 8989 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8990 return Split; 8991 } 8992 8993 if (CRHS && VT == MVT::i32) { 8994 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8995 // nb = number of trailing zeroes in mask 8996 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8997 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8998 uint64_t Mask = CRHS->getZExtValue(); 8999 unsigned Bits = countPopulation(Mask); 9000 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9001 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9002 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9003 unsigned Shift = CShift->getZExtValue(); 9004 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9005 unsigned Offset = NB + Shift; 9006 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9007 SDLoc SL(N); 9008 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9009 LHS->getOperand(0), 9010 DAG.getConstant(Offset, SL, MVT::i32), 9011 DAG.getConstant(Bits, SL, MVT::i32)); 9012 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9013 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9014 DAG.getValueType(NarrowVT)); 9015 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9016 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9017 return Shl; 9018 } 9019 } 9020 } 9021 9022 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9023 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9024 isa<ConstantSDNode>(LHS.getOperand(2))) { 9025 uint32_t Sel = getConstantPermuteMask(Mask); 9026 if (!Sel) 9027 return SDValue(); 9028 9029 // Select 0xc for all zero bytes 9030 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9031 SDLoc DL(N); 9032 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9033 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9034 } 9035 } 9036 9037 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9038 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9039 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9040 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9041 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9042 9043 SDValue X = LHS.getOperand(0); 9044 SDValue Y = RHS.getOperand(0); 9045 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9046 return SDValue(); 9047 9048 if (LCC == ISD::SETO) { 9049 if (X != LHS.getOperand(1)) 9050 return SDValue(); 9051 9052 if (RCC == ISD::SETUNE) { 9053 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9054 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9055 return SDValue(); 9056 9057 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9058 SIInstrFlags::N_SUBNORMAL | 9059 SIInstrFlags::N_ZERO | 9060 SIInstrFlags::P_ZERO | 9061 SIInstrFlags::P_SUBNORMAL | 9062 SIInstrFlags::P_NORMAL; 9063 9064 static_assert(((~(SIInstrFlags::S_NAN | 9065 SIInstrFlags::Q_NAN | 9066 SIInstrFlags::N_INFINITY | 9067 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9068 "mask not equal"); 9069 9070 SDLoc DL(N); 9071 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9072 X, DAG.getConstant(Mask, DL, MVT::i32)); 9073 } 9074 } 9075 } 9076 9077 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9078 std::swap(LHS, RHS); 9079 9080 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9081 RHS.hasOneUse()) { 9082 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9083 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9084 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9085 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9086 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9087 (RHS.getOperand(0) == LHS.getOperand(0) && 9088 LHS.getOperand(0) == LHS.getOperand(1))) { 9089 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9090 unsigned NewMask = LCC == ISD::SETO ? 9091 Mask->getZExtValue() & ~OrdMask : 9092 Mask->getZExtValue() & OrdMask; 9093 9094 SDLoc DL(N); 9095 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9096 DAG.getConstant(NewMask, DL, MVT::i32)); 9097 } 9098 } 9099 9100 if (VT == MVT::i32 && 9101 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9102 // and x, (sext cc from i1) => select cc, x, 0 9103 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9104 std::swap(LHS, RHS); 9105 if (isBoolSGPR(RHS.getOperand(0))) 9106 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9107 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9108 } 9109 9110 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9111 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9112 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9113 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9114 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9115 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9116 if (LHSMask != ~0u && RHSMask != ~0u) { 9117 // Canonicalize the expression in an attempt to have fewer unique masks 9118 // and therefore fewer registers used to hold the masks. 9119 if (LHSMask > RHSMask) { 9120 std::swap(LHSMask, RHSMask); 9121 std::swap(LHS, RHS); 9122 } 9123 9124 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9125 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9126 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9127 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9128 9129 // Check of we need to combine values from two sources within a byte. 9130 if (!(LHSUsedLanes & RHSUsedLanes) && 9131 // If we select high and lower word keep it for SDWA. 9132 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9133 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9134 // Each byte in each mask is either selector mask 0-3, or has higher 9135 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9136 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9137 // mask which is not 0xff wins. By anding both masks we have a correct 9138 // result except that 0x0c shall be corrected to give 0x0c only. 9139 uint32_t Mask = LHSMask & RHSMask; 9140 for (unsigned I = 0; I < 32; I += 8) { 9141 uint32_t ByteSel = 0xff << I; 9142 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9143 Mask &= (0x0c << I) & 0xffffffff; 9144 } 9145 9146 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9147 // or 0x0c. 9148 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9149 SDLoc DL(N); 9150 9151 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9152 LHS.getOperand(0), RHS.getOperand(0), 9153 DAG.getConstant(Sel, DL, MVT::i32)); 9154 } 9155 } 9156 } 9157 9158 return SDValue(); 9159 } 9160 9161 SDValue SITargetLowering::performOrCombine(SDNode *N, 9162 DAGCombinerInfo &DCI) const { 9163 SelectionDAG &DAG = DCI.DAG; 9164 SDValue LHS = N->getOperand(0); 9165 SDValue RHS = N->getOperand(1); 9166 9167 EVT VT = N->getValueType(0); 9168 if (VT == MVT::i1) { 9169 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9170 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9171 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9172 SDValue Src = LHS.getOperand(0); 9173 if (Src != RHS.getOperand(0)) 9174 return SDValue(); 9175 9176 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9177 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9178 if (!CLHS || !CRHS) 9179 return SDValue(); 9180 9181 // Only 10 bits are used. 9182 static const uint32_t MaxMask = 0x3ff; 9183 9184 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9185 SDLoc DL(N); 9186 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9187 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9188 } 9189 9190 return SDValue(); 9191 } 9192 9193 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9194 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9195 LHS.getOpcode() == AMDGPUISD::PERM && 9196 isa<ConstantSDNode>(LHS.getOperand(2))) { 9197 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9198 if (!Sel) 9199 return SDValue(); 9200 9201 Sel |= LHS.getConstantOperandVal(2); 9202 SDLoc DL(N); 9203 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9204 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9205 } 9206 9207 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9209 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9210 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9211 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9212 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9213 if (LHSMask != ~0u && RHSMask != ~0u) { 9214 // Canonicalize the expression in an attempt to have fewer unique masks 9215 // and therefore fewer registers used to hold the masks. 9216 if (LHSMask > RHSMask) { 9217 std::swap(LHSMask, RHSMask); 9218 std::swap(LHS, RHS); 9219 } 9220 9221 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9222 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9223 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9224 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9225 9226 // Check of we need to combine values from two sources within a byte. 9227 if (!(LHSUsedLanes & RHSUsedLanes) && 9228 // If we select high and lower word keep it for SDWA. 9229 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9230 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9231 // Kill zero bytes selected by other mask. Zero value is 0xc. 9232 LHSMask &= ~RHSUsedLanes; 9233 RHSMask &= ~LHSUsedLanes; 9234 // Add 4 to each active LHS lane 9235 LHSMask |= LHSUsedLanes & 0x04040404; 9236 // Combine masks 9237 uint32_t Sel = LHSMask | RHSMask; 9238 SDLoc DL(N); 9239 9240 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9241 LHS.getOperand(0), RHS.getOperand(0), 9242 DAG.getConstant(Sel, DL, MVT::i32)); 9243 } 9244 } 9245 } 9246 9247 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9248 return SDValue(); 9249 9250 // TODO: This could be a generic combine with a predicate for extracting the 9251 // high half of an integer being free. 9252 9253 // (or i64:x, (zero_extend i32:y)) -> 9254 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9255 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9256 RHS.getOpcode() != ISD::ZERO_EXTEND) 9257 std::swap(LHS, RHS); 9258 9259 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9260 SDValue ExtSrc = RHS.getOperand(0); 9261 EVT SrcVT = ExtSrc.getValueType(); 9262 if (SrcVT == MVT::i32) { 9263 SDLoc SL(N); 9264 SDValue LowLHS, HiBits; 9265 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9266 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9267 9268 DCI.AddToWorklist(LowOr.getNode()); 9269 DCI.AddToWorklist(HiBits.getNode()); 9270 9271 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9272 LowOr, HiBits); 9273 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9274 } 9275 } 9276 9277 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9278 if (CRHS) { 9279 if (SDValue Split 9280 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9281 return Split; 9282 } 9283 9284 return SDValue(); 9285 } 9286 9287 SDValue SITargetLowering::performXorCombine(SDNode *N, 9288 DAGCombinerInfo &DCI) const { 9289 EVT VT = N->getValueType(0); 9290 if (VT != MVT::i64) 9291 return SDValue(); 9292 9293 SDValue LHS = N->getOperand(0); 9294 SDValue RHS = N->getOperand(1); 9295 9296 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9297 if (CRHS) { 9298 if (SDValue Split 9299 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9300 return Split; 9301 } 9302 9303 return SDValue(); 9304 } 9305 9306 // Instructions that will be lowered with a final instruction that zeros the 9307 // high result bits. 9308 // XXX - probably only need to list legal operations. 9309 static bool fp16SrcZerosHighBits(unsigned Opc) { 9310 switch (Opc) { 9311 case ISD::FADD: 9312 case ISD::FSUB: 9313 case ISD::FMUL: 9314 case ISD::FDIV: 9315 case ISD::FREM: 9316 case ISD::FMA: 9317 case ISD::FMAD: 9318 case ISD::FCANONICALIZE: 9319 case ISD::FP_ROUND: 9320 case ISD::UINT_TO_FP: 9321 case ISD::SINT_TO_FP: 9322 case ISD::FABS: 9323 // Fabs is lowered to a bit operation, but it's an and which will clear the 9324 // high bits anyway. 9325 case ISD::FSQRT: 9326 case ISD::FSIN: 9327 case ISD::FCOS: 9328 case ISD::FPOWI: 9329 case ISD::FPOW: 9330 case ISD::FLOG: 9331 case ISD::FLOG2: 9332 case ISD::FLOG10: 9333 case ISD::FEXP: 9334 case ISD::FEXP2: 9335 case ISD::FCEIL: 9336 case ISD::FTRUNC: 9337 case ISD::FRINT: 9338 case ISD::FNEARBYINT: 9339 case ISD::FROUND: 9340 case ISD::FFLOOR: 9341 case ISD::FMINNUM: 9342 case ISD::FMAXNUM: 9343 case AMDGPUISD::FRACT: 9344 case AMDGPUISD::CLAMP: 9345 case AMDGPUISD::COS_HW: 9346 case AMDGPUISD::SIN_HW: 9347 case AMDGPUISD::FMIN3: 9348 case AMDGPUISD::FMAX3: 9349 case AMDGPUISD::FMED3: 9350 case AMDGPUISD::FMAD_FTZ: 9351 case AMDGPUISD::RCP: 9352 case AMDGPUISD::RSQ: 9353 case AMDGPUISD::RCP_IFLAG: 9354 case AMDGPUISD::LDEXP: 9355 return true; 9356 default: 9357 // fcopysign, select and others may be lowered to 32-bit bit operations 9358 // which don't zero the high bits. 9359 return false; 9360 } 9361 } 9362 9363 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9364 DAGCombinerInfo &DCI) const { 9365 if (!Subtarget->has16BitInsts() || 9366 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9367 return SDValue(); 9368 9369 EVT VT = N->getValueType(0); 9370 if (VT != MVT::i32) 9371 return SDValue(); 9372 9373 SDValue Src = N->getOperand(0); 9374 if (Src.getValueType() != MVT::i16) 9375 return SDValue(); 9376 9377 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9378 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9379 if (Src.getOpcode() == ISD::BITCAST) { 9380 SDValue BCSrc = Src.getOperand(0); 9381 if (BCSrc.getValueType() == MVT::f16 && 9382 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9383 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9384 } 9385 9386 return SDValue(); 9387 } 9388 9389 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9390 DAGCombinerInfo &DCI) 9391 const { 9392 SDValue Src = N->getOperand(0); 9393 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9394 9395 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9396 VTSign->getVT() == MVT::i8) || 9397 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9398 VTSign->getVT() == MVT::i16)) && 9399 Src.hasOneUse()) { 9400 auto *M = cast<MemSDNode>(Src); 9401 SDValue Ops[] = { 9402 Src.getOperand(0), // Chain 9403 Src.getOperand(1), // rsrc 9404 Src.getOperand(2), // vindex 9405 Src.getOperand(3), // voffset 9406 Src.getOperand(4), // soffset 9407 Src.getOperand(5), // offset 9408 Src.getOperand(6), 9409 Src.getOperand(7) 9410 }; 9411 // replace with BUFFER_LOAD_BYTE/SHORT 9412 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9413 Src.getOperand(0).getValueType()); 9414 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9415 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9416 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9417 ResList, 9418 Ops, M->getMemoryVT(), 9419 M->getMemOperand()); 9420 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9421 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9422 } 9423 return SDValue(); 9424 } 9425 9426 SDValue SITargetLowering::performClassCombine(SDNode *N, 9427 DAGCombinerInfo &DCI) const { 9428 SelectionDAG &DAG = DCI.DAG; 9429 SDValue Mask = N->getOperand(1); 9430 9431 // fp_class x, 0 -> false 9432 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9433 if (CMask->isNullValue()) 9434 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9435 } 9436 9437 if (N->getOperand(0).isUndef()) 9438 return DAG.getUNDEF(MVT::i1); 9439 9440 return SDValue(); 9441 } 9442 9443 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9444 DAGCombinerInfo &DCI) const { 9445 EVT VT = N->getValueType(0); 9446 SDValue N0 = N->getOperand(0); 9447 9448 if (N0.isUndef()) 9449 return N0; 9450 9451 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9452 N0.getOpcode() == ISD::SINT_TO_FP)) { 9453 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9454 N->getFlags()); 9455 } 9456 9457 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9458 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9459 N0.getOperand(0), N->getFlags()); 9460 } 9461 9462 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9463 } 9464 9465 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9466 unsigned MaxDepth) const { 9467 unsigned Opcode = Op.getOpcode(); 9468 if (Opcode == ISD::FCANONICALIZE) 9469 return true; 9470 9471 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9472 auto F = CFP->getValueAPF(); 9473 if (F.isNaN() && F.isSignaling()) 9474 return false; 9475 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9476 } 9477 9478 // If source is a result of another standard FP operation it is already in 9479 // canonical form. 9480 if (MaxDepth == 0) 9481 return false; 9482 9483 switch (Opcode) { 9484 // These will flush denorms if required. 9485 case ISD::FADD: 9486 case ISD::FSUB: 9487 case ISD::FMUL: 9488 case ISD::FCEIL: 9489 case ISD::FFLOOR: 9490 case ISD::FMA: 9491 case ISD::FMAD: 9492 case ISD::FSQRT: 9493 case ISD::FDIV: 9494 case ISD::FREM: 9495 case ISD::FP_ROUND: 9496 case ISD::FP_EXTEND: 9497 case AMDGPUISD::FMUL_LEGACY: 9498 case AMDGPUISD::FMAD_FTZ: 9499 case AMDGPUISD::RCP: 9500 case AMDGPUISD::RSQ: 9501 case AMDGPUISD::RSQ_CLAMP: 9502 case AMDGPUISD::RCP_LEGACY: 9503 case AMDGPUISD::RCP_IFLAG: 9504 case AMDGPUISD::DIV_SCALE: 9505 case AMDGPUISD::DIV_FMAS: 9506 case AMDGPUISD::DIV_FIXUP: 9507 case AMDGPUISD::FRACT: 9508 case AMDGPUISD::LDEXP: 9509 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9510 case AMDGPUISD::CVT_F32_UBYTE0: 9511 case AMDGPUISD::CVT_F32_UBYTE1: 9512 case AMDGPUISD::CVT_F32_UBYTE2: 9513 case AMDGPUISD::CVT_F32_UBYTE3: 9514 return true; 9515 9516 // It can/will be lowered or combined as a bit operation. 9517 // Need to check their input recursively to handle. 9518 case ISD::FNEG: 9519 case ISD::FABS: 9520 case ISD::FCOPYSIGN: 9521 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9522 9523 case ISD::FSIN: 9524 case ISD::FCOS: 9525 case ISD::FSINCOS: 9526 return Op.getValueType().getScalarType() != MVT::f16; 9527 9528 case ISD::FMINNUM: 9529 case ISD::FMAXNUM: 9530 case ISD::FMINNUM_IEEE: 9531 case ISD::FMAXNUM_IEEE: 9532 case AMDGPUISD::CLAMP: 9533 case AMDGPUISD::FMED3: 9534 case AMDGPUISD::FMAX3: 9535 case AMDGPUISD::FMIN3: { 9536 // FIXME: Shouldn't treat the generic operations different based these. 9537 // However, we aren't really required to flush the result from 9538 // minnum/maxnum.. 9539 9540 // snans will be quieted, so we only need to worry about denormals. 9541 if (Subtarget->supportsMinMaxDenormModes() || 9542 denormalsEnabledForType(DAG, Op.getValueType())) 9543 return true; 9544 9545 // Flushing may be required. 9546 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9547 // targets need to check their input recursively. 9548 9549 // FIXME: Does this apply with clamp? It's implemented with max. 9550 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9551 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9552 return false; 9553 } 9554 9555 return true; 9556 } 9557 case ISD::SELECT: { 9558 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9559 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9560 } 9561 case ISD::BUILD_VECTOR: { 9562 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9563 SDValue SrcOp = Op.getOperand(i); 9564 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9565 return false; 9566 } 9567 9568 return true; 9569 } 9570 case ISD::EXTRACT_VECTOR_ELT: 9571 case ISD::EXTRACT_SUBVECTOR: { 9572 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9573 } 9574 case ISD::INSERT_VECTOR_ELT: { 9575 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9576 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9577 } 9578 case ISD::UNDEF: 9579 // Could be anything. 9580 return false; 9581 9582 case ISD::BITCAST: { 9583 // Hack round the mess we make when legalizing extract_vector_elt 9584 SDValue Src = Op.getOperand(0); 9585 if (Src.getValueType() == MVT::i16 && 9586 Src.getOpcode() == ISD::TRUNCATE) { 9587 SDValue TruncSrc = Src.getOperand(0); 9588 if (TruncSrc.getValueType() == MVT::i32 && 9589 TruncSrc.getOpcode() == ISD::BITCAST && 9590 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9591 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9592 } 9593 } 9594 9595 return false; 9596 } 9597 case ISD::INTRINSIC_WO_CHAIN: { 9598 unsigned IntrinsicID 9599 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9600 // TODO: Handle more intrinsics 9601 switch (IntrinsicID) { 9602 case Intrinsic::amdgcn_cvt_pkrtz: 9603 case Intrinsic::amdgcn_cubeid: 9604 case Intrinsic::amdgcn_frexp_mant: 9605 case Intrinsic::amdgcn_fdot2: 9606 case Intrinsic::amdgcn_rcp: 9607 case Intrinsic::amdgcn_rsq: 9608 case Intrinsic::amdgcn_rsq_clamp: 9609 case Intrinsic::amdgcn_rcp_legacy: 9610 case Intrinsic::amdgcn_rsq_legacy: 9611 case Intrinsic::amdgcn_trig_preop: 9612 return true; 9613 default: 9614 break; 9615 } 9616 9617 LLVM_FALLTHROUGH; 9618 } 9619 default: 9620 return denormalsEnabledForType(DAG, Op.getValueType()) && 9621 DAG.isKnownNeverSNaN(Op); 9622 } 9623 9624 llvm_unreachable("invalid operation"); 9625 } 9626 9627 // Constant fold canonicalize. 9628 SDValue SITargetLowering::getCanonicalConstantFP( 9629 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9630 // Flush denormals to 0 if not enabled. 9631 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9632 return DAG.getConstantFP(0.0, SL, VT); 9633 9634 if (C.isNaN()) { 9635 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9636 if (C.isSignaling()) { 9637 // Quiet a signaling NaN. 9638 // FIXME: Is this supposed to preserve payload bits? 9639 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9640 } 9641 9642 // Make sure it is the canonical NaN bitpattern. 9643 // 9644 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9645 // immediate? 9646 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9647 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9648 } 9649 9650 // Already canonical. 9651 return DAG.getConstantFP(C, SL, VT); 9652 } 9653 9654 static bool vectorEltWillFoldAway(SDValue Op) { 9655 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9656 } 9657 9658 SDValue SITargetLowering::performFCanonicalizeCombine( 9659 SDNode *N, 9660 DAGCombinerInfo &DCI) const { 9661 SelectionDAG &DAG = DCI.DAG; 9662 SDValue N0 = N->getOperand(0); 9663 EVT VT = N->getValueType(0); 9664 9665 // fcanonicalize undef -> qnan 9666 if (N0.isUndef()) { 9667 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9668 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9669 } 9670 9671 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9672 EVT VT = N->getValueType(0); 9673 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9674 } 9675 9676 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9677 // (fcanonicalize k) 9678 // 9679 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9680 9681 // TODO: This could be better with wider vectors that will be split to v2f16, 9682 // and to consider uses since there aren't that many packed operations. 9683 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9684 isTypeLegal(MVT::v2f16)) { 9685 SDLoc SL(N); 9686 SDValue NewElts[2]; 9687 SDValue Lo = N0.getOperand(0); 9688 SDValue Hi = N0.getOperand(1); 9689 EVT EltVT = Lo.getValueType(); 9690 9691 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9692 for (unsigned I = 0; I != 2; ++I) { 9693 SDValue Op = N0.getOperand(I); 9694 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9695 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9696 CFP->getValueAPF()); 9697 } else if (Op.isUndef()) { 9698 // Handled below based on what the other operand is. 9699 NewElts[I] = Op; 9700 } else { 9701 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9702 } 9703 } 9704 9705 // If one half is undef, and one is constant, perfer a splat vector rather 9706 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9707 // cheaper to use and may be free with a packed operation. 9708 if (NewElts[0].isUndef()) { 9709 if (isa<ConstantFPSDNode>(NewElts[1])) 9710 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9711 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9712 } 9713 9714 if (NewElts[1].isUndef()) { 9715 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9716 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9717 } 9718 9719 return DAG.getBuildVector(VT, SL, NewElts); 9720 } 9721 } 9722 9723 unsigned SrcOpc = N0.getOpcode(); 9724 9725 // If it's free to do so, push canonicalizes further up the source, which may 9726 // find a canonical source. 9727 // 9728 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9729 // sNaNs. 9730 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9731 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9732 if (CRHS && N0.hasOneUse()) { 9733 SDLoc SL(N); 9734 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9735 N0.getOperand(0)); 9736 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9737 DCI.AddToWorklist(Canon0.getNode()); 9738 9739 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9740 } 9741 } 9742 9743 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9744 } 9745 9746 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9747 switch (Opc) { 9748 case ISD::FMAXNUM: 9749 case ISD::FMAXNUM_IEEE: 9750 return AMDGPUISD::FMAX3; 9751 case ISD::SMAX: 9752 return AMDGPUISD::SMAX3; 9753 case ISD::UMAX: 9754 return AMDGPUISD::UMAX3; 9755 case ISD::FMINNUM: 9756 case ISD::FMINNUM_IEEE: 9757 return AMDGPUISD::FMIN3; 9758 case ISD::SMIN: 9759 return AMDGPUISD::SMIN3; 9760 case ISD::UMIN: 9761 return AMDGPUISD::UMIN3; 9762 default: 9763 llvm_unreachable("Not a min/max opcode"); 9764 } 9765 } 9766 9767 SDValue SITargetLowering::performIntMed3ImmCombine( 9768 SelectionDAG &DAG, const SDLoc &SL, 9769 SDValue Op0, SDValue Op1, bool Signed) const { 9770 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9771 if (!K1) 9772 return SDValue(); 9773 9774 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9775 if (!K0) 9776 return SDValue(); 9777 9778 if (Signed) { 9779 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9780 return SDValue(); 9781 } else { 9782 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9783 return SDValue(); 9784 } 9785 9786 EVT VT = K0->getValueType(0); 9787 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9788 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9789 return DAG.getNode(Med3Opc, SL, VT, 9790 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9791 } 9792 9793 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9794 MVT NVT = MVT::i32; 9795 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9796 9797 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9798 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9799 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9800 9801 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9802 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9803 } 9804 9805 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9806 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9807 return C; 9808 9809 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9810 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9811 return C; 9812 } 9813 9814 return nullptr; 9815 } 9816 9817 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9818 const SDLoc &SL, 9819 SDValue Op0, 9820 SDValue Op1) const { 9821 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9822 if (!K1) 9823 return SDValue(); 9824 9825 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9826 if (!K0) 9827 return SDValue(); 9828 9829 // Ordered >= (although NaN inputs should have folded away by now). 9830 if (K0->getValueAPF() > K1->getValueAPF()) 9831 return SDValue(); 9832 9833 const MachineFunction &MF = DAG.getMachineFunction(); 9834 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9835 9836 // TODO: Check IEEE bit enabled? 9837 EVT VT = Op0.getValueType(); 9838 if (Info->getMode().DX10Clamp) { 9839 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9840 // hardware fmed3 behavior converting to a min. 9841 // FIXME: Should this be allowing -0.0? 9842 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9843 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9844 } 9845 9846 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9847 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9848 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9849 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9850 // then give the other result, which is different from med3 with a NaN 9851 // input. 9852 SDValue Var = Op0.getOperand(0); 9853 if (!DAG.isKnownNeverSNaN(Var)) 9854 return SDValue(); 9855 9856 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9857 9858 if ((!K0->hasOneUse() || 9859 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9860 (!K1->hasOneUse() || 9861 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9862 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9863 Var, SDValue(K0, 0), SDValue(K1, 0)); 9864 } 9865 } 9866 9867 return SDValue(); 9868 } 9869 9870 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9871 DAGCombinerInfo &DCI) const { 9872 SelectionDAG &DAG = DCI.DAG; 9873 9874 EVT VT = N->getValueType(0); 9875 unsigned Opc = N->getOpcode(); 9876 SDValue Op0 = N->getOperand(0); 9877 SDValue Op1 = N->getOperand(1); 9878 9879 // Only do this if the inner op has one use since this will just increases 9880 // register pressure for no benefit. 9881 9882 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9883 !VT.isVector() && 9884 (VT == MVT::i32 || VT == MVT::f32 || 9885 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9886 // max(max(a, b), c) -> max3(a, b, c) 9887 // min(min(a, b), c) -> min3(a, b, c) 9888 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9889 SDLoc DL(N); 9890 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9891 DL, 9892 N->getValueType(0), 9893 Op0.getOperand(0), 9894 Op0.getOperand(1), 9895 Op1); 9896 } 9897 9898 // Try commuted. 9899 // max(a, max(b, c)) -> max3(a, b, c) 9900 // min(a, min(b, c)) -> min3(a, b, c) 9901 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9902 SDLoc DL(N); 9903 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9904 DL, 9905 N->getValueType(0), 9906 Op0, 9907 Op1.getOperand(0), 9908 Op1.getOperand(1)); 9909 } 9910 } 9911 9912 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9913 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9914 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9915 return Med3; 9916 } 9917 9918 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9919 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9920 return Med3; 9921 } 9922 9923 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9924 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9925 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9926 (Opc == AMDGPUISD::FMIN_LEGACY && 9927 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9928 (VT == MVT::f32 || VT == MVT::f64 || 9929 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9930 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9931 Op0.hasOneUse()) { 9932 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9933 return Res; 9934 } 9935 9936 return SDValue(); 9937 } 9938 9939 static bool isClampZeroToOne(SDValue A, SDValue B) { 9940 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9941 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9942 // FIXME: Should this be allowing -0.0? 9943 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9944 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9945 } 9946 } 9947 9948 return false; 9949 } 9950 9951 // FIXME: Should only worry about snans for version with chain. 9952 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9953 DAGCombinerInfo &DCI) const { 9954 EVT VT = N->getValueType(0); 9955 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9956 // NaNs. With a NaN input, the order of the operands may change the result. 9957 9958 SelectionDAG &DAG = DCI.DAG; 9959 SDLoc SL(N); 9960 9961 SDValue Src0 = N->getOperand(0); 9962 SDValue Src1 = N->getOperand(1); 9963 SDValue Src2 = N->getOperand(2); 9964 9965 if (isClampZeroToOne(Src0, Src1)) { 9966 // const_a, const_b, x -> clamp is safe in all cases including signaling 9967 // nans. 9968 // FIXME: Should this be allowing -0.0? 9969 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9970 } 9971 9972 const MachineFunction &MF = DAG.getMachineFunction(); 9973 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9974 9975 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9976 // handling no dx10-clamp? 9977 if (Info->getMode().DX10Clamp) { 9978 // If NaNs is clamped to 0, we are free to reorder the inputs. 9979 9980 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9981 std::swap(Src0, Src1); 9982 9983 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9984 std::swap(Src1, Src2); 9985 9986 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9987 std::swap(Src0, Src1); 9988 9989 if (isClampZeroToOne(Src1, Src2)) 9990 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9991 } 9992 9993 return SDValue(); 9994 } 9995 9996 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9997 DAGCombinerInfo &DCI) const { 9998 SDValue Src0 = N->getOperand(0); 9999 SDValue Src1 = N->getOperand(1); 10000 if (Src0.isUndef() && Src1.isUndef()) 10001 return DCI.DAG.getUNDEF(N->getValueType(0)); 10002 return SDValue(); 10003 } 10004 10005 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10006 // expanded into a set of cmp/select instructions. 10007 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10008 unsigned NumElem, 10009 bool IsDivergentIdx) { 10010 if (UseDivergentRegisterIndexing) 10011 return false; 10012 10013 unsigned VecSize = EltSize * NumElem; 10014 10015 // Sub-dword vectors of size 2 dword or less have better implementation. 10016 if (VecSize <= 64 && EltSize < 32) 10017 return false; 10018 10019 // Always expand the rest of sub-dword instructions, otherwise it will be 10020 // lowered via memory. 10021 if (EltSize < 32) 10022 return true; 10023 10024 // Always do this if var-idx is divergent, otherwise it will become a loop. 10025 if (IsDivergentIdx) 10026 return true; 10027 10028 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10029 unsigned NumInsts = NumElem /* Number of compares */ + 10030 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10031 return NumInsts <= 16; 10032 } 10033 10034 static bool shouldExpandVectorDynExt(SDNode *N) { 10035 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10036 if (isa<ConstantSDNode>(Idx)) 10037 return false; 10038 10039 SDValue Vec = N->getOperand(0); 10040 EVT VecVT = Vec.getValueType(); 10041 EVT EltVT = VecVT.getVectorElementType(); 10042 unsigned EltSize = EltVT.getSizeInBits(); 10043 unsigned NumElem = VecVT.getVectorNumElements(); 10044 10045 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10046 Idx->isDivergent()); 10047 } 10048 10049 SDValue SITargetLowering::performExtractVectorEltCombine( 10050 SDNode *N, DAGCombinerInfo &DCI) const { 10051 SDValue Vec = N->getOperand(0); 10052 SelectionDAG &DAG = DCI.DAG; 10053 10054 EVT VecVT = Vec.getValueType(); 10055 EVT EltVT = VecVT.getVectorElementType(); 10056 10057 if ((Vec.getOpcode() == ISD::FNEG || 10058 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10059 SDLoc SL(N); 10060 EVT EltVT = N->getValueType(0); 10061 SDValue Idx = N->getOperand(1); 10062 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10063 Vec.getOperand(0), Idx); 10064 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10065 } 10066 10067 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10068 // => 10069 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10070 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10071 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10072 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10073 SDLoc SL(N); 10074 EVT EltVT = N->getValueType(0); 10075 SDValue Idx = N->getOperand(1); 10076 unsigned Opc = Vec.getOpcode(); 10077 10078 switch(Opc) { 10079 default: 10080 break; 10081 // TODO: Support other binary operations. 10082 case ISD::FADD: 10083 case ISD::FSUB: 10084 case ISD::FMUL: 10085 case ISD::ADD: 10086 case ISD::UMIN: 10087 case ISD::UMAX: 10088 case ISD::SMIN: 10089 case ISD::SMAX: 10090 case ISD::FMAXNUM: 10091 case ISD::FMINNUM: 10092 case ISD::FMAXNUM_IEEE: 10093 case ISD::FMINNUM_IEEE: { 10094 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10095 Vec.getOperand(0), Idx); 10096 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10097 Vec.getOperand(1), Idx); 10098 10099 DCI.AddToWorklist(Elt0.getNode()); 10100 DCI.AddToWorklist(Elt1.getNode()); 10101 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10102 } 10103 } 10104 } 10105 10106 unsigned VecSize = VecVT.getSizeInBits(); 10107 unsigned EltSize = EltVT.getSizeInBits(); 10108 10109 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10110 if (::shouldExpandVectorDynExt(N)) { 10111 SDLoc SL(N); 10112 SDValue Idx = N->getOperand(1); 10113 SDValue V; 10114 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10115 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10116 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10117 if (I == 0) 10118 V = Elt; 10119 else 10120 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10121 } 10122 return V; 10123 } 10124 10125 if (!DCI.isBeforeLegalize()) 10126 return SDValue(); 10127 10128 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10129 // elements. This exposes more load reduction opportunities by replacing 10130 // multiple small extract_vector_elements with a single 32-bit extract. 10131 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10132 if (isa<MemSDNode>(Vec) && 10133 EltSize <= 16 && 10134 EltVT.isByteSized() && 10135 VecSize > 32 && 10136 VecSize % 32 == 0 && 10137 Idx) { 10138 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10139 10140 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10141 unsigned EltIdx = BitIndex / 32; 10142 unsigned LeftoverBitIdx = BitIndex % 32; 10143 SDLoc SL(N); 10144 10145 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10146 DCI.AddToWorklist(Cast.getNode()); 10147 10148 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10149 DAG.getConstant(EltIdx, SL, MVT::i32)); 10150 DCI.AddToWorklist(Elt.getNode()); 10151 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10152 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10153 DCI.AddToWorklist(Srl.getNode()); 10154 10155 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10156 DCI.AddToWorklist(Trunc.getNode()); 10157 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10158 } 10159 10160 return SDValue(); 10161 } 10162 10163 SDValue 10164 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10165 DAGCombinerInfo &DCI) const { 10166 SDValue Vec = N->getOperand(0); 10167 SDValue Idx = N->getOperand(2); 10168 EVT VecVT = Vec.getValueType(); 10169 EVT EltVT = VecVT.getVectorElementType(); 10170 10171 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10172 // => BUILD_VECTOR n x select (e, const-idx) 10173 if (!::shouldExpandVectorDynExt(N)) 10174 return SDValue(); 10175 10176 SelectionDAG &DAG = DCI.DAG; 10177 SDLoc SL(N); 10178 SDValue Ins = N->getOperand(1); 10179 EVT IdxVT = Idx.getValueType(); 10180 10181 SmallVector<SDValue, 16> Ops; 10182 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10183 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10184 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10185 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10186 Ops.push_back(V); 10187 } 10188 10189 return DAG.getBuildVector(VecVT, SL, Ops); 10190 } 10191 10192 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10193 const SDNode *N0, 10194 const SDNode *N1) const { 10195 EVT VT = N0->getValueType(0); 10196 10197 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10198 // support denormals ever. 10199 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10200 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10201 getSubtarget()->hasMadF16())) && 10202 isOperationLegal(ISD::FMAD, VT)) 10203 return ISD::FMAD; 10204 10205 const TargetOptions &Options = DAG.getTarget().Options; 10206 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10207 (N0->getFlags().hasAllowContract() && 10208 N1->getFlags().hasAllowContract())) && 10209 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10210 return ISD::FMA; 10211 } 10212 10213 return 0; 10214 } 10215 10216 // For a reassociatable opcode perform: 10217 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10218 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10219 SelectionDAG &DAG) const { 10220 EVT VT = N->getValueType(0); 10221 if (VT != MVT::i32 && VT != MVT::i64) 10222 return SDValue(); 10223 10224 unsigned Opc = N->getOpcode(); 10225 SDValue Op0 = N->getOperand(0); 10226 SDValue Op1 = N->getOperand(1); 10227 10228 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10229 return SDValue(); 10230 10231 if (Op0->isDivergent()) 10232 std::swap(Op0, Op1); 10233 10234 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10235 return SDValue(); 10236 10237 SDValue Op2 = Op1.getOperand(1); 10238 Op1 = Op1.getOperand(0); 10239 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10240 return SDValue(); 10241 10242 if (Op1->isDivergent()) 10243 std::swap(Op1, Op2); 10244 10245 // If either operand is constant this will conflict with 10246 // DAGCombiner::ReassociateOps(). 10247 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10248 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10249 return SDValue(); 10250 10251 SDLoc SL(N); 10252 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10253 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10254 } 10255 10256 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10257 EVT VT, 10258 SDValue N0, SDValue N1, SDValue N2, 10259 bool Signed) { 10260 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10261 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10262 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10263 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10264 } 10265 10266 SDValue SITargetLowering::performAddCombine(SDNode *N, 10267 DAGCombinerInfo &DCI) const { 10268 SelectionDAG &DAG = DCI.DAG; 10269 EVT VT = N->getValueType(0); 10270 SDLoc SL(N); 10271 SDValue LHS = N->getOperand(0); 10272 SDValue RHS = N->getOperand(1); 10273 10274 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10275 && Subtarget->hasMad64_32() && 10276 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10277 VT.getScalarSizeInBits() <= 64) { 10278 if (LHS.getOpcode() != ISD::MUL) 10279 std::swap(LHS, RHS); 10280 10281 SDValue MulLHS = LHS.getOperand(0); 10282 SDValue MulRHS = LHS.getOperand(1); 10283 SDValue AddRHS = RHS; 10284 10285 // TODO: Maybe restrict if SGPR inputs. 10286 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10287 numBitsUnsigned(MulRHS, DAG) <= 32) { 10288 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10289 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10290 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10291 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10292 } 10293 10294 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10295 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10296 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10297 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10298 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10299 } 10300 10301 return SDValue(); 10302 } 10303 10304 if (SDValue V = reassociateScalarOps(N, DAG)) { 10305 return V; 10306 } 10307 10308 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10309 return SDValue(); 10310 10311 // add x, zext (setcc) => addcarry x, 0, setcc 10312 // add x, sext (setcc) => subcarry x, 0, setcc 10313 unsigned Opc = LHS.getOpcode(); 10314 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10315 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10316 std::swap(RHS, LHS); 10317 10318 Opc = RHS.getOpcode(); 10319 switch (Opc) { 10320 default: break; 10321 case ISD::ZERO_EXTEND: 10322 case ISD::SIGN_EXTEND: 10323 case ISD::ANY_EXTEND: { 10324 auto Cond = RHS.getOperand(0); 10325 // If this won't be a real VOPC output, we would still need to insert an 10326 // extra instruction anyway. 10327 if (!isBoolSGPR(Cond)) 10328 break; 10329 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10330 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10331 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10332 return DAG.getNode(Opc, SL, VTList, Args); 10333 } 10334 case ISD::ADDCARRY: { 10335 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10336 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10337 if (!C || C->getZExtValue() != 0) break; 10338 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10339 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10340 } 10341 } 10342 return SDValue(); 10343 } 10344 10345 SDValue SITargetLowering::performSubCombine(SDNode *N, 10346 DAGCombinerInfo &DCI) const { 10347 SelectionDAG &DAG = DCI.DAG; 10348 EVT VT = N->getValueType(0); 10349 10350 if (VT != MVT::i32) 10351 return SDValue(); 10352 10353 SDLoc SL(N); 10354 SDValue LHS = N->getOperand(0); 10355 SDValue RHS = N->getOperand(1); 10356 10357 // sub x, zext (setcc) => subcarry x, 0, setcc 10358 // sub x, sext (setcc) => addcarry x, 0, setcc 10359 unsigned Opc = RHS.getOpcode(); 10360 switch (Opc) { 10361 default: break; 10362 case ISD::ZERO_EXTEND: 10363 case ISD::SIGN_EXTEND: 10364 case ISD::ANY_EXTEND: { 10365 auto Cond = RHS.getOperand(0); 10366 // If this won't be a real VOPC output, we would still need to insert an 10367 // extra instruction anyway. 10368 if (!isBoolSGPR(Cond)) 10369 break; 10370 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10371 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10372 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10373 return DAG.getNode(Opc, SL, VTList, Args); 10374 } 10375 } 10376 10377 if (LHS.getOpcode() == ISD::SUBCARRY) { 10378 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10379 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10380 if (!C || !C->isNullValue()) 10381 return SDValue(); 10382 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10383 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10384 } 10385 return SDValue(); 10386 } 10387 10388 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10389 DAGCombinerInfo &DCI) const { 10390 10391 if (N->getValueType(0) != MVT::i32) 10392 return SDValue(); 10393 10394 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10395 if (!C || C->getZExtValue() != 0) 10396 return SDValue(); 10397 10398 SelectionDAG &DAG = DCI.DAG; 10399 SDValue LHS = N->getOperand(0); 10400 10401 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10402 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10403 unsigned LHSOpc = LHS.getOpcode(); 10404 unsigned Opc = N->getOpcode(); 10405 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10406 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10407 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10408 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10409 } 10410 return SDValue(); 10411 } 10412 10413 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10414 DAGCombinerInfo &DCI) const { 10415 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10416 return SDValue(); 10417 10418 SelectionDAG &DAG = DCI.DAG; 10419 EVT VT = N->getValueType(0); 10420 10421 SDLoc SL(N); 10422 SDValue LHS = N->getOperand(0); 10423 SDValue RHS = N->getOperand(1); 10424 10425 // These should really be instruction patterns, but writing patterns with 10426 // source modiifiers is a pain. 10427 10428 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10429 if (LHS.getOpcode() == ISD::FADD) { 10430 SDValue A = LHS.getOperand(0); 10431 if (A == LHS.getOperand(1)) { 10432 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10433 if (FusedOp != 0) { 10434 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10435 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10436 } 10437 } 10438 } 10439 10440 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10441 if (RHS.getOpcode() == ISD::FADD) { 10442 SDValue A = RHS.getOperand(0); 10443 if (A == RHS.getOperand(1)) { 10444 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10445 if (FusedOp != 0) { 10446 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10447 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10448 } 10449 } 10450 } 10451 10452 return SDValue(); 10453 } 10454 10455 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10456 DAGCombinerInfo &DCI) const { 10457 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10458 return SDValue(); 10459 10460 SelectionDAG &DAG = DCI.DAG; 10461 SDLoc SL(N); 10462 EVT VT = N->getValueType(0); 10463 assert(!VT.isVector()); 10464 10465 // Try to get the fneg to fold into the source modifier. This undoes generic 10466 // DAG combines and folds them into the mad. 10467 // 10468 // Only do this if we are not trying to support denormals. v_mad_f32 does 10469 // not support denormals ever. 10470 SDValue LHS = N->getOperand(0); 10471 SDValue RHS = N->getOperand(1); 10472 if (LHS.getOpcode() == ISD::FADD) { 10473 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10474 SDValue A = LHS.getOperand(0); 10475 if (A == LHS.getOperand(1)) { 10476 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10477 if (FusedOp != 0){ 10478 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10479 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10480 10481 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10482 } 10483 } 10484 } 10485 10486 if (RHS.getOpcode() == ISD::FADD) { 10487 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10488 10489 SDValue A = RHS.getOperand(0); 10490 if (A == RHS.getOperand(1)) { 10491 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10492 if (FusedOp != 0){ 10493 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10494 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10495 } 10496 } 10497 } 10498 10499 return SDValue(); 10500 } 10501 10502 SDValue SITargetLowering::performFMACombine(SDNode *N, 10503 DAGCombinerInfo &DCI) const { 10504 SelectionDAG &DAG = DCI.DAG; 10505 EVT VT = N->getValueType(0); 10506 SDLoc SL(N); 10507 10508 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10509 return SDValue(); 10510 10511 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10512 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10513 SDValue Op1 = N->getOperand(0); 10514 SDValue Op2 = N->getOperand(1); 10515 SDValue FMA = N->getOperand(2); 10516 10517 if (FMA.getOpcode() != ISD::FMA || 10518 Op1.getOpcode() != ISD::FP_EXTEND || 10519 Op2.getOpcode() != ISD::FP_EXTEND) 10520 return SDValue(); 10521 10522 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10523 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10524 // is sufficient to allow generaing fdot2. 10525 const TargetOptions &Options = DAG.getTarget().Options; 10526 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10527 (N->getFlags().hasAllowContract() && 10528 FMA->getFlags().hasAllowContract())) { 10529 Op1 = Op1.getOperand(0); 10530 Op2 = Op2.getOperand(0); 10531 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10532 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10533 return SDValue(); 10534 10535 SDValue Vec1 = Op1.getOperand(0); 10536 SDValue Idx1 = Op1.getOperand(1); 10537 SDValue Vec2 = Op2.getOperand(0); 10538 10539 SDValue FMAOp1 = FMA.getOperand(0); 10540 SDValue FMAOp2 = FMA.getOperand(1); 10541 SDValue FMAAcc = FMA.getOperand(2); 10542 10543 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10544 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10545 return SDValue(); 10546 10547 FMAOp1 = FMAOp1.getOperand(0); 10548 FMAOp2 = FMAOp2.getOperand(0); 10549 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10550 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10551 return SDValue(); 10552 10553 SDValue Vec3 = FMAOp1.getOperand(0); 10554 SDValue Vec4 = FMAOp2.getOperand(0); 10555 SDValue Idx2 = FMAOp1.getOperand(1); 10556 10557 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10558 // Idx1 and Idx2 cannot be the same. 10559 Idx1 == Idx2) 10560 return SDValue(); 10561 10562 if (Vec1 == Vec2 || Vec3 == Vec4) 10563 return SDValue(); 10564 10565 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10566 return SDValue(); 10567 10568 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10569 (Vec1 == Vec4 && Vec2 == Vec3)) { 10570 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10571 DAG.getTargetConstant(0, SL, MVT::i1)); 10572 } 10573 } 10574 return SDValue(); 10575 } 10576 10577 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10578 DAGCombinerInfo &DCI) const { 10579 SelectionDAG &DAG = DCI.DAG; 10580 SDLoc SL(N); 10581 10582 SDValue LHS = N->getOperand(0); 10583 SDValue RHS = N->getOperand(1); 10584 EVT VT = LHS.getValueType(); 10585 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10586 10587 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10588 if (!CRHS) { 10589 CRHS = dyn_cast<ConstantSDNode>(LHS); 10590 if (CRHS) { 10591 std::swap(LHS, RHS); 10592 CC = getSetCCSwappedOperands(CC); 10593 } 10594 } 10595 10596 if (CRHS) { 10597 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10598 isBoolSGPR(LHS.getOperand(0))) { 10599 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10600 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10601 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10602 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10603 if ((CRHS->isAllOnesValue() && 10604 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10605 (CRHS->isNullValue() && 10606 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10607 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10608 DAG.getConstant(-1, SL, MVT::i1)); 10609 if ((CRHS->isAllOnesValue() && 10610 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10611 (CRHS->isNullValue() && 10612 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10613 return LHS.getOperand(0); 10614 } 10615 10616 uint64_t CRHSVal = CRHS->getZExtValue(); 10617 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10618 LHS.getOpcode() == ISD::SELECT && 10619 isa<ConstantSDNode>(LHS.getOperand(1)) && 10620 isa<ConstantSDNode>(LHS.getOperand(2)) && 10621 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10622 isBoolSGPR(LHS.getOperand(0))) { 10623 // Given CT != FT: 10624 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10625 // setcc (select cc, CT, CF), CF, ne => cc 10626 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10627 // setcc (select cc, CT, CF), CT, eq => cc 10628 uint64_t CT = LHS.getConstantOperandVal(1); 10629 uint64_t CF = LHS.getConstantOperandVal(2); 10630 10631 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10632 (CT == CRHSVal && CC == ISD::SETNE)) 10633 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10634 DAG.getConstant(-1, SL, MVT::i1)); 10635 if ((CF == CRHSVal && CC == ISD::SETNE) || 10636 (CT == CRHSVal && CC == ISD::SETEQ)) 10637 return LHS.getOperand(0); 10638 } 10639 } 10640 10641 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10642 VT != MVT::f16)) 10643 return SDValue(); 10644 10645 // Match isinf/isfinite pattern 10646 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10647 // (fcmp one (fabs x), inf) -> (fp_class x, 10648 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10649 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10650 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10651 if (!CRHS) 10652 return SDValue(); 10653 10654 const APFloat &APF = CRHS->getValueAPF(); 10655 if (APF.isInfinity() && !APF.isNegative()) { 10656 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10657 SIInstrFlags::N_INFINITY; 10658 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10659 SIInstrFlags::P_ZERO | 10660 SIInstrFlags::N_NORMAL | 10661 SIInstrFlags::P_NORMAL | 10662 SIInstrFlags::N_SUBNORMAL | 10663 SIInstrFlags::P_SUBNORMAL; 10664 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10665 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10666 DAG.getConstant(Mask, SL, MVT::i32)); 10667 } 10668 } 10669 10670 return SDValue(); 10671 } 10672 10673 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10674 DAGCombinerInfo &DCI) const { 10675 SelectionDAG &DAG = DCI.DAG; 10676 SDLoc SL(N); 10677 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10678 10679 SDValue Src = N->getOperand(0); 10680 SDValue Shift = N->getOperand(0); 10681 10682 // TODO: Extend type shouldn't matter (assuming legal types). 10683 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10684 Shift = Shift.getOperand(0); 10685 10686 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10687 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10688 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10689 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10690 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10691 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10692 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10693 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10694 SDLoc(Shift.getOperand(0)), MVT::i32); 10695 10696 unsigned ShiftOffset = 8 * Offset; 10697 if (Shift.getOpcode() == ISD::SHL) 10698 ShiftOffset -= C->getZExtValue(); 10699 else 10700 ShiftOffset += C->getZExtValue(); 10701 10702 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10703 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10704 MVT::f32, Shift); 10705 } 10706 } 10707 } 10708 10709 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10710 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10711 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10712 // We simplified Src. If this node is not dead, visit it again so it is 10713 // folded properly. 10714 if (N->getOpcode() != ISD::DELETED_NODE) 10715 DCI.AddToWorklist(N); 10716 return SDValue(N, 0); 10717 } 10718 10719 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10720 if (SDValue DemandedSrc = 10721 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10722 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10723 10724 return SDValue(); 10725 } 10726 10727 SDValue SITargetLowering::performClampCombine(SDNode *N, 10728 DAGCombinerInfo &DCI) const { 10729 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10730 if (!CSrc) 10731 return SDValue(); 10732 10733 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10734 const APFloat &F = CSrc->getValueAPF(); 10735 APFloat Zero = APFloat::getZero(F.getSemantics()); 10736 if (F < Zero || 10737 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10738 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10739 } 10740 10741 APFloat One(F.getSemantics(), "1.0"); 10742 if (F > One) 10743 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10744 10745 return SDValue(CSrc, 0); 10746 } 10747 10748 10749 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10750 DAGCombinerInfo &DCI) const { 10751 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10752 return SDValue(); 10753 switch (N->getOpcode()) { 10754 case ISD::ADD: 10755 return performAddCombine(N, DCI); 10756 case ISD::SUB: 10757 return performSubCombine(N, DCI); 10758 case ISD::ADDCARRY: 10759 case ISD::SUBCARRY: 10760 return performAddCarrySubCarryCombine(N, DCI); 10761 case ISD::FADD: 10762 return performFAddCombine(N, DCI); 10763 case ISD::FSUB: 10764 return performFSubCombine(N, DCI); 10765 case ISD::SETCC: 10766 return performSetCCCombine(N, DCI); 10767 case ISD::FMAXNUM: 10768 case ISD::FMINNUM: 10769 case ISD::FMAXNUM_IEEE: 10770 case ISD::FMINNUM_IEEE: 10771 case ISD::SMAX: 10772 case ISD::SMIN: 10773 case ISD::UMAX: 10774 case ISD::UMIN: 10775 case AMDGPUISD::FMIN_LEGACY: 10776 case AMDGPUISD::FMAX_LEGACY: 10777 return performMinMaxCombine(N, DCI); 10778 case ISD::FMA: 10779 return performFMACombine(N, DCI); 10780 case ISD::AND: 10781 return performAndCombine(N, DCI); 10782 case ISD::OR: 10783 return performOrCombine(N, DCI); 10784 case ISD::XOR: 10785 return performXorCombine(N, DCI); 10786 case ISD::ZERO_EXTEND: 10787 return performZeroExtendCombine(N, DCI); 10788 case ISD::SIGN_EXTEND_INREG: 10789 return performSignExtendInRegCombine(N , DCI); 10790 case AMDGPUISD::FP_CLASS: 10791 return performClassCombine(N, DCI); 10792 case ISD::FCANONICALIZE: 10793 return performFCanonicalizeCombine(N, DCI); 10794 case AMDGPUISD::RCP: 10795 return performRcpCombine(N, DCI); 10796 case AMDGPUISD::FRACT: 10797 case AMDGPUISD::RSQ: 10798 case AMDGPUISD::RCP_LEGACY: 10799 case AMDGPUISD::RCP_IFLAG: 10800 case AMDGPUISD::RSQ_CLAMP: 10801 case AMDGPUISD::LDEXP: { 10802 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10803 SDValue Src = N->getOperand(0); 10804 if (Src.isUndef()) 10805 return Src; 10806 break; 10807 } 10808 case ISD::SINT_TO_FP: 10809 case ISD::UINT_TO_FP: 10810 return performUCharToFloatCombine(N, DCI); 10811 case AMDGPUISD::CVT_F32_UBYTE0: 10812 case AMDGPUISD::CVT_F32_UBYTE1: 10813 case AMDGPUISD::CVT_F32_UBYTE2: 10814 case AMDGPUISD::CVT_F32_UBYTE3: 10815 return performCvtF32UByteNCombine(N, DCI); 10816 case AMDGPUISD::FMED3: 10817 return performFMed3Combine(N, DCI); 10818 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10819 return performCvtPkRTZCombine(N, DCI); 10820 case AMDGPUISD::CLAMP: 10821 return performClampCombine(N, DCI); 10822 case ISD::SCALAR_TO_VECTOR: { 10823 SelectionDAG &DAG = DCI.DAG; 10824 EVT VT = N->getValueType(0); 10825 10826 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10827 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10828 SDLoc SL(N); 10829 SDValue Src = N->getOperand(0); 10830 EVT EltVT = Src.getValueType(); 10831 if (EltVT == MVT::f16) 10832 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10833 10834 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10835 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10836 } 10837 10838 break; 10839 } 10840 case ISD::EXTRACT_VECTOR_ELT: 10841 return performExtractVectorEltCombine(N, DCI); 10842 case ISD::INSERT_VECTOR_ELT: 10843 return performInsertVectorEltCombine(N, DCI); 10844 case ISD::LOAD: { 10845 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10846 return Widended; 10847 LLVM_FALLTHROUGH; 10848 } 10849 default: { 10850 if (!DCI.isBeforeLegalize()) { 10851 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10852 return performMemSDNodeCombine(MemNode, DCI); 10853 } 10854 10855 break; 10856 } 10857 } 10858 10859 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10860 } 10861 10862 /// Helper function for adjustWritemask 10863 static unsigned SubIdx2Lane(unsigned Idx) { 10864 switch (Idx) { 10865 default: return ~0u; 10866 case AMDGPU::sub0: return 0; 10867 case AMDGPU::sub1: return 1; 10868 case AMDGPU::sub2: return 2; 10869 case AMDGPU::sub3: return 3; 10870 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10871 } 10872 } 10873 10874 /// Adjust the writemask of MIMG instructions 10875 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10876 SelectionDAG &DAG) const { 10877 unsigned Opcode = Node->getMachineOpcode(); 10878 10879 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10880 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10881 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10882 return Node; // not implemented for D16 10883 10884 SDNode *Users[5] = { nullptr }; 10885 unsigned Lane = 0; 10886 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10887 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10888 unsigned NewDmask = 0; 10889 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10890 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10891 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10892 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10893 unsigned TFCLane = 0; 10894 bool HasChain = Node->getNumValues() > 1; 10895 10896 if (OldDmask == 0) { 10897 // These are folded out, but on the chance it happens don't assert. 10898 return Node; 10899 } 10900 10901 unsigned OldBitsSet = countPopulation(OldDmask); 10902 // Work out which is the TFE/LWE lane if that is enabled. 10903 if (UsesTFC) { 10904 TFCLane = OldBitsSet; 10905 } 10906 10907 // Try to figure out the used register components 10908 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10909 I != E; ++I) { 10910 10911 // Don't look at users of the chain. 10912 if (I.getUse().getResNo() != 0) 10913 continue; 10914 10915 // Abort if we can't understand the usage 10916 if (!I->isMachineOpcode() || 10917 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10918 return Node; 10919 10920 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10921 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10922 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10923 // set, etc. 10924 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10925 if (Lane == ~0u) 10926 return Node; 10927 10928 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10929 if (UsesTFC && Lane == TFCLane) { 10930 Users[Lane] = *I; 10931 } else { 10932 // Set which texture component corresponds to the lane. 10933 unsigned Comp; 10934 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10935 Comp = countTrailingZeros(Dmask); 10936 Dmask &= ~(1 << Comp); 10937 } 10938 10939 // Abort if we have more than one user per component. 10940 if (Users[Lane]) 10941 return Node; 10942 10943 Users[Lane] = *I; 10944 NewDmask |= 1 << Comp; 10945 } 10946 } 10947 10948 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10949 bool NoChannels = !NewDmask; 10950 if (NoChannels) { 10951 if (!UsesTFC) { 10952 // No uses of the result and not using TFC. Then do nothing. 10953 return Node; 10954 } 10955 // If the original dmask has one channel - then nothing to do 10956 if (OldBitsSet == 1) 10957 return Node; 10958 // Use an arbitrary dmask - required for the instruction to work 10959 NewDmask = 1; 10960 } 10961 // Abort if there's no change 10962 if (NewDmask == OldDmask) 10963 return Node; 10964 10965 unsigned BitsSet = countPopulation(NewDmask); 10966 10967 // Check for TFE or LWE - increase the number of channels by one to account 10968 // for the extra return value 10969 // This will need adjustment for D16 if this is also included in 10970 // adjustWriteMask (this function) but at present D16 are excluded. 10971 unsigned NewChannels = BitsSet + UsesTFC; 10972 10973 int NewOpcode = 10974 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10975 assert(NewOpcode != -1 && 10976 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10977 "failed to find equivalent MIMG op"); 10978 10979 // Adjust the writemask in the node 10980 SmallVector<SDValue, 12> Ops; 10981 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10982 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10983 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10984 10985 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10986 10987 MVT ResultVT = NewChannels == 1 ? 10988 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10989 NewChannels == 5 ? 8 : NewChannels); 10990 SDVTList NewVTList = HasChain ? 10991 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10992 10993 10994 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10995 NewVTList, Ops); 10996 10997 if (HasChain) { 10998 // Update chain. 10999 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11000 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11001 } 11002 11003 if (NewChannels == 1) { 11004 assert(Node->hasNUsesOfValue(1, 0)); 11005 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11006 SDLoc(Node), Users[Lane]->getValueType(0), 11007 SDValue(NewNode, 0)); 11008 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11009 return nullptr; 11010 } 11011 11012 // Update the users of the node with the new indices 11013 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11014 SDNode *User = Users[i]; 11015 if (!User) { 11016 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11017 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11018 if (i || !NoChannels) 11019 continue; 11020 } else { 11021 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11022 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11023 } 11024 11025 switch (Idx) { 11026 default: break; 11027 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11028 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11029 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11030 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11031 } 11032 } 11033 11034 DAG.RemoveDeadNode(Node); 11035 return nullptr; 11036 } 11037 11038 static bool isFrameIndexOp(SDValue Op) { 11039 if (Op.getOpcode() == ISD::AssertZext) 11040 Op = Op.getOperand(0); 11041 11042 return isa<FrameIndexSDNode>(Op); 11043 } 11044 11045 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11046 /// with frame index operands. 11047 /// LLVM assumes that inputs are to these instructions are registers. 11048 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11049 SelectionDAG &DAG) const { 11050 if (Node->getOpcode() == ISD::CopyToReg) { 11051 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11052 SDValue SrcVal = Node->getOperand(2); 11053 11054 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11055 // to try understanding copies to physical registers. 11056 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11057 SDLoc SL(Node); 11058 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11059 SDValue VReg = DAG.getRegister( 11060 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11061 11062 SDNode *Glued = Node->getGluedNode(); 11063 SDValue ToVReg 11064 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11065 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11066 SDValue ToResultReg 11067 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11068 VReg, ToVReg.getValue(1)); 11069 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11070 DAG.RemoveDeadNode(Node); 11071 return ToResultReg.getNode(); 11072 } 11073 } 11074 11075 SmallVector<SDValue, 8> Ops; 11076 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11077 if (!isFrameIndexOp(Node->getOperand(i))) { 11078 Ops.push_back(Node->getOperand(i)); 11079 continue; 11080 } 11081 11082 SDLoc DL(Node); 11083 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11084 Node->getOperand(i).getValueType(), 11085 Node->getOperand(i)), 0)); 11086 } 11087 11088 return DAG.UpdateNodeOperands(Node, Ops); 11089 } 11090 11091 /// Fold the instructions after selecting them. 11092 /// Returns null if users were already updated. 11093 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11094 SelectionDAG &DAG) const { 11095 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11096 unsigned Opcode = Node->getMachineOpcode(); 11097 11098 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11099 !TII->isGather4(Opcode) && 11100 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11101 return adjustWritemask(Node, DAG); 11102 } 11103 11104 if (Opcode == AMDGPU::INSERT_SUBREG || 11105 Opcode == AMDGPU::REG_SEQUENCE) { 11106 legalizeTargetIndependentNode(Node, DAG); 11107 return Node; 11108 } 11109 11110 switch (Opcode) { 11111 case AMDGPU::V_DIV_SCALE_F32: 11112 case AMDGPU::V_DIV_SCALE_F64: { 11113 // Satisfy the operand register constraint when one of the inputs is 11114 // undefined. Ordinarily each undef value will have its own implicit_def of 11115 // a vreg, so force these to use a single register. 11116 SDValue Src0 = Node->getOperand(1); 11117 SDValue Src1 = Node->getOperand(3); 11118 SDValue Src2 = Node->getOperand(5); 11119 11120 if ((Src0.isMachineOpcode() && 11121 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11122 (Src0 == Src1 || Src0 == Src2)) 11123 break; 11124 11125 MVT VT = Src0.getValueType().getSimpleVT(); 11126 const TargetRegisterClass *RC = 11127 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11128 11129 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11130 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11131 11132 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11133 UndefReg, Src0, SDValue()); 11134 11135 // src0 must be the same register as src1 or src2, even if the value is 11136 // undefined, so make sure we don't violate this constraint. 11137 if (Src0.isMachineOpcode() && 11138 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11139 if (Src1.isMachineOpcode() && 11140 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11141 Src0 = Src1; 11142 else if (Src2.isMachineOpcode() && 11143 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11144 Src0 = Src2; 11145 else { 11146 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11147 Src0 = UndefReg; 11148 Src1 = UndefReg; 11149 } 11150 } else 11151 break; 11152 11153 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11154 Ops[1] = Src0; 11155 Ops[3] = Src1; 11156 Ops[5] = Src2; 11157 Ops.push_back(ImpDef.getValue(1)); 11158 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11159 } 11160 default: 11161 break; 11162 } 11163 11164 return Node; 11165 } 11166 11167 /// Assign the register class depending on the number of 11168 /// bits set in the writemask 11169 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11170 SDNode *Node) const { 11171 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11172 11173 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11174 11175 if (TII->isVOP3(MI.getOpcode())) { 11176 // Make sure constant bus requirements are respected. 11177 TII->legalizeOperandsVOP3(MRI, MI); 11178 11179 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11180 // This saves a chain-copy of registers and better ballance register 11181 // use between vgpr and agpr as agpr tuples tend to be big. 11182 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11183 unsigned Opc = MI.getOpcode(); 11184 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11185 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11186 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11187 if (I == -1) 11188 break; 11189 MachineOperand &Op = MI.getOperand(I); 11190 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11191 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11192 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11193 continue; 11194 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11195 if (!Src || !Src->isCopy() || 11196 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11197 continue; 11198 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11199 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11200 // All uses of agpr64 and agpr32 can also accept vgpr except for 11201 // v_accvgpr_read, but we do not produce agpr reads during selection, 11202 // so no use checks are needed. 11203 MRI.setRegClass(Op.getReg(), NewRC); 11204 } 11205 } 11206 11207 return; 11208 } 11209 11210 // Replace unused atomics with the no return version. 11211 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11212 if (NoRetAtomicOp != -1) { 11213 if (!Node->hasAnyUseOfValue(0)) { 11214 int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11215 AMDGPU::OpName::glc1); 11216 if (Glc1Idx != -1) 11217 MI.RemoveOperand(Glc1Idx); 11218 MI.RemoveOperand(0); 11219 MI.setDesc(TII->get(NoRetAtomicOp)); 11220 return; 11221 } 11222 11223 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11224 // instruction, because the return type of these instructions is a vec2 of 11225 // the memory type, so it can be tied to the input operand. 11226 // This means these instructions always have a use, so we need to add a 11227 // special case to check if the atomic has only one extract_subreg use, 11228 // which itself has no uses. 11229 if ((Node->hasNUsesOfValue(1, 0) && 11230 Node->use_begin()->isMachineOpcode() && 11231 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11232 !Node->use_begin()->hasAnyUseOfValue(0))) { 11233 Register Def = MI.getOperand(0).getReg(); 11234 11235 // Change this into a noret atomic. 11236 MI.setDesc(TII->get(NoRetAtomicOp)); 11237 MI.RemoveOperand(0); 11238 11239 // If we only remove the def operand from the atomic instruction, the 11240 // extract_subreg will be left with a use of a vreg without a def. 11241 // So we need to insert an implicit_def to avoid machine verifier 11242 // errors. 11243 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11244 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11245 } 11246 return; 11247 } 11248 } 11249 11250 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11251 uint64_t Val) { 11252 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11253 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11254 } 11255 11256 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11257 const SDLoc &DL, 11258 SDValue Ptr) const { 11259 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11260 11261 // Build the half of the subregister with the constants before building the 11262 // full 128-bit register. If we are building multiple resource descriptors, 11263 // this will allow CSEing of the 2-component register. 11264 const SDValue Ops0[] = { 11265 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11266 buildSMovImm32(DAG, DL, 0), 11267 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11268 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11269 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11270 }; 11271 11272 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11273 MVT::v2i32, Ops0), 0); 11274 11275 // Combine the constants and the pointer. 11276 const SDValue Ops1[] = { 11277 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11278 Ptr, 11279 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11280 SubRegHi, 11281 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11282 }; 11283 11284 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11285 } 11286 11287 /// Return a resource descriptor with the 'Add TID' bit enabled 11288 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11289 /// of the resource descriptor) to create an offset, which is added to 11290 /// the resource pointer. 11291 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11292 SDValue Ptr, uint32_t RsrcDword1, 11293 uint64_t RsrcDword2And3) const { 11294 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11295 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11296 if (RsrcDword1) { 11297 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11298 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11299 0); 11300 } 11301 11302 SDValue DataLo = buildSMovImm32(DAG, DL, 11303 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11304 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11305 11306 const SDValue Ops[] = { 11307 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11308 PtrLo, 11309 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11310 PtrHi, 11311 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11312 DataLo, 11313 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11314 DataHi, 11315 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11316 }; 11317 11318 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11319 } 11320 11321 //===----------------------------------------------------------------------===// 11322 // SI Inline Assembly Support 11323 //===----------------------------------------------------------------------===// 11324 11325 std::pair<unsigned, const TargetRegisterClass *> 11326 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11327 StringRef Constraint, 11328 MVT VT) const { 11329 const TargetRegisterClass *RC = nullptr; 11330 if (Constraint.size() == 1) { 11331 const unsigned BitWidth = VT.getSizeInBits(); 11332 switch (Constraint[0]) { 11333 default: 11334 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11335 case 's': 11336 case 'r': 11337 switch (BitWidth) { 11338 case 16: 11339 RC = &AMDGPU::SReg_32RegClass; 11340 break; 11341 case 64: 11342 RC = &AMDGPU::SGPR_64RegClass; 11343 break; 11344 default: 11345 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11346 if (!RC) 11347 return std::make_pair(0U, nullptr); 11348 break; 11349 } 11350 break; 11351 case 'v': 11352 switch (BitWidth) { 11353 case 16: 11354 RC = &AMDGPU::VGPR_32RegClass; 11355 break; 11356 default: 11357 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11358 if (!RC) 11359 return std::make_pair(0U, nullptr); 11360 break; 11361 } 11362 break; 11363 case 'a': 11364 if (!Subtarget->hasMAIInsts()) 11365 break; 11366 switch (BitWidth) { 11367 case 16: 11368 RC = &AMDGPU::AGPR_32RegClass; 11369 break; 11370 default: 11371 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11372 if (!RC) 11373 return std::make_pair(0U, nullptr); 11374 break; 11375 } 11376 break; 11377 } 11378 // We actually support i128, i16 and f16 as inline parameters 11379 // even if they are not reported as legal 11380 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11381 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11382 return std::make_pair(0U, RC); 11383 } 11384 11385 if (Constraint.size() > 1) { 11386 if (Constraint[1] == 'v') { 11387 RC = &AMDGPU::VGPR_32RegClass; 11388 } else if (Constraint[1] == 's') { 11389 RC = &AMDGPU::SGPR_32RegClass; 11390 } else if (Constraint[1] == 'a') { 11391 RC = &AMDGPU::AGPR_32RegClass; 11392 } 11393 11394 if (RC) { 11395 uint32_t Idx; 11396 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11397 if (!Failed && Idx < RC->getNumRegs()) 11398 return std::make_pair(RC->getRegister(Idx), RC); 11399 } 11400 } 11401 11402 // FIXME: Returns VS_32 for physical SGPR constraints 11403 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11404 } 11405 11406 static bool isImmConstraint(StringRef Constraint) { 11407 if (Constraint.size() == 1) { 11408 switch (Constraint[0]) { 11409 default: break; 11410 case 'I': 11411 case 'J': 11412 case 'A': 11413 case 'B': 11414 case 'C': 11415 return true; 11416 } 11417 } else if (Constraint == "DA" || 11418 Constraint == "DB") { 11419 return true; 11420 } 11421 return false; 11422 } 11423 11424 SITargetLowering::ConstraintType 11425 SITargetLowering::getConstraintType(StringRef Constraint) const { 11426 if (Constraint.size() == 1) { 11427 switch (Constraint[0]) { 11428 default: break; 11429 case 's': 11430 case 'v': 11431 case 'a': 11432 return C_RegisterClass; 11433 } 11434 } 11435 if (isImmConstraint(Constraint)) { 11436 return C_Other; 11437 } 11438 return TargetLowering::getConstraintType(Constraint); 11439 } 11440 11441 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11442 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11443 Val = Val & maskTrailingOnes<uint64_t>(Size); 11444 } 11445 return Val; 11446 } 11447 11448 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11449 std::string &Constraint, 11450 std::vector<SDValue> &Ops, 11451 SelectionDAG &DAG) const { 11452 if (isImmConstraint(Constraint)) { 11453 uint64_t Val; 11454 if (getAsmOperandConstVal(Op, Val) && 11455 checkAsmConstraintVal(Op, Constraint, Val)) { 11456 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11457 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11458 } 11459 } else { 11460 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11461 } 11462 } 11463 11464 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11465 unsigned Size = Op.getScalarValueSizeInBits(); 11466 if (Size > 64) 11467 return false; 11468 11469 if (Size == 16 && !Subtarget->has16BitInsts()) 11470 return false; 11471 11472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11473 Val = C->getSExtValue(); 11474 return true; 11475 } 11476 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11477 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11478 return true; 11479 } 11480 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11481 if (Size != 16 || Op.getNumOperands() != 2) 11482 return false; 11483 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11484 return false; 11485 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11486 Val = C->getSExtValue(); 11487 return true; 11488 } 11489 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11490 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11491 return true; 11492 } 11493 } 11494 11495 return false; 11496 } 11497 11498 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11499 const std::string &Constraint, 11500 uint64_t Val) const { 11501 if (Constraint.size() == 1) { 11502 switch (Constraint[0]) { 11503 case 'I': 11504 return AMDGPU::isInlinableIntLiteral(Val); 11505 case 'J': 11506 return isInt<16>(Val); 11507 case 'A': 11508 return checkAsmConstraintValA(Op, Val); 11509 case 'B': 11510 return isInt<32>(Val); 11511 case 'C': 11512 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11513 AMDGPU::isInlinableIntLiteral(Val); 11514 default: 11515 break; 11516 } 11517 } else if (Constraint.size() == 2) { 11518 if (Constraint == "DA") { 11519 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11520 int64_t LoBits = static_cast<int32_t>(Val); 11521 return checkAsmConstraintValA(Op, HiBits, 32) && 11522 checkAsmConstraintValA(Op, LoBits, 32); 11523 } 11524 if (Constraint == "DB") { 11525 return true; 11526 } 11527 } 11528 llvm_unreachable("Invalid asm constraint"); 11529 } 11530 11531 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11532 uint64_t Val, 11533 unsigned MaxSize) const { 11534 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11535 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11536 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11537 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11538 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11539 return true; 11540 } 11541 return false; 11542 } 11543 11544 // Figure out which registers should be reserved for stack access. Only after 11545 // the function is legalized do we know all of the non-spill stack objects or if 11546 // calls are present. 11547 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11548 MachineRegisterInfo &MRI = MF.getRegInfo(); 11549 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11550 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11551 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11552 11553 if (Info->isEntryFunction()) { 11554 // Callable functions have fixed registers used for stack access. 11555 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11556 } 11557 11558 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11559 Info->getStackPtrOffsetReg())); 11560 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11561 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11562 11563 // We need to worry about replacing the default register with itself in case 11564 // of MIR testcases missing the MFI. 11565 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11566 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11567 11568 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11569 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11570 11571 Info->limitOccupancy(MF); 11572 11573 if (ST.isWave32() && !MF.empty()) { 11574 const SIInstrInfo *TII = ST.getInstrInfo(); 11575 for (auto &MBB : MF) { 11576 for (auto &MI : MBB) { 11577 TII->fixImplicitOperands(MI); 11578 } 11579 } 11580 } 11581 11582 TargetLoweringBase::finalizeLowering(MF); 11583 11584 // Allocate a VGPR for future SGPR Spill if 11585 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11586 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11587 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11588 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11589 Info->reserveVGPRforSGPRSpills(MF); 11590 } 11591 11592 void SITargetLowering::computeKnownBitsForFrameIndex( 11593 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11594 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11595 11596 // Set the high bits to zero based on the maximum allowed scratch size per 11597 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11598 // calculation won't overflow, so assume the sign bit is never set. 11599 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11600 } 11601 11602 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11603 KnownBits &Known, unsigned Dim) { 11604 unsigned MaxValue = 11605 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11606 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11607 } 11608 11609 void SITargetLowering::computeKnownBitsForTargetInstr( 11610 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11611 const MachineRegisterInfo &MRI, unsigned Depth) const { 11612 const MachineInstr *MI = MRI.getVRegDef(R); 11613 switch (MI->getOpcode()) { 11614 case AMDGPU::G_INTRINSIC: { 11615 switch (MI->getIntrinsicID()) { 11616 case Intrinsic::amdgcn_workitem_id_x: 11617 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11618 break; 11619 case Intrinsic::amdgcn_workitem_id_y: 11620 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11621 break; 11622 case Intrinsic::amdgcn_workitem_id_z: 11623 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11624 break; 11625 case Intrinsic::amdgcn_mbcnt_lo: 11626 case Intrinsic::amdgcn_mbcnt_hi: { 11627 // These return at most the wavefront size - 1. 11628 unsigned Size = MRI.getType(R).getSizeInBits(); 11629 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11630 break; 11631 } 11632 case Intrinsic::amdgcn_groupstaticsize: { 11633 // We can report everything over the maximum size as 0. We can't report 11634 // based on the actual size because we don't know if it's accurate or not 11635 // at any given point. 11636 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11637 break; 11638 } 11639 } 11640 break; 11641 } 11642 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11643 Known.Zero.setHighBits(24); 11644 break; 11645 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11646 Known.Zero.setHighBits(16); 11647 break; 11648 } 11649 } 11650 11651 Align SITargetLowering::computeKnownAlignForTargetInstr( 11652 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11653 unsigned Depth) const { 11654 const MachineInstr *MI = MRI.getVRegDef(R); 11655 switch (MI->getOpcode()) { 11656 case AMDGPU::G_INTRINSIC: 11657 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11658 // FIXME: Can this move to generic code? What about the case where the call 11659 // site specifies a lower alignment? 11660 Intrinsic::ID IID = MI->getIntrinsicID(); 11661 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11662 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11663 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11664 return *RetAlign; 11665 return Align(1); 11666 } 11667 default: 11668 return Align(1); 11669 } 11670 } 11671 11672 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11673 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11674 const Align CacheLineAlign = Align(64); 11675 11676 // Pre-GFX10 target did not benefit from loop alignment 11677 if (!ML || DisableLoopAlignment || 11678 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11679 getSubtarget()->hasInstFwdPrefetchBug()) 11680 return PrefAlign; 11681 11682 // On GFX10 I$ is 4 x 64 bytes cache lines. 11683 // By default prefetcher keeps one cache line behind and reads two ahead. 11684 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11685 // behind and one ahead. 11686 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11687 // If loop fits 64 bytes it always spans no more than two cache lines and 11688 // does not need an alignment. 11689 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11690 // Else if loop is less or equal 192 bytes we need two lines behind. 11691 11692 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11693 const MachineBasicBlock *Header = ML->getHeader(); 11694 if (Header->getAlignment() != PrefAlign) 11695 return Header->getAlignment(); // Already processed. 11696 11697 unsigned LoopSize = 0; 11698 for (const MachineBasicBlock *MBB : ML->blocks()) { 11699 // If inner loop block is aligned assume in average half of the alignment 11700 // size to be added as nops. 11701 if (MBB != Header) 11702 LoopSize += MBB->getAlignment().value() / 2; 11703 11704 for (const MachineInstr &MI : *MBB) { 11705 LoopSize += TII->getInstSizeInBytes(MI); 11706 if (LoopSize > 192) 11707 return PrefAlign; 11708 } 11709 } 11710 11711 if (LoopSize <= 64) 11712 return PrefAlign; 11713 11714 if (LoopSize <= 128) 11715 return CacheLineAlign; 11716 11717 // If any of parent loops is surrounded by prefetch instructions do not 11718 // insert new for inner loop, which would reset parent's settings. 11719 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11720 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11721 auto I = Exit->getFirstNonDebugInstr(); 11722 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11723 return CacheLineAlign; 11724 } 11725 } 11726 11727 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11728 MachineBasicBlock *Exit = ML->getExitBlock(); 11729 11730 if (Pre && Exit) { 11731 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11732 TII->get(AMDGPU::S_INST_PREFETCH)) 11733 .addImm(1); // prefetch 2 lines behind PC 11734 11735 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11736 TII->get(AMDGPU::S_INST_PREFETCH)) 11737 .addImm(2); // prefetch 1 line behind PC 11738 } 11739 11740 return CacheLineAlign; 11741 } 11742 11743 LLVM_ATTRIBUTE_UNUSED 11744 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11745 assert(N->getOpcode() == ISD::CopyFromReg); 11746 do { 11747 // Follow the chain until we find an INLINEASM node. 11748 N = N->getOperand(0).getNode(); 11749 if (N->getOpcode() == ISD::INLINEASM || 11750 N->getOpcode() == ISD::INLINEASM_BR) 11751 return true; 11752 } while (N->getOpcode() == ISD::CopyFromReg); 11753 return false; 11754 } 11755 11756 bool SITargetLowering::isSDNodeSourceOfDivergence( 11757 const SDNode *N, FunctionLoweringInfo *FLI, 11758 LegacyDivergenceAnalysis *KDA) const { 11759 switch (N->getOpcode()) { 11760 case ISD::CopyFromReg: { 11761 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11762 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11763 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11764 Register Reg = R->getReg(); 11765 11766 // FIXME: Why does this need to consider isLiveIn? 11767 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11768 return !TRI->isSGPRReg(MRI, Reg); 11769 11770 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11771 return KDA->isDivergent(V); 11772 11773 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11774 return !TRI->isSGPRReg(MRI, Reg); 11775 } 11776 case ISD::LOAD: { 11777 const LoadSDNode *L = cast<LoadSDNode>(N); 11778 unsigned AS = L->getAddressSpace(); 11779 // A flat load may access private memory. 11780 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11781 } 11782 case ISD::CALLSEQ_END: 11783 return true; 11784 case ISD::INTRINSIC_WO_CHAIN: 11785 return AMDGPU::isIntrinsicSourceOfDivergence( 11786 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11787 case ISD::INTRINSIC_W_CHAIN: 11788 return AMDGPU::isIntrinsicSourceOfDivergence( 11789 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11790 } 11791 return false; 11792 } 11793 11794 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11795 EVT VT) const { 11796 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11797 case MVT::f32: 11798 return hasFP32Denormals(DAG.getMachineFunction()); 11799 case MVT::f64: 11800 case MVT::f16: 11801 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11802 default: 11803 return false; 11804 } 11805 } 11806 11807 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11808 const SelectionDAG &DAG, 11809 bool SNaN, 11810 unsigned Depth) const { 11811 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11812 const MachineFunction &MF = DAG.getMachineFunction(); 11813 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11814 11815 if (Info->getMode().DX10Clamp) 11816 return true; // Clamped to 0. 11817 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11818 } 11819 11820 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11821 SNaN, Depth); 11822 } 11823 11824 // Global FP atomic instructions have a hardcoded FP mode and do not support 11825 // FP32 denormals, and only support v2f16 denormals. 11826 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11827 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11828 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11829 if (&Flt == &APFloat::IEEEsingle()) 11830 return DenormMode == DenormalMode::getPreserveSign(); 11831 return DenormMode == DenormalMode::getIEEE(); 11832 } 11833 11834 TargetLowering::AtomicExpansionKind 11835 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11836 switch (RMW->getOperation()) { 11837 case AtomicRMWInst::FAdd: { 11838 Type *Ty = RMW->getType(); 11839 11840 // We don't have a way to support 16-bit atomics now, so just leave them 11841 // as-is. 11842 if (Ty->isHalfTy()) 11843 return AtomicExpansionKind::None; 11844 11845 if (!Ty->isFloatTy()) 11846 return AtomicExpansionKind::CmpXChg; 11847 11848 // TODO: Do have these for flat. Older targets also had them for buffers. 11849 unsigned AS = RMW->getPointerAddressSpace(); 11850 11851 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11852 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11853 return AtomicExpansionKind::CmpXChg; 11854 11855 return RMW->use_empty() ? AtomicExpansionKind::None : 11856 AtomicExpansionKind::CmpXChg; 11857 } 11858 11859 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11860 // to round-to-nearest-even. 11861 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11862 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11863 } 11864 default: 11865 break; 11866 } 11867 11868 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11869 } 11870 11871 const TargetRegisterClass * 11872 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11873 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11874 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11875 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11876 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11877 : &AMDGPU::SReg_32RegClass; 11878 if (!TRI->isSGPRClass(RC) && !isDivergent) 11879 return TRI->getEquivalentSGPRClass(RC); 11880 else if (TRI->isSGPRClass(RC) && isDivergent) 11881 return TRI->getEquivalentVGPRClass(RC); 11882 11883 return RC; 11884 } 11885 11886 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11887 // uniform values (as produced by the mask results of control flow intrinsics) 11888 // used outside of divergent blocks. The phi users need to also be treated as 11889 // always uniform. 11890 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11891 unsigned WaveSize) { 11892 // FIXME: We asssume we never cast the mask results of a control flow 11893 // intrinsic. 11894 // Early exit if the type won't be consistent as a compile time hack. 11895 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11896 if (!IT || IT->getBitWidth() != WaveSize) 11897 return false; 11898 11899 if (!isa<Instruction>(V)) 11900 return false; 11901 if (!Visited.insert(V).second) 11902 return false; 11903 bool Result = false; 11904 for (auto U : V->users()) { 11905 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11906 if (V == U->getOperand(1)) { 11907 switch (Intrinsic->getIntrinsicID()) { 11908 default: 11909 Result = false; 11910 break; 11911 case Intrinsic::amdgcn_if_break: 11912 case Intrinsic::amdgcn_if: 11913 case Intrinsic::amdgcn_else: 11914 Result = true; 11915 break; 11916 } 11917 } 11918 if (V == U->getOperand(0)) { 11919 switch (Intrinsic->getIntrinsicID()) { 11920 default: 11921 Result = false; 11922 break; 11923 case Intrinsic::amdgcn_end_cf: 11924 case Intrinsic::amdgcn_loop: 11925 Result = true; 11926 break; 11927 } 11928 } 11929 } else { 11930 Result = hasCFUser(U, Visited, WaveSize); 11931 } 11932 if (Result) 11933 break; 11934 } 11935 return Result; 11936 } 11937 11938 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11939 const Value *V) const { 11940 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11941 if (CI->isInlineAsm()) { 11942 // FIXME: This cannot give a correct answer. This should only trigger in 11943 // the case where inline asm returns mixed SGPR and VGPR results, used 11944 // outside the defining block. We don't have a specific result to 11945 // consider, so this assumes if any value is SGPR, the overall register 11946 // also needs to be SGPR. 11947 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11948 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11949 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11950 for (auto &TC : TargetConstraints) { 11951 if (TC.Type == InlineAsm::isOutput) { 11952 ComputeConstraintToUse(TC, SDValue()); 11953 unsigned AssignedReg; 11954 const TargetRegisterClass *RC; 11955 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11956 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11957 if (RC) { 11958 MachineRegisterInfo &MRI = MF.getRegInfo(); 11959 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11960 return true; 11961 else if (SIRI->isSGPRClass(RC)) 11962 return true; 11963 } 11964 } 11965 } 11966 } 11967 } 11968 SmallPtrSet<const Value *, 16> Visited; 11969 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11970 } 11971 11972 std::pair<int, MVT> 11973 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11974 Type *Ty) const { 11975 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11976 auto Size = DL.getTypeSizeInBits(Ty); 11977 // Maximum load or store can handle 8 dwords for scalar and 4 for 11978 // vector ALU. Let's assume anything above 8 dwords is expensive 11979 // even if legal. 11980 if (Size <= 256) 11981 return Cost; 11982 11983 Cost.first = (Size + 255) / 256; 11984 return Cost; 11985 } 11986