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 // FIXME: We have to be conservative here and assume that flat operations 1474 // will access scratch. If we had access to the IR function, then we 1475 // could determine if any private memory was used in the function. 1476 if (!Subtarget->hasUnalignedScratchAccess() && 1477 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1478 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1479 bool AlignedBy4 = Alignment >= Align(4); 1480 if (IsFast) 1481 *IsFast = AlignedBy4; 1482 1483 return AlignedBy4; 1484 } 1485 1486 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1487 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1488 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1489 // If we have an uniform constant load, it still requires using a slow 1490 // buffer instruction if unaligned. 1491 if (IsFast) { 1492 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1493 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1494 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1495 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1496 Alignment >= Align(4) : Alignment != Align(2); 1497 } 1498 1499 return true; 1500 } 1501 1502 // Smaller than dword value must be aligned. 1503 if (Size < 32) 1504 return false; 1505 1506 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1507 // byte-address are ignored, thus forcing Dword alignment. 1508 // This applies to private, global, and constant memory. 1509 if (IsFast) 1510 *IsFast = true; 1511 1512 return Size >= 32 && Alignment >= Align(4); 1513 } 1514 1515 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1516 EVT VT, unsigned AddrSpace, unsigned Alignment, 1517 MachineMemOperand::Flags Flags, bool *IsFast) const { 1518 if (IsFast) 1519 *IsFast = false; 1520 1521 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1522 // which isn't a simple VT. 1523 // Until MVT is extended to handle this, simply check for the size and 1524 // rely on the condition below: allow accesses if the size is a multiple of 4. 1525 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1526 VT.getStoreSize() > 16)) { 1527 return false; 1528 } 1529 1530 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1531 Align(Alignment), Flags, IsFast); 1532 } 1533 1534 EVT SITargetLowering::getOptimalMemOpType( 1535 const MemOp &Op, const AttributeList &FuncAttributes) const { 1536 // FIXME: Should account for address space here. 1537 1538 // The default fallback uses the private pointer size as a guess for a type to 1539 // use. Make sure we switch these to 64-bit accesses. 1540 1541 if (Op.size() >= 16 && 1542 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1543 return MVT::v4i32; 1544 1545 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1546 return MVT::v2i32; 1547 1548 // Use the default. 1549 return MVT::Other; 1550 } 1551 1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1553 const MemSDNode *MemNode = cast<MemSDNode>(N); 1554 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1555 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1556 return I && I->getMetadata("amdgpu.noclobber"); 1557 } 1558 1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1560 unsigned DestAS) const { 1561 // Flat -> private/local is a simple truncate. 1562 // Flat -> global is no-op 1563 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1564 return true; 1565 1566 const GCNTargetMachine &TM = 1567 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1568 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1569 } 1570 1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1572 const MemSDNode *MemNode = cast<MemSDNode>(N); 1573 1574 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1575 } 1576 1577 TargetLoweringBase::LegalizeTypeAction 1578 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1579 int NumElts = VT.getVectorNumElements(); 1580 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1581 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1582 return TargetLoweringBase::getPreferredVectorAction(VT); 1583 } 1584 1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1586 Type *Ty) const { 1587 // FIXME: Could be smarter if called for vector constants. 1588 return true; 1589 } 1590 1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1592 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1593 switch (Op) { 1594 case ISD::LOAD: 1595 case ISD::STORE: 1596 1597 // These operations are done with 32-bit instructions anyway. 1598 case ISD::AND: 1599 case ISD::OR: 1600 case ISD::XOR: 1601 case ISD::SELECT: 1602 // TODO: Extensions? 1603 return true; 1604 default: 1605 return false; 1606 } 1607 } 1608 1609 // SimplifySetCC uses this function to determine whether or not it should 1610 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1611 if (VT == MVT::i1 && Op == ISD::SETCC) 1612 return false; 1613 1614 return TargetLowering::isTypeDesirableForOp(Op, VT); 1615 } 1616 1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1618 const SDLoc &SL, 1619 SDValue Chain, 1620 uint64_t Offset) const { 1621 const DataLayout &DL = DAG.getDataLayout(); 1622 MachineFunction &MF = DAG.getMachineFunction(); 1623 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1624 1625 const ArgDescriptor *InputPtrReg; 1626 const TargetRegisterClass *RC; 1627 LLT ArgTy; 1628 1629 std::tie(InputPtrReg, RC, ArgTy) = 1630 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1631 1632 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1633 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1634 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1635 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1636 1637 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1638 } 1639 1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1641 const SDLoc &SL) const { 1642 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1643 FIRST_IMPLICIT); 1644 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1645 } 1646 1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1648 const SDLoc &SL, SDValue Val, 1649 bool Signed, 1650 const ISD::InputArg *Arg) const { 1651 // First, if it is a widened vector, narrow it. 1652 if (VT.isVector() && 1653 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1654 EVT NarrowedVT = 1655 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1656 VT.getVectorNumElements()); 1657 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1658 DAG.getConstant(0, SL, MVT::i32)); 1659 } 1660 1661 // Then convert the vector elements or scalar value. 1662 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1663 VT.bitsLT(MemVT)) { 1664 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1665 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1666 } 1667 1668 if (MemVT.isFloatingPoint()) 1669 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1670 else if (Signed) 1671 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1672 else 1673 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1674 1675 return Val; 1676 } 1677 1678 SDValue SITargetLowering::lowerKernargMemParameter( 1679 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1680 uint64_t Offset, Align Alignment, bool Signed, 1681 const ISD::InputArg *Arg) const { 1682 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1683 1684 // Try to avoid using an extload by loading earlier than the argument address, 1685 // and extracting the relevant bits. The load should hopefully be merged with 1686 // the previous argument. 1687 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1688 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1689 int64_t AlignDownOffset = alignDown(Offset, 4); 1690 int64_t OffsetDiff = Offset - AlignDownOffset; 1691 1692 EVT IntVT = MemVT.changeTypeToInteger(); 1693 1694 // TODO: If we passed in the base kernel offset we could have a better 1695 // alignment than 4, but we don't really need it. 1696 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1697 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1698 MachineMemOperand::MODereferenceable | 1699 MachineMemOperand::MOInvariant); 1700 1701 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1702 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1703 1704 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1705 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1706 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1707 1708 1709 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1710 } 1711 1712 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1713 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1714 MachineMemOperand::MODereferenceable | 1715 MachineMemOperand::MOInvariant); 1716 1717 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1718 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1719 } 1720 1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1722 const SDLoc &SL, SDValue Chain, 1723 const ISD::InputArg &Arg) const { 1724 MachineFunction &MF = DAG.getMachineFunction(); 1725 MachineFrameInfo &MFI = MF.getFrameInfo(); 1726 1727 if (Arg.Flags.isByVal()) { 1728 unsigned Size = Arg.Flags.getByValSize(); 1729 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1730 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1731 } 1732 1733 unsigned ArgOffset = VA.getLocMemOffset(); 1734 unsigned ArgSize = VA.getValVT().getStoreSize(); 1735 1736 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1737 1738 // Create load nodes to retrieve arguments from the stack. 1739 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1740 SDValue ArgValue; 1741 1742 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1743 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1744 MVT MemVT = VA.getValVT(); 1745 1746 switch (VA.getLocInfo()) { 1747 default: 1748 break; 1749 case CCValAssign::BCvt: 1750 MemVT = VA.getLocVT(); 1751 break; 1752 case CCValAssign::SExt: 1753 ExtType = ISD::SEXTLOAD; 1754 break; 1755 case CCValAssign::ZExt: 1756 ExtType = ISD::ZEXTLOAD; 1757 break; 1758 case CCValAssign::AExt: 1759 ExtType = ISD::EXTLOAD; 1760 break; 1761 } 1762 1763 ArgValue = DAG.getExtLoad( 1764 ExtType, SL, VA.getLocVT(), Chain, FIN, 1765 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1766 MemVT); 1767 return ArgValue; 1768 } 1769 1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1771 const SIMachineFunctionInfo &MFI, 1772 EVT VT, 1773 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1774 const ArgDescriptor *Reg; 1775 const TargetRegisterClass *RC; 1776 LLT Ty; 1777 1778 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1779 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1780 } 1781 1782 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1783 CallingConv::ID CallConv, 1784 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1785 FunctionType *FType, 1786 SIMachineFunctionInfo *Info) { 1787 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1788 const ISD::InputArg *Arg = &Ins[I]; 1789 1790 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1791 "vector type argument should have been split"); 1792 1793 // First check if it's a PS input addr. 1794 if (CallConv == CallingConv::AMDGPU_PS && 1795 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1796 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1797 1798 // Inconveniently only the first part of the split is marked as isSplit, 1799 // so skip to the end. We only want to increment PSInputNum once for the 1800 // entire split argument. 1801 if (Arg->Flags.isSplit()) { 1802 while (!Arg->Flags.isSplitEnd()) { 1803 assert((!Arg->VT.isVector() || 1804 Arg->VT.getScalarSizeInBits() == 16) && 1805 "unexpected vector split in ps argument type"); 1806 if (!SkipArg) 1807 Splits.push_back(*Arg); 1808 Arg = &Ins[++I]; 1809 } 1810 } 1811 1812 if (SkipArg) { 1813 // We can safely skip PS inputs. 1814 Skipped.set(Arg->getOrigArgIndex()); 1815 ++PSInputNum; 1816 continue; 1817 } 1818 1819 Info->markPSInputAllocated(PSInputNum); 1820 if (Arg->Used) 1821 Info->markPSInputEnabled(PSInputNum); 1822 1823 ++PSInputNum; 1824 } 1825 1826 Splits.push_back(*Arg); 1827 } 1828 } 1829 1830 // Allocate special inputs passed in VGPRs. 1831 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1832 MachineFunction &MF, 1833 const SIRegisterInfo &TRI, 1834 SIMachineFunctionInfo &Info) const { 1835 const LLT S32 = LLT::scalar(32); 1836 MachineRegisterInfo &MRI = MF.getRegInfo(); 1837 1838 if (Info.hasWorkItemIDX()) { 1839 Register Reg = AMDGPU::VGPR0; 1840 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1841 1842 CCInfo.AllocateReg(Reg); 1843 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1844 } 1845 1846 if (Info.hasWorkItemIDY()) { 1847 Register Reg = AMDGPU::VGPR1; 1848 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1849 1850 CCInfo.AllocateReg(Reg); 1851 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1852 } 1853 1854 if (Info.hasWorkItemIDZ()) { 1855 Register Reg = AMDGPU::VGPR2; 1856 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1857 1858 CCInfo.AllocateReg(Reg); 1859 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1860 } 1861 } 1862 1863 // Try to allocate a VGPR at the end of the argument list, or if no argument 1864 // VGPRs are left allocating a stack slot. 1865 // If \p Mask is is given it indicates bitfield position in the register. 1866 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1867 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1868 ArgDescriptor Arg = ArgDescriptor()) { 1869 if (Arg.isSet()) 1870 return ArgDescriptor::createArg(Arg, Mask); 1871 1872 ArrayRef<MCPhysReg> ArgVGPRs 1873 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1874 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1875 if (RegIdx == ArgVGPRs.size()) { 1876 // Spill to stack required. 1877 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1878 1879 return ArgDescriptor::createStack(Offset, Mask); 1880 } 1881 1882 unsigned Reg = ArgVGPRs[RegIdx]; 1883 Reg = CCInfo.AllocateReg(Reg); 1884 assert(Reg != AMDGPU::NoRegister); 1885 1886 MachineFunction &MF = CCInfo.getMachineFunction(); 1887 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1888 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1889 return ArgDescriptor::createRegister(Reg, Mask); 1890 } 1891 1892 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1893 const TargetRegisterClass *RC, 1894 unsigned NumArgRegs) { 1895 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1896 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1897 if (RegIdx == ArgSGPRs.size()) 1898 report_fatal_error("ran out of SGPRs for arguments"); 1899 1900 unsigned Reg = ArgSGPRs[RegIdx]; 1901 Reg = CCInfo.AllocateReg(Reg); 1902 assert(Reg != AMDGPU::NoRegister); 1903 1904 MachineFunction &MF = CCInfo.getMachineFunction(); 1905 MF.addLiveIn(Reg, RC); 1906 return ArgDescriptor::createRegister(Reg); 1907 } 1908 1909 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1910 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1911 } 1912 1913 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1914 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1915 } 1916 1917 /// Allocate implicit function VGPR arguments at the end of allocated user 1918 /// arguments. 1919 void SITargetLowering::allocateSpecialInputVGPRs( 1920 CCState &CCInfo, MachineFunction &MF, 1921 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1922 const unsigned Mask = 0x3ff; 1923 ArgDescriptor Arg; 1924 1925 if (Info.hasWorkItemIDX()) { 1926 Arg = allocateVGPR32Input(CCInfo, Mask); 1927 Info.setWorkItemIDX(Arg); 1928 } 1929 1930 if (Info.hasWorkItemIDY()) { 1931 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1932 Info.setWorkItemIDY(Arg); 1933 } 1934 1935 if (Info.hasWorkItemIDZ()) 1936 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1937 } 1938 1939 /// Allocate implicit function VGPR arguments in fixed registers. 1940 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1941 CCState &CCInfo, MachineFunction &MF, 1942 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1943 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1944 if (!Reg) 1945 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1946 1947 const unsigned Mask = 0x3ff; 1948 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1949 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1950 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1951 } 1952 1953 void SITargetLowering::allocateSpecialInputSGPRs( 1954 CCState &CCInfo, 1955 MachineFunction &MF, 1956 const SIRegisterInfo &TRI, 1957 SIMachineFunctionInfo &Info) const { 1958 auto &ArgInfo = Info.getArgInfo(); 1959 1960 // TODO: Unify handling with private memory pointers. 1961 1962 if (Info.hasDispatchPtr()) 1963 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1964 1965 if (Info.hasQueuePtr()) 1966 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1967 1968 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1969 // constant offset from the kernarg segment. 1970 if (Info.hasImplicitArgPtr()) 1971 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1972 1973 if (Info.hasDispatchID()) 1974 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1975 1976 // flat_scratch_init is not applicable for non-kernel functions. 1977 1978 if (Info.hasWorkGroupIDX()) 1979 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1980 1981 if (Info.hasWorkGroupIDY()) 1982 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1983 1984 if (Info.hasWorkGroupIDZ()) 1985 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1986 } 1987 1988 // Allocate special inputs passed in user SGPRs. 1989 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1990 MachineFunction &MF, 1991 const SIRegisterInfo &TRI, 1992 SIMachineFunctionInfo &Info) const { 1993 if (Info.hasImplicitBufferPtr()) { 1994 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1995 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1996 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1997 } 1998 1999 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2000 if (Info.hasPrivateSegmentBuffer()) { 2001 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2002 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2003 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2004 } 2005 2006 if (Info.hasDispatchPtr()) { 2007 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2008 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2009 CCInfo.AllocateReg(DispatchPtrReg); 2010 } 2011 2012 if (Info.hasQueuePtr()) { 2013 Register QueuePtrReg = Info.addQueuePtr(TRI); 2014 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2015 CCInfo.AllocateReg(QueuePtrReg); 2016 } 2017 2018 if (Info.hasKernargSegmentPtr()) { 2019 MachineRegisterInfo &MRI = MF.getRegInfo(); 2020 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2021 CCInfo.AllocateReg(InputPtrReg); 2022 2023 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2024 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2025 } 2026 2027 if (Info.hasDispatchID()) { 2028 Register DispatchIDReg = Info.addDispatchID(TRI); 2029 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2030 CCInfo.AllocateReg(DispatchIDReg); 2031 } 2032 2033 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2034 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2035 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2036 CCInfo.AllocateReg(FlatScratchInitReg); 2037 } 2038 2039 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2040 // these from the dispatch pointer. 2041 } 2042 2043 // Allocate special input registers that are initialized per-wave. 2044 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2045 MachineFunction &MF, 2046 SIMachineFunctionInfo &Info, 2047 CallingConv::ID CallConv, 2048 bool IsShader) const { 2049 if (Info.hasWorkGroupIDX()) { 2050 Register Reg = Info.addWorkGroupIDX(); 2051 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2052 CCInfo.AllocateReg(Reg); 2053 } 2054 2055 if (Info.hasWorkGroupIDY()) { 2056 Register Reg = Info.addWorkGroupIDY(); 2057 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2058 CCInfo.AllocateReg(Reg); 2059 } 2060 2061 if (Info.hasWorkGroupIDZ()) { 2062 Register Reg = Info.addWorkGroupIDZ(); 2063 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2064 CCInfo.AllocateReg(Reg); 2065 } 2066 2067 if (Info.hasWorkGroupInfo()) { 2068 Register Reg = Info.addWorkGroupInfo(); 2069 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2070 CCInfo.AllocateReg(Reg); 2071 } 2072 2073 if (Info.hasPrivateSegmentWaveByteOffset()) { 2074 // Scratch wave offset passed in system SGPR. 2075 unsigned PrivateSegmentWaveByteOffsetReg; 2076 2077 if (IsShader) { 2078 PrivateSegmentWaveByteOffsetReg = 2079 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2080 2081 // This is true if the scratch wave byte offset doesn't have a fixed 2082 // location. 2083 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2084 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2085 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2086 } 2087 } else 2088 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2089 2090 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2091 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2092 } 2093 } 2094 2095 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2096 MachineFunction &MF, 2097 const SIRegisterInfo &TRI, 2098 SIMachineFunctionInfo &Info) { 2099 // Now that we've figured out where the scratch register inputs are, see if 2100 // should reserve the arguments and use them directly. 2101 MachineFrameInfo &MFI = MF.getFrameInfo(); 2102 bool HasStackObjects = MFI.hasStackObjects(); 2103 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2104 2105 // Record that we know we have non-spill stack objects so we don't need to 2106 // check all stack objects later. 2107 if (HasStackObjects) 2108 Info.setHasNonSpillStackObjects(true); 2109 2110 // Everything live out of a block is spilled with fast regalloc, so it's 2111 // almost certain that spilling will be required. 2112 if (TM.getOptLevel() == CodeGenOpt::None) 2113 HasStackObjects = true; 2114 2115 // For now assume stack access is needed in any callee functions, so we need 2116 // the scratch registers to pass in. 2117 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2118 2119 if (!ST.enableFlatScratch()) { 2120 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2121 // If we have stack objects, we unquestionably need the private buffer 2122 // resource. For the Code Object V2 ABI, this will be the first 4 user 2123 // SGPR inputs. We can reserve those and use them directly. 2124 2125 Register PrivateSegmentBufferReg = 2126 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2127 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2128 } else { 2129 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2130 // We tentatively reserve the last registers (skipping the last registers 2131 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2132 // we'll replace these with the ones immediately after those which were 2133 // really allocated. In the prologue copies will be inserted from the 2134 // argument to these reserved registers. 2135 2136 // Without HSA, relocations are used for the scratch pointer and the 2137 // buffer resource setup is always inserted in the prologue. Scratch wave 2138 // offset is still in an input SGPR. 2139 Info.setScratchRSrcReg(ReservedBufferReg); 2140 } 2141 } 2142 2143 MachineRegisterInfo &MRI = MF.getRegInfo(); 2144 2145 // For entry functions we have to set up the stack pointer if we use it, 2146 // whereas non-entry functions get this "for free". This means there is no 2147 // intrinsic advantage to using S32 over S34 in cases where we do not have 2148 // calls but do need a frame pointer (i.e. if we are requested to have one 2149 // because frame pointer elimination is disabled). To keep things simple we 2150 // only ever use S32 as the call ABI stack pointer, and so using it does not 2151 // imply we need a separate frame pointer. 2152 // 2153 // Try to use s32 as the SP, but move it if it would interfere with input 2154 // arguments. This won't work with calls though. 2155 // 2156 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2157 // registers. 2158 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2159 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2160 } else { 2161 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2162 2163 if (MFI.hasCalls()) 2164 report_fatal_error("call in graphics shader with too many input SGPRs"); 2165 2166 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2167 if (!MRI.isLiveIn(Reg)) { 2168 Info.setStackPtrOffsetReg(Reg); 2169 break; 2170 } 2171 } 2172 2173 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2174 report_fatal_error("failed to find register for SP"); 2175 } 2176 2177 // hasFP should be accurate for entry functions even before the frame is 2178 // finalized, because it does not rely on the known stack size, only 2179 // properties like whether variable sized objects are present. 2180 if (ST.getFrameLowering()->hasFP(MF)) { 2181 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2182 } 2183 } 2184 2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2186 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2187 return !Info->isEntryFunction(); 2188 } 2189 2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2191 2192 } 2193 2194 void SITargetLowering::insertCopiesSplitCSR( 2195 MachineBasicBlock *Entry, 2196 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2197 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2198 2199 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2200 if (!IStart) 2201 return; 2202 2203 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2204 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2205 MachineBasicBlock::iterator MBBI = Entry->begin(); 2206 for (const MCPhysReg *I = IStart; *I; ++I) { 2207 const TargetRegisterClass *RC = nullptr; 2208 if (AMDGPU::SReg_64RegClass.contains(*I)) 2209 RC = &AMDGPU::SGPR_64RegClass; 2210 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2211 RC = &AMDGPU::SGPR_32RegClass; 2212 else 2213 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2214 2215 Register NewVR = MRI->createVirtualRegister(RC); 2216 // Create copy from CSR to a virtual register. 2217 Entry->addLiveIn(*I); 2218 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2219 .addReg(*I); 2220 2221 // Insert the copy-back instructions right before the terminator. 2222 for (auto *Exit : Exits) 2223 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2224 TII->get(TargetOpcode::COPY), *I) 2225 .addReg(NewVR); 2226 } 2227 } 2228 2229 SDValue SITargetLowering::LowerFormalArguments( 2230 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2231 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2232 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2233 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2234 2235 MachineFunction &MF = DAG.getMachineFunction(); 2236 const Function &Fn = MF.getFunction(); 2237 FunctionType *FType = MF.getFunction().getFunctionType(); 2238 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2239 2240 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2241 DiagnosticInfoUnsupported NoGraphicsHSA( 2242 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2243 DAG.getContext()->diagnose(NoGraphicsHSA); 2244 return DAG.getEntryNode(); 2245 } 2246 2247 SmallVector<ISD::InputArg, 16> Splits; 2248 SmallVector<CCValAssign, 16> ArgLocs; 2249 BitVector Skipped(Ins.size()); 2250 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2251 *DAG.getContext()); 2252 2253 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2254 bool IsKernel = AMDGPU::isKernel(CallConv); 2255 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2256 2257 if (IsGraphics) { 2258 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2259 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2260 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2261 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2262 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2263 !Info->hasWorkItemIDZ()); 2264 } 2265 2266 if (CallConv == CallingConv::AMDGPU_PS) { 2267 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2268 2269 // At least one interpolation mode must be enabled or else the GPU will 2270 // hang. 2271 // 2272 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2273 // set PSInputAddr, the user wants to enable some bits after the compilation 2274 // based on run-time states. Since we can't know what the final PSInputEna 2275 // will look like, so we shouldn't do anything here and the user should take 2276 // responsibility for the correct programming. 2277 // 2278 // Otherwise, the following restrictions apply: 2279 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2280 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2281 // enabled too. 2282 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2283 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2284 CCInfo.AllocateReg(AMDGPU::VGPR0); 2285 CCInfo.AllocateReg(AMDGPU::VGPR1); 2286 Info->markPSInputAllocated(0); 2287 Info->markPSInputEnabled(0); 2288 } 2289 if (Subtarget->isAmdPalOS()) { 2290 // For isAmdPalOS, the user does not enable some bits after compilation 2291 // based on run-time states; the register values being generated here are 2292 // the final ones set in hardware. Therefore we need to apply the 2293 // workaround to PSInputAddr and PSInputEnable together. (The case where 2294 // a bit is set in PSInputAddr but not PSInputEnable is where the 2295 // frontend set up an input arg for a particular interpolation mode, but 2296 // nothing uses that input arg. Really we should have an earlier pass 2297 // that removes such an arg.) 2298 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2299 if ((PsInputBits & 0x7F) == 0 || 2300 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2301 Info->markPSInputEnabled( 2302 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2303 } 2304 } else if (IsKernel) { 2305 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2306 } else { 2307 Splits.append(Ins.begin(), Ins.end()); 2308 } 2309 2310 if (IsEntryFunc) { 2311 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2312 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2313 } else { 2314 // For the fixed ABI, pass workitem IDs in the last argument register. 2315 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2316 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2317 } 2318 2319 if (IsKernel) { 2320 analyzeFormalArgumentsCompute(CCInfo, Ins); 2321 } else { 2322 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2323 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2324 } 2325 2326 SmallVector<SDValue, 16> Chains; 2327 2328 // FIXME: This is the minimum kernel argument alignment. We should improve 2329 // this to the maximum alignment of the arguments. 2330 // 2331 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2332 // kern arg offset. 2333 const Align KernelArgBaseAlign = Align(16); 2334 2335 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2336 const ISD::InputArg &Arg = Ins[i]; 2337 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2338 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2339 continue; 2340 } 2341 2342 CCValAssign &VA = ArgLocs[ArgIdx++]; 2343 MVT VT = VA.getLocVT(); 2344 2345 if (IsEntryFunc && VA.isMemLoc()) { 2346 VT = Ins[i].VT; 2347 EVT MemVT = VA.getLocVT(); 2348 2349 const uint64_t Offset = VA.getLocMemOffset(); 2350 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2351 2352 if (Arg.Flags.isByRef()) { 2353 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2354 2355 const GCNTargetMachine &TM = 2356 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2357 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2358 Arg.Flags.getPointerAddrSpace())) { 2359 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2360 Arg.Flags.getPointerAddrSpace()); 2361 } 2362 2363 InVals.push_back(Ptr); 2364 continue; 2365 } 2366 2367 SDValue Arg = lowerKernargMemParameter( 2368 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2369 Chains.push_back(Arg.getValue(1)); 2370 2371 auto *ParamTy = 2372 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2373 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2374 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2375 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2376 // On SI local pointers are just offsets into LDS, so they are always 2377 // less than 16-bits. On CI and newer they could potentially be 2378 // real pointers, so we can't guarantee their size. 2379 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2380 DAG.getValueType(MVT::i16)); 2381 } 2382 2383 InVals.push_back(Arg); 2384 continue; 2385 } else if (!IsEntryFunc && VA.isMemLoc()) { 2386 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2387 InVals.push_back(Val); 2388 if (!Arg.Flags.isByVal()) 2389 Chains.push_back(Val.getValue(1)); 2390 continue; 2391 } 2392 2393 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2394 2395 Register Reg = VA.getLocReg(); 2396 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2397 EVT ValVT = VA.getValVT(); 2398 2399 Reg = MF.addLiveIn(Reg, RC); 2400 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2401 2402 if (Arg.Flags.isSRet()) { 2403 // The return object should be reasonably addressable. 2404 2405 // FIXME: This helps when the return is a real sret. If it is a 2406 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2407 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2408 unsigned NumBits 2409 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2410 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2411 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2412 } 2413 2414 // If this is an 8 or 16-bit value, it is really passed promoted 2415 // to 32 bits. Insert an assert[sz]ext to capture this, then 2416 // truncate to the right size. 2417 switch (VA.getLocInfo()) { 2418 case CCValAssign::Full: 2419 break; 2420 case CCValAssign::BCvt: 2421 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2422 break; 2423 case CCValAssign::SExt: 2424 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2425 DAG.getValueType(ValVT)); 2426 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2427 break; 2428 case CCValAssign::ZExt: 2429 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2430 DAG.getValueType(ValVT)); 2431 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2432 break; 2433 case CCValAssign::AExt: 2434 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2435 break; 2436 default: 2437 llvm_unreachable("Unknown loc info!"); 2438 } 2439 2440 InVals.push_back(Val); 2441 } 2442 2443 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2444 // Special inputs come after user arguments. 2445 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2446 } 2447 2448 // Start adding system SGPRs. 2449 if (IsEntryFunc) { 2450 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2451 } else { 2452 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2453 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2454 } 2455 2456 auto &ArgUsageInfo = 2457 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2458 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2459 2460 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2461 Info->setBytesInStackArgArea(StackArgSize); 2462 2463 return Chains.empty() ? Chain : 2464 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2465 } 2466 2467 // TODO: If return values can't fit in registers, we should return as many as 2468 // possible in registers before passing on stack. 2469 bool SITargetLowering::CanLowerReturn( 2470 CallingConv::ID CallConv, 2471 MachineFunction &MF, bool IsVarArg, 2472 const SmallVectorImpl<ISD::OutputArg> &Outs, 2473 LLVMContext &Context) const { 2474 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2475 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2476 // for shaders. Vector types should be explicitly handled by CC. 2477 if (AMDGPU::isEntryFunctionCC(CallConv)) 2478 return true; 2479 2480 SmallVector<CCValAssign, 16> RVLocs; 2481 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2482 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2483 } 2484 2485 SDValue 2486 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2487 bool isVarArg, 2488 const SmallVectorImpl<ISD::OutputArg> &Outs, 2489 const SmallVectorImpl<SDValue> &OutVals, 2490 const SDLoc &DL, SelectionDAG &DAG) const { 2491 MachineFunction &MF = DAG.getMachineFunction(); 2492 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2493 2494 if (AMDGPU::isKernel(CallConv)) { 2495 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2496 OutVals, DL, DAG); 2497 } 2498 2499 bool IsShader = AMDGPU::isShader(CallConv); 2500 2501 Info->setIfReturnsVoid(Outs.empty()); 2502 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2503 2504 // CCValAssign - represent the assignment of the return value to a location. 2505 SmallVector<CCValAssign, 48> RVLocs; 2506 SmallVector<ISD::OutputArg, 48> Splits; 2507 2508 // CCState - Info about the registers and stack slots. 2509 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2510 *DAG.getContext()); 2511 2512 // Analyze outgoing return values. 2513 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2514 2515 SDValue Flag; 2516 SmallVector<SDValue, 48> RetOps; 2517 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2518 2519 // Add return address for callable functions. 2520 if (!Info->isEntryFunction()) { 2521 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2522 SDValue ReturnAddrReg = CreateLiveInRegister( 2523 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2524 2525 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2526 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2527 MVT::i64); 2528 Chain = 2529 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2530 Flag = Chain.getValue(1); 2531 RetOps.push_back(ReturnAddrVirtualReg); 2532 } 2533 2534 // Copy the result values into the output registers. 2535 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2536 ++I, ++RealRVLocIdx) { 2537 CCValAssign &VA = RVLocs[I]; 2538 assert(VA.isRegLoc() && "Can only return in registers!"); 2539 // TODO: Partially return in registers if return values don't fit. 2540 SDValue Arg = OutVals[RealRVLocIdx]; 2541 2542 // Copied from other backends. 2543 switch (VA.getLocInfo()) { 2544 case CCValAssign::Full: 2545 break; 2546 case CCValAssign::BCvt: 2547 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2548 break; 2549 case CCValAssign::SExt: 2550 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2551 break; 2552 case CCValAssign::ZExt: 2553 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2554 break; 2555 case CCValAssign::AExt: 2556 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2557 break; 2558 default: 2559 llvm_unreachable("Unknown loc info!"); 2560 } 2561 2562 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2563 Flag = Chain.getValue(1); 2564 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2565 } 2566 2567 // FIXME: Does sret work properly? 2568 if (!Info->isEntryFunction()) { 2569 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2570 const MCPhysReg *I = 2571 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2572 if (I) { 2573 for (; *I; ++I) { 2574 if (AMDGPU::SReg_64RegClass.contains(*I)) 2575 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2576 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2577 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2578 else 2579 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2580 } 2581 } 2582 } 2583 2584 // Update chain and glue. 2585 RetOps[0] = Chain; 2586 if (Flag.getNode()) 2587 RetOps.push_back(Flag); 2588 2589 unsigned Opc = AMDGPUISD::ENDPGM; 2590 if (!IsWaveEnd) 2591 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2592 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2593 } 2594 2595 SDValue SITargetLowering::LowerCallResult( 2596 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2597 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2598 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2599 SDValue ThisVal) const { 2600 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2601 2602 // Assign locations to each value returned by this call. 2603 SmallVector<CCValAssign, 16> RVLocs; 2604 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2605 *DAG.getContext()); 2606 CCInfo.AnalyzeCallResult(Ins, RetCC); 2607 2608 // Copy all of the result registers out of their specified physreg. 2609 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2610 CCValAssign VA = RVLocs[i]; 2611 SDValue Val; 2612 2613 if (VA.isRegLoc()) { 2614 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2615 Chain = Val.getValue(1); 2616 InFlag = Val.getValue(2); 2617 } else if (VA.isMemLoc()) { 2618 report_fatal_error("TODO: return values in memory"); 2619 } else 2620 llvm_unreachable("unknown argument location type"); 2621 2622 switch (VA.getLocInfo()) { 2623 case CCValAssign::Full: 2624 break; 2625 case CCValAssign::BCvt: 2626 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2627 break; 2628 case CCValAssign::ZExt: 2629 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2630 DAG.getValueType(VA.getValVT())); 2631 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2632 break; 2633 case CCValAssign::SExt: 2634 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2635 DAG.getValueType(VA.getValVT())); 2636 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2637 break; 2638 case CCValAssign::AExt: 2639 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2640 break; 2641 default: 2642 llvm_unreachable("Unknown loc info!"); 2643 } 2644 2645 InVals.push_back(Val); 2646 } 2647 2648 return Chain; 2649 } 2650 2651 // Add code to pass special inputs required depending on used features separate 2652 // from the explicit user arguments present in the IR. 2653 void SITargetLowering::passSpecialInputs( 2654 CallLoweringInfo &CLI, 2655 CCState &CCInfo, 2656 const SIMachineFunctionInfo &Info, 2657 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2658 SmallVectorImpl<SDValue> &MemOpChains, 2659 SDValue Chain) const { 2660 // If we don't have a call site, this was a call inserted by 2661 // legalization. These can never use special inputs. 2662 if (!CLI.CB) 2663 return; 2664 2665 SelectionDAG &DAG = CLI.DAG; 2666 const SDLoc &DL = CLI.DL; 2667 2668 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2669 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2670 2671 const AMDGPUFunctionArgInfo *CalleeArgInfo 2672 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2673 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2674 auto &ArgUsageInfo = 2675 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2676 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2677 } 2678 2679 // TODO: Unify with private memory register handling. This is complicated by 2680 // the fact that at least in kernels, the input argument is not necessarily 2681 // in the same location as the input. 2682 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2683 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2684 AMDGPUFunctionArgInfo::QUEUE_PTR, 2685 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2686 AMDGPUFunctionArgInfo::DISPATCH_ID, 2687 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2688 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2689 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2690 }; 2691 2692 for (auto InputID : InputRegs) { 2693 const ArgDescriptor *OutgoingArg; 2694 const TargetRegisterClass *ArgRC; 2695 LLT ArgTy; 2696 2697 std::tie(OutgoingArg, ArgRC, ArgTy) = 2698 CalleeArgInfo->getPreloadedValue(InputID); 2699 if (!OutgoingArg) 2700 continue; 2701 2702 const ArgDescriptor *IncomingArg; 2703 const TargetRegisterClass *IncomingArgRC; 2704 LLT Ty; 2705 std::tie(IncomingArg, IncomingArgRC, Ty) = 2706 CallerArgInfo.getPreloadedValue(InputID); 2707 assert(IncomingArgRC == ArgRC); 2708 2709 // All special arguments are ints for now. 2710 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2711 SDValue InputReg; 2712 2713 if (IncomingArg) { 2714 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2715 } else { 2716 // The implicit arg ptr is special because it doesn't have a corresponding 2717 // input for kernels, and is computed from the kernarg segment pointer. 2718 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2719 InputReg = getImplicitArgPtr(DAG, DL); 2720 } 2721 2722 if (OutgoingArg->isRegister()) { 2723 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2724 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2725 report_fatal_error("failed to allocate implicit input argument"); 2726 } else { 2727 unsigned SpecialArgOffset = 2728 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2729 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2730 SpecialArgOffset); 2731 MemOpChains.push_back(ArgStore); 2732 } 2733 } 2734 2735 // Pack workitem IDs into a single register or pass it as is if already 2736 // packed. 2737 const ArgDescriptor *OutgoingArg; 2738 const TargetRegisterClass *ArgRC; 2739 LLT Ty; 2740 2741 std::tie(OutgoingArg, ArgRC, Ty) = 2742 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2743 if (!OutgoingArg) 2744 std::tie(OutgoingArg, ArgRC, Ty) = 2745 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2746 if (!OutgoingArg) 2747 std::tie(OutgoingArg, ArgRC, Ty) = 2748 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2749 if (!OutgoingArg) 2750 return; 2751 2752 const ArgDescriptor *IncomingArgX = std::get<0>( 2753 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2754 const ArgDescriptor *IncomingArgY = std::get<0>( 2755 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2756 const ArgDescriptor *IncomingArgZ = std::get<0>( 2757 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2758 2759 SDValue InputReg; 2760 SDLoc SL; 2761 2762 // If incoming ids are not packed we need to pack them. 2763 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2764 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2765 2766 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2767 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2768 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2769 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2770 InputReg = InputReg.getNode() ? 2771 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2772 } 2773 2774 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2775 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2776 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2777 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2778 InputReg = InputReg.getNode() ? 2779 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2780 } 2781 2782 if (!InputReg.getNode()) { 2783 // Workitem ids are already packed, any of present incoming arguments 2784 // will carry all required fields. 2785 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2786 IncomingArgX ? *IncomingArgX : 2787 IncomingArgY ? *IncomingArgY : 2788 *IncomingArgZ, ~0u); 2789 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2790 } 2791 2792 if (OutgoingArg->isRegister()) { 2793 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2794 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2795 } else { 2796 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2797 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2798 SpecialArgOffset); 2799 MemOpChains.push_back(ArgStore); 2800 } 2801 } 2802 2803 static bool canGuaranteeTCO(CallingConv::ID CC) { 2804 return CC == CallingConv::Fast; 2805 } 2806 2807 /// Return true if we might ever do TCO for calls with this calling convention. 2808 static bool mayTailCallThisCC(CallingConv::ID CC) { 2809 switch (CC) { 2810 case CallingConv::C: 2811 return true; 2812 default: 2813 return canGuaranteeTCO(CC); 2814 } 2815 } 2816 2817 bool SITargetLowering::isEligibleForTailCallOptimization( 2818 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2819 const SmallVectorImpl<ISD::OutputArg> &Outs, 2820 const SmallVectorImpl<SDValue> &OutVals, 2821 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2822 if (!mayTailCallThisCC(CalleeCC)) 2823 return false; 2824 2825 MachineFunction &MF = DAG.getMachineFunction(); 2826 const Function &CallerF = MF.getFunction(); 2827 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2828 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2829 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2830 2831 // Kernels aren't callable, and don't have a live in return address so it 2832 // doesn't make sense to do a tail call with entry functions. 2833 if (!CallerPreserved) 2834 return false; 2835 2836 bool CCMatch = CallerCC == CalleeCC; 2837 2838 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2839 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2840 return true; 2841 return false; 2842 } 2843 2844 // TODO: Can we handle var args? 2845 if (IsVarArg) 2846 return false; 2847 2848 for (const Argument &Arg : CallerF.args()) { 2849 if (Arg.hasByValAttr()) 2850 return false; 2851 } 2852 2853 LLVMContext &Ctx = *DAG.getContext(); 2854 2855 // Check that the call results are passed in the same way. 2856 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2857 CCAssignFnForCall(CalleeCC, IsVarArg), 2858 CCAssignFnForCall(CallerCC, IsVarArg))) 2859 return false; 2860 2861 // The callee has to preserve all registers the caller needs to preserve. 2862 if (!CCMatch) { 2863 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2864 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2865 return false; 2866 } 2867 2868 // Nothing more to check if the callee is taking no arguments. 2869 if (Outs.empty()) 2870 return true; 2871 2872 SmallVector<CCValAssign, 16> ArgLocs; 2873 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2874 2875 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2876 2877 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2878 // If the stack arguments for this call do not fit into our own save area then 2879 // the call cannot be made tail. 2880 // TODO: Is this really necessary? 2881 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2882 return false; 2883 2884 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2885 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2886 } 2887 2888 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2889 if (!CI->isTailCall()) 2890 return false; 2891 2892 const Function *ParentFn = CI->getParent()->getParent(); 2893 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2894 return false; 2895 return true; 2896 } 2897 2898 // The wave scratch offset register is used as the global base pointer. 2899 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2900 SmallVectorImpl<SDValue> &InVals) const { 2901 SelectionDAG &DAG = CLI.DAG; 2902 const SDLoc &DL = CLI.DL; 2903 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2904 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2905 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2906 SDValue Chain = CLI.Chain; 2907 SDValue Callee = CLI.Callee; 2908 bool &IsTailCall = CLI.IsTailCall; 2909 CallingConv::ID CallConv = CLI.CallConv; 2910 bool IsVarArg = CLI.IsVarArg; 2911 bool IsSibCall = false; 2912 bool IsThisReturn = false; 2913 MachineFunction &MF = DAG.getMachineFunction(); 2914 2915 if (Callee.isUndef() || isNullConstant(Callee)) { 2916 if (!CLI.IsTailCall) { 2917 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2918 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2919 } 2920 2921 return Chain; 2922 } 2923 2924 if (IsVarArg) { 2925 return lowerUnhandledCall(CLI, InVals, 2926 "unsupported call to variadic function "); 2927 } 2928 2929 if (!CLI.CB) 2930 report_fatal_error("unsupported libcall legalization"); 2931 2932 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2933 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2934 return lowerUnhandledCall(CLI, InVals, 2935 "unsupported indirect call to function "); 2936 } 2937 2938 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2939 return lowerUnhandledCall(CLI, InVals, 2940 "unsupported required tail call to function "); 2941 } 2942 2943 if (AMDGPU::isShader(CallConv)) { 2944 // Note the issue is with the CC of the called function, not of the call 2945 // itself. 2946 return lowerUnhandledCall(CLI, InVals, 2947 "unsupported call to a shader function "); 2948 } 2949 2950 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2951 CallConv != CallingConv::AMDGPU_Gfx) { 2952 // Only allow calls with specific calling conventions. 2953 return lowerUnhandledCall(CLI, InVals, 2954 "unsupported calling convention for call from " 2955 "graphics shader of function "); 2956 } 2957 2958 if (IsTailCall) { 2959 IsTailCall = isEligibleForTailCallOptimization( 2960 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2961 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2962 report_fatal_error("failed to perform tail call elimination on a call " 2963 "site marked musttail"); 2964 } 2965 2966 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2967 2968 // A sibling call is one where we're under the usual C ABI and not planning 2969 // to change that but can still do a tail call: 2970 if (!TailCallOpt && IsTailCall) 2971 IsSibCall = true; 2972 2973 if (IsTailCall) 2974 ++NumTailCalls; 2975 } 2976 2977 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2978 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2979 SmallVector<SDValue, 8> MemOpChains; 2980 2981 // Analyze operands of the call, assigning locations to each operand. 2982 SmallVector<CCValAssign, 16> ArgLocs; 2983 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2984 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2985 2986 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 2987 CallConv != CallingConv::AMDGPU_Gfx) { 2988 // With a fixed ABI, allocate fixed registers before user arguments. 2989 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2990 } 2991 2992 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2993 2994 // Get a count of how many bytes are to be pushed on the stack. 2995 unsigned NumBytes = CCInfo.getNextStackOffset(); 2996 2997 if (IsSibCall) { 2998 // Since we're not changing the ABI to make this a tail call, the memory 2999 // operands are already available in the caller's incoming argument space. 3000 NumBytes = 0; 3001 } 3002 3003 // FPDiff is the byte offset of the call's argument area from the callee's. 3004 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3005 // by this amount for a tail call. In a sibling call it must be 0 because the 3006 // caller will deallocate the entire stack and the callee still expects its 3007 // arguments to begin at SP+0. Completely unused for non-tail calls. 3008 int32_t FPDiff = 0; 3009 MachineFrameInfo &MFI = MF.getFrameInfo(); 3010 3011 // Adjust the stack pointer for the new arguments... 3012 // These operations are automatically eliminated by the prolog/epilog pass 3013 if (!IsSibCall) { 3014 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3015 3016 if (!Subtarget->enableFlatScratch()) { 3017 SmallVector<SDValue, 4> CopyFromChains; 3018 3019 // In the HSA case, this should be an identity copy. 3020 SDValue ScratchRSrcReg 3021 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3022 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3023 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3024 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3025 } 3026 } 3027 3028 MVT PtrVT = MVT::i32; 3029 3030 // Walk the register/memloc assignments, inserting copies/loads. 3031 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3032 CCValAssign &VA = ArgLocs[i]; 3033 SDValue Arg = OutVals[i]; 3034 3035 // Promote the value if needed. 3036 switch (VA.getLocInfo()) { 3037 case CCValAssign::Full: 3038 break; 3039 case CCValAssign::BCvt: 3040 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3041 break; 3042 case CCValAssign::ZExt: 3043 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3044 break; 3045 case CCValAssign::SExt: 3046 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3047 break; 3048 case CCValAssign::AExt: 3049 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3050 break; 3051 case CCValAssign::FPExt: 3052 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3053 break; 3054 default: 3055 llvm_unreachable("Unknown loc info!"); 3056 } 3057 3058 if (VA.isRegLoc()) { 3059 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3060 } else { 3061 assert(VA.isMemLoc()); 3062 3063 SDValue DstAddr; 3064 MachinePointerInfo DstInfo; 3065 3066 unsigned LocMemOffset = VA.getLocMemOffset(); 3067 int32_t Offset = LocMemOffset; 3068 3069 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3070 MaybeAlign Alignment; 3071 3072 if (IsTailCall) { 3073 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3074 unsigned OpSize = Flags.isByVal() ? 3075 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3076 3077 // FIXME: We can have better than the minimum byval required alignment. 3078 Alignment = 3079 Flags.isByVal() 3080 ? Flags.getNonZeroByValAlign() 3081 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3082 3083 Offset = Offset + FPDiff; 3084 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3085 3086 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3087 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3088 3089 // Make sure any stack arguments overlapping with where we're storing 3090 // are loaded before this eventual operation. Otherwise they'll be 3091 // clobbered. 3092 3093 // FIXME: Why is this really necessary? This seems to just result in a 3094 // lot of code to copy the stack and write them back to the same 3095 // locations, which are supposed to be immutable? 3096 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3097 } else { 3098 DstAddr = PtrOff; 3099 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3100 Alignment = 3101 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3102 } 3103 3104 if (Outs[i].Flags.isByVal()) { 3105 SDValue SizeNode = 3106 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3107 SDValue Cpy = 3108 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3109 Outs[i].Flags.getNonZeroByValAlign(), 3110 /*isVol = */ false, /*AlwaysInline = */ true, 3111 /*isTailCall = */ false, DstInfo, 3112 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3113 3114 MemOpChains.push_back(Cpy); 3115 } else { 3116 SDValue Store = 3117 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3118 MemOpChains.push_back(Store); 3119 } 3120 } 3121 } 3122 3123 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3124 CallConv != CallingConv::AMDGPU_Gfx) { 3125 // Copy special input registers after user input arguments. 3126 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3127 } 3128 3129 if (!MemOpChains.empty()) 3130 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3131 3132 // Build a sequence of copy-to-reg nodes chained together with token chain 3133 // and flag operands which copy the outgoing args into the appropriate regs. 3134 SDValue InFlag; 3135 for (auto &RegToPass : RegsToPass) { 3136 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3137 RegToPass.second, InFlag); 3138 InFlag = Chain.getValue(1); 3139 } 3140 3141 3142 SDValue PhysReturnAddrReg; 3143 if (IsTailCall) { 3144 // Since the return is being combined with the call, we need to pass on the 3145 // return address. 3146 3147 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3148 SDValue ReturnAddrReg = CreateLiveInRegister( 3149 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3150 3151 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3152 MVT::i64); 3153 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3154 InFlag = Chain.getValue(1); 3155 } 3156 3157 // We don't usually want to end the call-sequence here because we would tidy 3158 // the frame up *after* the call, however in the ABI-changing tail-call case 3159 // we've carefully laid out the parameters so that when sp is reset they'll be 3160 // in the correct location. 3161 if (IsTailCall && !IsSibCall) { 3162 Chain = DAG.getCALLSEQ_END(Chain, 3163 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3164 DAG.getTargetConstant(0, DL, MVT::i32), 3165 InFlag, DL); 3166 InFlag = Chain.getValue(1); 3167 } 3168 3169 std::vector<SDValue> Ops; 3170 Ops.push_back(Chain); 3171 Ops.push_back(Callee); 3172 // Add a redundant copy of the callee global which will not be legalized, as 3173 // we need direct access to the callee later. 3174 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3175 const GlobalValue *GV = GSD->getGlobal(); 3176 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3177 } else { 3178 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3179 } 3180 3181 if (IsTailCall) { 3182 // Each tail call may have to adjust the stack by a different amount, so 3183 // this information must travel along with the operation for eventual 3184 // consumption by emitEpilogue. 3185 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3186 3187 Ops.push_back(PhysReturnAddrReg); 3188 } 3189 3190 // Add argument registers to the end of the list so that they are known live 3191 // into the call. 3192 for (auto &RegToPass : RegsToPass) { 3193 Ops.push_back(DAG.getRegister(RegToPass.first, 3194 RegToPass.second.getValueType())); 3195 } 3196 3197 // Add a register mask operand representing the call-preserved registers. 3198 3199 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3200 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3201 assert(Mask && "Missing call preserved mask for calling convention"); 3202 Ops.push_back(DAG.getRegisterMask(Mask)); 3203 3204 if (InFlag.getNode()) 3205 Ops.push_back(InFlag); 3206 3207 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3208 3209 // If we're doing a tall call, use a TC_RETURN here rather than an 3210 // actual call instruction. 3211 if (IsTailCall) { 3212 MFI.setHasTailCall(); 3213 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3214 } 3215 3216 // Returns a chain and a flag for retval copy to use. 3217 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3218 Chain = Call.getValue(0); 3219 InFlag = Call.getValue(1); 3220 3221 uint64_t CalleePopBytes = NumBytes; 3222 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3223 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3224 InFlag, DL); 3225 if (!Ins.empty()) 3226 InFlag = Chain.getValue(1); 3227 3228 // Handle result values, copying them out of physregs into vregs that we 3229 // return. 3230 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3231 InVals, IsThisReturn, 3232 IsThisReturn ? OutVals[0] : SDValue()); 3233 } 3234 3235 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3236 // except for applying the wave size scale to the increment amount. 3237 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3238 SDValue Op, SelectionDAG &DAG) const { 3239 const MachineFunction &MF = DAG.getMachineFunction(); 3240 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3241 3242 SDLoc dl(Op); 3243 EVT VT = Op.getValueType(); 3244 SDValue Tmp1 = Op; 3245 SDValue Tmp2 = Op.getValue(1); 3246 SDValue Tmp3 = Op.getOperand(2); 3247 SDValue Chain = Tmp1.getOperand(0); 3248 3249 Register SPReg = Info->getStackPtrOffsetReg(); 3250 3251 // Chain the dynamic stack allocation so that it doesn't modify the stack 3252 // pointer when other instructions are using the stack. 3253 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3254 3255 SDValue Size = Tmp2.getOperand(1); 3256 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3257 Chain = SP.getValue(1); 3258 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3259 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3260 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3261 unsigned Opc = 3262 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3263 ISD::ADD : ISD::SUB; 3264 3265 SDValue ScaledSize = DAG.getNode( 3266 ISD::SHL, dl, VT, Size, 3267 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3268 3269 Align StackAlign = TFL->getStackAlign(); 3270 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3271 if (Alignment && *Alignment > StackAlign) { 3272 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3273 DAG.getConstant(-(uint64_t)Alignment->value() 3274 << ST.getWavefrontSizeLog2(), 3275 dl, VT)); 3276 } 3277 3278 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3279 Tmp2 = DAG.getCALLSEQ_END( 3280 Chain, DAG.getIntPtrConstant(0, dl, true), 3281 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3282 3283 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3284 } 3285 3286 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3287 SelectionDAG &DAG) const { 3288 // We only handle constant sizes here to allow non-entry block, static sized 3289 // allocas. A truly dynamic value is more difficult to support because we 3290 // don't know if the size value is uniform or not. If the size isn't uniform, 3291 // we would need to do a wave reduction to get the maximum size to know how 3292 // much to increment the uniform stack pointer. 3293 SDValue Size = Op.getOperand(1); 3294 if (isa<ConstantSDNode>(Size)) 3295 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3296 3297 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3298 } 3299 3300 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3301 const MachineFunction &MF) const { 3302 Register Reg = StringSwitch<Register>(RegName) 3303 .Case("m0", AMDGPU::M0) 3304 .Case("exec", AMDGPU::EXEC) 3305 .Case("exec_lo", AMDGPU::EXEC_LO) 3306 .Case("exec_hi", AMDGPU::EXEC_HI) 3307 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3308 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3309 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3310 .Default(Register()); 3311 3312 if (Reg == AMDGPU::NoRegister) { 3313 report_fatal_error(Twine("invalid register name \"" 3314 + StringRef(RegName) + "\".")); 3315 3316 } 3317 3318 if (!Subtarget->hasFlatScrRegister() && 3319 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3320 report_fatal_error(Twine("invalid register \"" 3321 + StringRef(RegName) + "\" for subtarget.")); 3322 } 3323 3324 switch (Reg) { 3325 case AMDGPU::M0: 3326 case AMDGPU::EXEC_LO: 3327 case AMDGPU::EXEC_HI: 3328 case AMDGPU::FLAT_SCR_LO: 3329 case AMDGPU::FLAT_SCR_HI: 3330 if (VT.getSizeInBits() == 32) 3331 return Reg; 3332 break; 3333 case AMDGPU::EXEC: 3334 case AMDGPU::FLAT_SCR: 3335 if (VT.getSizeInBits() == 64) 3336 return Reg; 3337 break; 3338 default: 3339 llvm_unreachable("missing register type checking"); 3340 } 3341 3342 report_fatal_error(Twine("invalid type for register \"" 3343 + StringRef(RegName) + "\".")); 3344 } 3345 3346 // If kill is not the last instruction, split the block so kill is always a 3347 // proper terminator. 3348 MachineBasicBlock * 3349 SITargetLowering::splitKillBlock(MachineInstr &MI, 3350 MachineBasicBlock *BB) const { 3351 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3352 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3353 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3354 return SplitBB; 3355 } 3356 3357 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3358 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3359 // be the first instruction in the remainder block. 3360 // 3361 /// \returns { LoopBody, Remainder } 3362 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3363 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3364 MachineFunction *MF = MBB.getParent(); 3365 MachineBasicBlock::iterator I(&MI); 3366 3367 // To insert the loop we need to split the block. Move everything after this 3368 // point to a new block, and insert a new empty block between the two. 3369 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3370 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3371 MachineFunction::iterator MBBI(MBB); 3372 ++MBBI; 3373 3374 MF->insert(MBBI, LoopBB); 3375 MF->insert(MBBI, RemainderBB); 3376 3377 LoopBB->addSuccessor(LoopBB); 3378 LoopBB->addSuccessor(RemainderBB); 3379 3380 // Move the rest of the block into a new block. 3381 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3382 3383 if (InstInLoop) { 3384 auto Next = std::next(I); 3385 3386 // Move instruction to loop body. 3387 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3388 3389 // Move the rest of the block. 3390 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3391 } else { 3392 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3393 } 3394 3395 MBB.addSuccessor(LoopBB); 3396 3397 return std::make_pair(LoopBB, RemainderBB); 3398 } 3399 3400 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3401 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3402 MachineBasicBlock *MBB = MI.getParent(); 3403 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3404 auto I = MI.getIterator(); 3405 auto E = std::next(I); 3406 3407 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3408 .addImm(0); 3409 3410 MIBundleBuilder Bundler(*MBB, I, E); 3411 finalizeBundle(*MBB, Bundler.begin()); 3412 } 3413 3414 MachineBasicBlock * 3415 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3416 MachineBasicBlock *BB) const { 3417 const DebugLoc &DL = MI.getDebugLoc(); 3418 3419 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3420 3421 MachineBasicBlock *LoopBB; 3422 MachineBasicBlock *RemainderBB; 3423 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3424 3425 // Apparently kill flags are only valid if the def is in the same block? 3426 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3427 Src->setIsKill(false); 3428 3429 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3430 3431 MachineBasicBlock::iterator I = LoopBB->end(); 3432 3433 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3434 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3435 3436 // Clear TRAP_STS.MEM_VIOL 3437 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3438 .addImm(0) 3439 .addImm(EncodedReg); 3440 3441 bundleInstWithWaitcnt(MI); 3442 3443 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3444 3445 // Load and check TRAP_STS.MEM_VIOL 3446 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3447 .addImm(EncodedReg); 3448 3449 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3450 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3451 .addReg(Reg, RegState::Kill) 3452 .addImm(0); 3453 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3454 .addMBB(LoopBB); 3455 3456 return RemainderBB; 3457 } 3458 3459 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3460 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3461 // will only do one iteration. In the worst case, this will loop 64 times. 3462 // 3463 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3464 static MachineBasicBlock::iterator 3465 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3466 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3467 const DebugLoc &DL, const MachineOperand &Idx, 3468 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3469 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3470 Register &SGPRIdxReg) { 3471 3472 MachineFunction *MF = OrigBB.getParent(); 3473 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3474 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3475 MachineBasicBlock::iterator I = LoopBB.begin(); 3476 3477 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3478 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3479 Register NewExec = MRI.createVirtualRegister(BoolRC); 3480 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3481 Register CondReg = MRI.createVirtualRegister(BoolRC); 3482 3483 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3484 .addReg(InitReg) 3485 .addMBB(&OrigBB) 3486 .addReg(ResultReg) 3487 .addMBB(&LoopBB); 3488 3489 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3490 .addReg(InitSaveExecReg) 3491 .addMBB(&OrigBB) 3492 .addReg(NewExec) 3493 .addMBB(&LoopBB); 3494 3495 // Read the next variant <- also loop target. 3496 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3497 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3498 3499 // Compare the just read M0 value to all possible Idx values. 3500 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3501 .addReg(CurrentIdxReg) 3502 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3503 3504 // Update EXEC, save the original EXEC value to VCC. 3505 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3506 : AMDGPU::S_AND_SAVEEXEC_B64), 3507 NewExec) 3508 .addReg(CondReg, RegState::Kill); 3509 3510 MRI.setSimpleHint(NewExec, CondReg); 3511 3512 if (UseGPRIdxMode) { 3513 if (Offset == 0) { 3514 SGPRIdxReg = CurrentIdxReg; 3515 } else { 3516 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3517 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3518 .addReg(CurrentIdxReg, RegState::Kill) 3519 .addImm(Offset); 3520 } 3521 } else { 3522 // Move index from VCC into M0 3523 if (Offset == 0) { 3524 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3525 .addReg(CurrentIdxReg, RegState::Kill); 3526 } else { 3527 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3528 .addReg(CurrentIdxReg, RegState::Kill) 3529 .addImm(Offset); 3530 } 3531 } 3532 3533 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3534 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3535 MachineInstr *InsertPt = 3536 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3537 : AMDGPU::S_XOR_B64_term), Exec) 3538 .addReg(Exec) 3539 .addReg(NewExec); 3540 3541 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3542 // s_cbranch_scc0? 3543 3544 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3545 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3546 .addMBB(&LoopBB); 3547 3548 return InsertPt->getIterator(); 3549 } 3550 3551 // This has slightly sub-optimal regalloc when the source vector is killed by 3552 // the read. The register allocator does not understand that the kill is 3553 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3554 // subregister from it, using 1 more VGPR than necessary. This was saved when 3555 // this was expanded after register allocation. 3556 static MachineBasicBlock::iterator 3557 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3558 unsigned InitResultReg, unsigned PhiReg, int Offset, 3559 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3560 MachineFunction *MF = MBB.getParent(); 3561 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3562 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3563 MachineRegisterInfo &MRI = MF->getRegInfo(); 3564 const DebugLoc &DL = MI.getDebugLoc(); 3565 MachineBasicBlock::iterator I(&MI); 3566 3567 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3568 Register DstReg = MI.getOperand(0).getReg(); 3569 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3570 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3571 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3572 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3573 3574 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3575 3576 // Save the EXEC mask 3577 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3578 .addReg(Exec); 3579 3580 MachineBasicBlock *LoopBB; 3581 MachineBasicBlock *RemainderBB; 3582 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3583 3584 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3585 3586 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3587 InitResultReg, DstReg, PhiReg, TmpExec, 3588 Offset, UseGPRIdxMode, SGPRIdxReg); 3589 3590 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3591 MachineFunction::iterator MBBI(LoopBB); 3592 ++MBBI; 3593 MF->insert(MBBI, LandingPad); 3594 LoopBB->removeSuccessor(RemainderBB); 3595 LandingPad->addSuccessor(RemainderBB); 3596 LoopBB->addSuccessor(LandingPad); 3597 MachineBasicBlock::iterator First = LandingPad->begin(); 3598 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3599 .addReg(SaveExec); 3600 3601 return InsPt; 3602 } 3603 3604 // Returns subreg index, offset 3605 static std::pair<unsigned, int> 3606 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3607 const TargetRegisterClass *SuperRC, 3608 unsigned VecReg, 3609 int Offset) { 3610 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3611 3612 // Skip out of bounds offsets, or else we would end up using an undefined 3613 // register. 3614 if (Offset >= NumElts || Offset < 0) 3615 return std::make_pair(AMDGPU::sub0, Offset); 3616 3617 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3618 } 3619 3620 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3621 MachineRegisterInfo &MRI, MachineInstr &MI, 3622 int Offset) { 3623 MachineBasicBlock *MBB = MI.getParent(); 3624 const DebugLoc &DL = MI.getDebugLoc(); 3625 MachineBasicBlock::iterator I(&MI); 3626 3627 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3628 3629 assert(Idx->getReg() != AMDGPU::NoRegister); 3630 3631 if (Offset == 0) { 3632 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3633 } else { 3634 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3635 .add(*Idx) 3636 .addImm(Offset); 3637 } 3638 } 3639 3640 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3641 MachineRegisterInfo &MRI, MachineInstr &MI, 3642 int Offset) { 3643 MachineBasicBlock *MBB = MI.getParent(); 3644 const DebugLoc &DL = MI.getDebugLoc(); 3645 MachineBasicBlock::iterator I(&MI); 3646 3647 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3648 3649 if (Offset == 0) 3650 return Idx->getReg(); 3651 3652 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3653 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3654 .add(*Idx) 3655 .addImm(Offset); 3656 return Tmp; 3657 } 3658 3659 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3660 MachineBasicBlock &MBB, 3661 const GCNSubtarget &ST) { 3662 const SIInstrInfo *TII = ST.getInstrInfo(); 3663 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3664 MachineFunction *MF = MBB.getParent(); 3665 MachineRegisterInfo &MRI = MF->getRegInfo(); 3666 3667 Register Dst = MI.getOperand(0).getReg(); 3668 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3669 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3670 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3671 3672 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3673 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3674 3675 unsigned SubReg; 3676 std::tie(SubReg, Offset) 3677 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3678 3679 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3680 3681 // Check for a SGPR index. 3682 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3683 MachineBasicBlock::iterator I(&MI); 3684 const DebugLoc &DL = MI.getDebugLoc(); 3685 3686 if (UseGPRIdxMode) { 3687 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3688 // to avoid interfering with other uses, so probably requires a new 3689 // optimization pass. 3690 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3691 3692 const MCInstrDesc &GPRIDXDesc = 3693 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3694 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3695 .addReg(SrcReg) 3696 .addReg(Idx) 3697 .addImm(SubReg); 3698 } else { 3699 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3700 3701 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3702 .addReg(SrcReg, 0, SubReg) 3703 .addReg(SrcReg, RegState::Implicit); 3704 } 3705 3706 MI.eraseFromParent(); 3707 3708 return &MBB; 3709 } 3710 3711 // Control flow needs to be inserted if indexing with a VGPR. 3712 const DebugLoc &DL = MI.getDebugLoc(); 3713 MachineBasicBlock::iterator I(&MI); 3714 3715 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3716 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3717 3718 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3719 3720 Register SGPRIdxReg; 3721 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3722 UseGPRIdxMode, SGPRIdxReg); 3723 3724 MachineBasicBlock *LoopBB = InsPt->getParent(); 3725 3726 if (UseGPRIdxMode) { 3727 const MCInstrDesc &GPRIDXDesc = 3728 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3729 3730 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3731 .addReg(SrcReg) 3732 .addReg(SGPRIdxReg) 3733 .addImm(SubReg); 3734 } else { 3735 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3736 .addReg(SrcReg, 0, SubReg) 3737 .addReg(SrcReg, RegState::Implicit); 3738 } 3739 3740 MI.eraseFromParent(); 3741 3742 return LoopBB; 3743 } 3744 3745 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3746 MachineBasicBlock &MBB, 3747 const GCNSubtarget &ST) { 3748 const SIInstrInfo *TII = ST.getInstrInfo(); 3749 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3750 MachineFunction *MF = MBB.getParent(); 3751 MachineRegisterInfo &MRI = MF->getRegInfo(); 3752 3753 Register Dst = MI.getOperand(0).getReg(); 3754 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3755 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3756 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3757 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3758 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3759 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3760 3761 // This can be an immediate, but will be folded later. 3762 assert(Val->getReg()); 3763 3764 unsigned SubReg; 3765 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3766 SrcVec->getReg(), 3767 Offset); 3768 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3769 3770 if (Idx->getReg() == AMDGPU::NoRegister) { 3771 MachineBasicBlock::iterator I(&MI); 3772 const DebugLoc &DL = MI.getDebugLoc(); 3773 3774 assert(Offset == 0); 3775 3776 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3777 .add(*SrcVec) 3778 .add(*Val) 3779 .addImm(SubReg); 3780 3781 MI.eraseFromParent(); 3782 return &MBB; 3783 } 3784 3785 // Check for a SGPR index. 3786 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3787 MachineBasicBlock::iterator I(&MI); 3788 const DebugLoc &DL = MI.getDebugLoc(); 3789 3790 if (UseGPRIdxMode) { 3791 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3792 3793 const MCInstrDesc &GPRIDXDesc = 3794 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3795 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3796 .addReg(SrcVec->getReg()) 3797 .add(*Val) 3798 .addReg(Idx) 3799 .addImm(SubReg); 3800 } else { 3801 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3802 3803 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3804 TRI.getRegSizeInBits(*VecRC), 32, false); 3805 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3806 .addReg(SrcVec->getReg()) 3807 .add(*Val) 3808 .addImm(SubReg); 3809 } 3810 MI.eraseFromParent(); 3811 return &MBB; 3812 } 3813 3814 // Control flow needs to be inserted if indexing with a VGPR. 3815 if (Val->isReg()) 3816 MRI.clearKillFlags(Val->getReg()); 3817 3818 const DebugLoc &DL = MI.getDebugLoc(); 3819 3820 Register PhiReg = MRI.createVirtualRegister(VecRC); 3821 3822 Register SGPRIdxReg; 3823 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3824 UseGPRIdxMode, SGPRIdxReg); 3825 MachineBasicBlock *LoopBB = InsPt->getParent(); 3826 3827 if (UseGPRIdxMode) { 3828 const MCInstrDesc &GPRIDXDesc = 3829 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3830 3831 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3832 .addReg(PhiReg) 3833 .add(*Val) 3834 .addReg(SGPRIdxReg) 3835 .addImm(AMDGPU::sub0); 3836 } else { 3837 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3838 TRI.getRegSizeInBits(*VecRC), 32, false); 3839 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3840 .addReg(PhiReg) 3841 .add(*Val) 3842 .addImm(AMDGPU::sub0); 3843 } 3844 3845 MI.eraseFromParent(); 3846 return LoopBB; 3847 } 3848 3849 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3850 MachineInstr &MI, MachineBasicBlock *BB) const { 3851 3852 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3853 MachineFunction *MF = BB->getParent(); 3854 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3855 3856 switch (MI.getOpcode()) { 3857 case AMDGPU::S_UADDO_PSEUDO: 3858 case AMDGPU::S_USUBO_PSEUDO: { 3859 const DebugLoc &DL = MI.getDebugLoc(); 3860 MachineOperand &Dest0 = MI.getOperand(0); 3861 MachineOperand &Dest1 = MI.getOperand(1); 3862 MachineOperand &Src0 = MI.getOperand(2); 3863 MachineOperand &Src1 = MI.getOperand(3); 3864 3865 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3866 ? AMDGPU::S_ADD_I32 3867 : AMDGPU::S_SUB_I32; 3868 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3869 3870 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3871 .addImm(1) 3872 .addImm(0); 3873 3874 MI.eraseFromParent(); 3875 return BB; 3876 } 3877 case AMDGPU::S_ADD_U64_PSEUDO: 3878 case AMDGPU::S_SUB_U64_PSEUDO: { 3879 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3880 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3881 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3882 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3883 const DebugLoc &DL = MI.getDebugLoc(); 3884 3885 MachineOperand &Dest = MI.getOperand(0); 3886 MachineOperand &Src0 = MI.getOperand(1); 3887 MachineOperand &Src1 = MI.getOperand(2); 3888 3889 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3890 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3891 3892 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3893 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3894 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3895 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3896 3897 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3898 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3899 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3900 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3901 3902 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3903 3904 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3905 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3906 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3907 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3908 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3909 .addReg(DestSub0) 3910 .addImm(AMDGPU::sub0) 3911 .addReg(DestSub1) 3912 .addImm(AMDGPU::sub1); 3913 MI.eraseFromParent(); 3914 return BB; 3915 } 3916 case AMDGPU::V_ADD_U64_PSEUDO: 3917 case AMDGPU::V_SUB_U64_PSEUDO: { 3918 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3919 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3920 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3921 const DebugLoc &DL = MI.getDebugLoc(); 3922 3923 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3924 3925 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3926 3927 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3928 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3929 3930 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3931 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3932 3933 MachineOperand &Dest = MI.getOperand(0); 3934 MachineOperand &Src0 = MI.getOperand(1); 3935 MachineOperand &Src1 = MI.getOperand(2); 3936 3937 const TargetRegisterClass *Src0RC = Src0.isReg() 3938 ? MRI.getRegClass(Src0.getReg()) 3939 : &AMDGPU::VReg_64RegClass; 3940 const TargetRegisterClass *Src1RC = Src1.isReg() 3941 ? MRI.getRegClass(Src1.getReg()) 3942 : &AMDGPU::VReg_64RegClass; 3943 3944 const TargetRegisterClass *Src0SubRC = 3945 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3946 const TargetRegisterClass *Src1SubRC = 3947 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3948 3949 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3950 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3951 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3952 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3953 3954 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3955 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3956 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3957 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3958 3959 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3960 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3961 .addReg(CarryReg, RegState::Define) 3962 .add(SrcReg0Sub0) 3963 .add(SrcReg1Sub0) 3964 .addImm(0); // clamp bit 3965 3966 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3967 MachineInstr *HiHalf = 3968 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3969 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3970 .add(SrcReg0Sub1) 3971 .add(SrcReg1Sub1) 3972 .addReg(CarryReg, RegState::Kill) 3973 .addImm(0); // clamp bit 3974 3975 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3976 .addReg(DestSub0) 3977 .addImm(AMDGPU::sub0) 3978 .addReg(DestSub1) 3979 .addImm(AMDGPU::sub1); 3980 TII->legalizeOperands(*LoHalf); 3981 TII->legalizeOperands(*HiHalf); 3982 MI.eraseFromParent(); 3983 return BB; 3984 } 3985 case AMDGPU::S_ADD_CO_PSEUDO: 3986 case AMDGPU::S_SUB_CO_PSEUDO: { 3987 // This pseudo has a chance to be selected 3988 // only from uniform add/subcarry node. All the VGPR operands 3989 // therefore assumed to be splat vectors. 3990 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3991 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3992 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3993 MachineBasicBlock::iterator MII = MI; 3994 const DebugLoc &DL = MI.getDebugLoc(); 3995 MachineOperand &Dest = MI.getOperand(0); 3996 MachineOperand &CarryDest = MI.getOperand(1); 3997 MachineOperand &Src0 = MI.getOperand(2); 3998 MachineOperand &Src1 = MI.getOperand(3); 3999 MachineOperand &Src2 = MI.getOperand(4); 4000 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4001 ? AMDGPU::S_ADDC_U32 4002 : AMDGPU::S_SUBB_U32; 4003 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4004 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4005 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4006 .addReg(Src0.getReg()); 4007 Src0.setReg(RegOp0); 4008 } 4009 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4010 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4011 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4012 .addReg(Src1.getReg()); 4013 Src1.setReg(RegOp1); 4014 } 4015 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4016 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4017 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4018 .addReg(Src2.getReg()); 4019 Src2.setReg(RegOp2); 4020 } 4021 4022 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4023 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4024 if (ST.hasScalarCompareEq64()) { 4025 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4026 .addReg(Src2.getReg()) 4027 .addImm(0); 4028 } else { 4029 const TargetRegisterClass *SubRC = 4030 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4031 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4032 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4033 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4034 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4035 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4036 4037 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4038 .add(Src2Sub0) 4039 .add(Src2Sub1); 4040 4041 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4042 .addReg(Src2_32, RegState::Kill) 4043 .addImm(0); 4044 } 4045 } else { 4046 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4047 .addReg(Src2.getReg()) 4048 .addImm(0); 4049 } 4050 4051 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4052 4053 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4054 .addReg(AMDGPU::SCC); 4055 MI.eraseFromParent(); 4056 return BB; 4057 } 4058 case AMDGPU::SI_INIT_M0: { 4059 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4060 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4061 .add(MI.getOperand(0)); 4062 MI.eraseFromParent(); 4063 return BB; 4064 } 4065 case AMDGPU::SI_INIT_EXEC: 4066 // This should be before all vector instructions. 4067 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 4068 AMDGPU::EXEC) 4069 .addImm(MI.getOperand(0).getImm()); 4070 MI.eraseFromParent(); 4071 return BB; 4072 4073 case AMDGPU::SI_INIT_EXEC_LO: 4074 // This should be before all vector instructions. 4075 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 4076 AMDGPU::EXEC_LO) 4077 .addImm(MI.getOperand(0).getImm()); 4078 MI.eraseFromParent(); 4079 return BB; 4080 4081 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 4082 // Extract the thread count from an SGPR input and set EXEC accordingly. 4083 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 4084 // 4085 // S_BFE_U32 count, input, {shift, 7} 4086 // S_BFM_B64 exec, count, 0 4087 // S_CMP_EQ_U32 count, 64 4088 // S_CMOV_B64 exec, -1 4089 MachineInstr *FirstMI = &*BB->begin(); 4090 MachineRegisterInfo &MRI = MF->getRegInfo(); 4091 Register InputReg = MI.getOperand(0).getReg(); 4092 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 4093 bool Found = false; 4094 4095 // Move the COPY of the input reg to the beginning, so that we can use it. 4096 for (auto I = BB->begin(); I != &MI; I++) { 4097 if (I->getOpcode() != TargetOpcode::COPY || 4098 I->getOperand(0).getReg() != InputReg) 4099 continue; 4100 4101 if (I == FirstMI) { 4102 FirstMI = &*++BB->begin(); 4103 } else { 4104 I->removeFromParent(); 4105 BB->insert(FirstMI, &*I); 4106 } 4107 Found = true; 4108 break; 4109 } 4110 assert(Found); 4111 (void)Found; 4112 4113 // This should be before all vector instructions. 4114 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 4115 bool isWave32 = getSubtarget()->isWave32(); 4116 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 4117 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 4118 .addReg(InputReg) 4119 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 4120 BuildMI(*BB, FirstMI, DebugLoc(), 4121 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 4122 Exec) 4123 .addReg(CountReg) 4124 .addImm(0); 4125 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 4126 .addReg(CountReg, RegState::Kill) 4127 .addImm(getSubtarget()->getWavefrontSize()); 4128 BuildMI(*BB, FirstMI, DebugLoc(), 4129 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 4130 Exec) 4131 .addImm(-1); 4132 MI.eraseFromParent(); 4133 return BB; 4134 } 4135 4136 case AMDGPU::GET_GROUPSTATICSIZE: { 4137 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4138 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4139 DebugLoc DL = MI.getDebugLoc(); 4140 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4141 .add(MI.getOperand(0)) 4142 .addImm(MFI->getLDSSize()); 4143 MI.eraseFromParent(); 4144 return BB; 4145 } 4146 case AMDGPU::SI_INDIRECT_SRC_V1: 4147 case AMDGPU::SI_INDIRECT_SRC_V2: 4148 case AMDGPU::SI_INDIRECT_SRC_V4: 4149 case AMDGPU::SI_INDIRECT_SRC_V8: 4150 case AMDGPU::SI_INDIRECT_SRC_V16: 4151 case AMDGPU::SI_INDIRECT_SRC_V32: 4152 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4153 case AMDGPU::SI_INDIRECT_DST_V1: 4154 case AMDGPU::SI_INDIRECT_DST_V2: 4155 case AMDGPU::SI_INDIRECT_DST_V4: 4156 case AMDGPU::SI_INDIRECT_DST_V8: 4157 case AMDGPU::SI_INDIRECT_DST_V16: 4158 case AMDGPU::SI_INDIRECT_DST_V32: 4159 return emitIndirectDst(MI, *BB, *getSubtarget()); 4160 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4161 case AMDGPU::SI_KILL_I1_PSEUDO: 4162 return splitKillBlock(MI, BB); 4163 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4164 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4165 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4166 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4167 4168 Register Dst = MI.getOperand(0).getReg(); 4169 Register Src0 = MI.getOperand(1).getReg(); 4170 Register Src1 = MI.getOperand(2).getReg(); 4171 const DebugLoc &DL = MI.getDebugLoc(); 4172 Register SrcCond = MI.getOperand(3).getReg(); 4173 4174 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4175 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4176 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4177 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4178 4179 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4180 .addReg(SrcCond); 4181 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4182 .addImm(0) 4183 .addReg(Src0, 0, AMDGPU::sub0) 4184 .addImm(0) 4185 .addReg(Src1, 0, AMDGPU::sub0) 4186 .addReg(SrcCondCopy); 4187 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4188 .addImm(0) 4189 .addReg(Src0, 0, AMDGPU::sub1) 4190 .addImm(0) 4191 .addReg(Src1, 0, AMDGPU::sub1) 4192 .addReg(SrcCondCopy); 4193 4194 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4195 .addReg(DstLo) 4196 .addImm(AMDGPU::sub0) 4197 .addReg(DstHi) 4198 .addImm(AMDGPU::sub1); 4199 MI.eraseFromParent(); 4200 return BB; 4201 } 4202 case AMDGPU::SI_BR_UNDEF: { 4203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4204 const DebugLoc &DL = MI.getDebugLoc(); 4205 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4206 .add(MI.getOperand(0)); 4207 Br->getOperand(1).setIsUndef(true); // read undef SCC 4208 MI.eraseFromParent(); 4209 return BB; 4210 } 4211 case AMDGPU::ADJCALLSTACKUP: 4212 case AMDGPU::ADJCALLSTACKDOWN: { 4213 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4214 MachineInstrBuilder MIB(*MF, &MI); 4215 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4216 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4217 return BB; 4218 } 4219 case AMDGPU::SI_CALL_ISEL: { 4220 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4221 const DebugLoc &DL = MI.getDebugLoc(); 4222 4223 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4224 4225 MachineInstrBuilder MIB; 4226 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4227 4228 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4229 MIB.add(MI.getOperand(I)); 4230 4231 MIB.cloneMemRefs(MI); 4232 MI.eraseFromParent(); 4233 return BB; 4234 } 4235 case AMDGPU::V_ADD_CO_U32_e32: 4236 case AMDGPU::V_SUB_CO_U32_e32: 4237 case AMDGPU::V_SUBREV_CO_U32_e32: { 4238 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4239 const DebugLoc &DL = MI.getDebugLoc(); 4240 unsigned Opc = MI.getOpcode(); 4241 4242 bool NeedClampOperand = false; 4243 if (TII->pseudoToMCOpcode(Opc) == -1) { 4244 Opc = AMDGPU::getVOPe64(Opc); 4245 NeedClampOperand = true; 4246 } 4247 4248 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4249 if (TII->isVOP3(*I)) { 4250 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4251 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4252 I.addReg(TRI->getVCC(), RegState::Define); 4253 } 4254 I.add(MI.getOperand(1)) 4255 .add(MI.getOperand(2)); 4256 if (NeedClampOperand) 4257 I.addImm(0); // clamp bit for e64 encoding 4258 4259 TII->legalizeOperands(*I); 4260 4261 MI.eraseFromParent(); 4262 return BB; 4263 } 4264 case AMDGPU::DS_GWS_INIT: 4265 case AMDGPU::DS_GWS_SEMA_V: 4266 case AMDGPU::DS_GWS_SEMA_BR: 4267 case AMDGPU::DS_GWS_SEMA_P: 4268 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4269 case AMDGPU::DS_GWS_BARRIER: 4270 // A s_waitcnt 0 is required to be the instruction immediately following. 4271 if (getSubtarget()->hasGWSAutoReplay()) { 4272 bundleInstWithWaitcnt(MI); 4273 return BB; 4274 } 4275 4276 return emitGWSMemViolTestLoop(MI, BB); 4277 case AMDGPU::S_SETREG_B32: { 4278 // Try to optimize cases that only set the denormal mode or rounding mode. 4279 // 4280 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4281 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4282 // instead. 4283 // 4284 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4285 // allow you to have a no side effect instruction in the output of a 4286 // sideeffecting pattern. 4287 unsigned ID, Offset, Width; 4288 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4289 if (ID != AMDGPU::Hwreg::ID_MODE) 4290 return BB; 4291 4292 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4293 const unsigned SetMask = WidthMask << Offset; 4294 4295 if (getSubtarget()->hasDenormModeInst()) { 4296 unsigned SetDenormOp = 0; 4297 unsigned SetRoundOp = 0; 4298 4299 // The dedicated instructions can only set the whole denorm or round mode 4300 // at once, not a subset of bits in either. 4301 if (SetMask == 4302 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4303 // If this fully sets both the round and denorm mode, emit the two 4304 // dedicated instructions for these. 4305 SetRoundOp = AMDGPU::S_ROUND_MODE; 4306 SetDenormOp = AMDGPU::S_DENORM_MODE; 4307 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4308 SetRoundOp = AMDGPU::S_ROUND_MODE; 4309 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4310 SetDenormOp = AMDGPU::S_DENORM_MODE; 4311 } 4312 4313 if (SetRoundOp || SetDenormOp) { 4314 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4315 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4316 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4317 unsigned ImmVal = Def->getOperand(1).getImm(); 4318 if (SetRoundOp) { 4319 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4320 .addImm(ImmVal & 0xf); 4321 4322 // If we also have the denorm mode, get just the denorm mode bits. 4323 ImmVal >>= 4; 4324 } 4325 4326 if (SetDenormOp) { 4327 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4328 .addImm(ImmVal & 0xf); 4329 } 4330 4331 MI.eraseFromParent(); 4332 return BB; 4333 } 4334 } 4335 } 4336 4337 // If only FP bits are touched, used the no side effects pseudo. 4338 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4339 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4340 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4341 4342 return BB; 4343 } 4344 default: 4345 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4346 } 4347 } 4348 4349 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4350 return isTypeLegal(VT.getScalarType()); 4351 } 4352 4353 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4354 // This currently forces unfolding various combinations of fsub into fma with 4355 // free fneg'd operands. As long as we have fast FMA (controlled by 4356 // isFMAFasterThanFMulAndFAdd), we should perform these. 4357 4358 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4359 // most of these combines appear to be cycle neutral but save on instruction 4360 // count / code size. 4361 return true; 4362 } 4363 4364 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4365 EVT VT) const { 4366 if (!VT.isVector()) { 4367 return MVT::i1; 4368 } 4369 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4370 } 4371 4372 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4373 // TODO: Should i16 be used always if legal? For now it would force VALU 4374 // shifts. 4375 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4376 } 4377 4378 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4379 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4380 ? Ty.changeElementSize(16) 4381 : Ty.changeElementSize(32); 4382 } 4383 4384 // Answering this is somewhat tricky and depends on the specific device which 4385 // have different rates for fma or all f64 operations. 4386 // 4387 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4388 // regardless of which device (although the number of cycles differs between 4389 // devices), so it is always profitable for f64. 4390 // 4391 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4392 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4393 // which we can always do even without fused FP ops since it returns the same 4394 // result as the separate operations and since it is always full 4395 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4396 // however does not support denormals, so we do report fma as faster if we have 4397 // a fast fma device and require denormals. 4398 // 4399 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4400 EVT VT) const { 4401 VT = VT.getScalarType(); 4402 4403 switch (VT.getSimpleVT().SimpleTy) { 4404 case MVT::f32: { 4405 // If mad is not available this depends only on if f32 fma is full rate. 4406 if (!Subtarget->hasMadMacF32Insts()) 4407 return Subtarget->hasFastFMAF32(); 4408 4409 // Otherwise f32 mad is always full rate and returns the same result as 4410 // the separate operations so should be preferred over fma. 4411 // However does not support denomals. 4412 if (hasFP32Denormals(MF)) 4413 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4414 4415 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4416 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4417 } 4418 case MVT::f64: 4419 return true; 4420 case MVT::f16: 4421 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4422 default: 4423 break; 4424 } 4425 4426 return false; 4427 } 4428 4429 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4430 const SDNode *N) const { 4431 // TODO: Check future ftz flag 4432 // v_mad_f32/v_mac_f32 do not support denormals. 4433 EVT VT = N->getValueType(0); 4434 if (VT == MVT::f32) 4435 return Subtarget->hasMadMacF32Insts() && 4436 !hasFP32Denormals(DAG.getMachineFunction()); 4437 if (VT == MVT::f16) { 4438 return Subtarget->hasMadF16() && 4439 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4440 } 4441 4442 return false; 4443 } 4444 4445 //===----------------------------------------------------------------------===// 4446 // Custom DAG Lowering Operations 4447 //===----------------------------------------------------------------------===// 4448 4449 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4450 // wider vector type is legal. 4451 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4452 SelectionDAG &DAG) const { 4453 unsigned Opc = Op.getOpcode(); 4454 EVT VT = Op.getValueType(); 4455 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4456 4457 SDValue Lo, Hi; 4458 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4459 4460 SDLoc SL(Op); 4461 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4462 Op->getFlags()); 4463 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4464 Op->getFlags()); 4465 4466 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4467 } 4468 4469 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4470 // wider vector type is legal. 4471 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4472 SelectionDAG &DAG) const { 4473 unsigned Opc = Op.getOpcode(); 4474 EVT VT = Op.getValueType(); 4475 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4476 4477 SDValue Lo0, Hi0; 4478 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4479 SDValue Lo1, Hi1; 4480 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4481 4482 SDLoc SL(Op); 4483 4484 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4485 Op->getFlags()); 4486 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4487 Op->getFlags()); 4488 4489 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4490 } 4491 4492 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4493 SelectionDAG &DAG) const { 4494 unsigned Opc = Op.getOpcode(); 4495 EVT VT = Op.getValueType(); 4496 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4497 4498 SDValue Lo0, Hi0; 4499 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4500 SDValue Lo1, Hi1; 4501 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4502 SDValue Lo2, Hi2; 4503 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4504 4505 SDLoc SL(Op); 4506 4507 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4508 Op->getFlags()); 4509 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4510 Op->getFlags()); 4511 4512 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4513 } 4514 4515 4516 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4517 switch (Op.getOpcode()) { 4518 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4519 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4520 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4521 case ISD::LOAD: { 4522 SDValue Result = LowerLOAD(Op, DAG); 4523 assert((!Result.getNode() || 4524 Result.getNode()->getNumValues() == 2) && 4525 "Load should return a value and a chain"); 4526 return Result; 4527 } 4528 4529 case ISD::FSIN: 4530 case ISD::FCOS: 4531 return LowerTrig(Op, DAG); 4532 case ISD::SELECT: return LowerSELECT(Op, DAG); 4533 case ISD::FDIV: return LowerFDIV(Op, DAG); 4534 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4535 case ISD::STORE: return LowerSTORE(Op, DAG); 4536 case ISD::GlobalAddress: { 4537 MachineFunction &MF = DAG.getMachineFunction(); 4538 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4539 return LowerGlobalAddress(MFI, Op, DAG); 4540 } 4541 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4542 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4543 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4544 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4545 case ISD::INSERT_SUBVECTOR: 4546 return lowerINSERT_SUBVECTOR(Op, DAG); 4547 case ISD::INSERT_VECTOR_ELT: 4548 return lowerINSERT_VECTOR_ELT(Op, DAG); 4549 case ISD::EXTRACT_VECTOR_ELT: 4550 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4551 case ISD::VECTOR_SHUFFLE: 4552 return lowerVECTOR_SHUFFLE(Op, DAG); 4553 case ISD::BUILD_VECTOR: 4554 return lowerBUILD_VECTOR(Op, DAG); 4555 case ISD::FP_ROUND: 4556 return lowerFP_ROUND(Op, DAG); 4557 case ISD::TRAP: 4558 return lowerTRAP(Op, DAG); 4559 case ISD::DEBUGTRAP: 4560 return lowerDEBUGTRAP(Op, DAG); 4561 case ISD::FABS: 4562 case ISD::FNEG: 4563 case ISD::FCANONICALIZE: 4564 case ISD::BSWAP: 4565 return splitUnaryVectorOp(Op, DAG); 4566 case ISD::FMINNUM: 4567 case ISD::FMAXNUM: 4568 return lowerFMINNUM_FMAXNUM(Op, DAG); 4569 case ISD::FMA: 4570 return splitTernaryVectorOp(Op, DAG); 4571 case ISD::SHL: 4572 case ISD::SRA: 4573 case ISD::SRL: 4574 case ISD::ADD: 4575 case ISD::SUB: 4576 case ISD::MUL: 4577 case ISD::SMIN: 4578 case ISD::SMAX: 4579 case ISD::UMIN: 4580 case ISD::UMAX: 4581 case ISD::FADD: 4582 case ISD::FMUL: 4583 case ISD::FMINNUM_IEEE: 4584 case ISD::FMAXNUM_IEEE: 4585 case ISD::UADDSAT: 4586 case ISD::USUBSAT: 4587 case ISD::SADDSAT: 4588 case ISD::SSUBSAT: 4589 return splitBinaryVectorOp(Op, DAG); 4590 case ISD::SMULO: 4591 case ISD::UMULO: 4592 return lowerXMULO(Op, DAG); 4593 case ISD::DYNAMIC_STACKALLOC: 4594 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4595 } 4596 return SDValue(); 4597 } 4598 4599 // Used for D16: Casts the result of an instruction into the right vector, 4600 // packs values if loads return unpacked values. 4601 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4602 const SDLoc &DL, 4603 SelectionDAG &DAG, bool Unpacked) { 4604 if (!LoadVT.isVector()) 4605 return Result; 4606 4607 // Cast back to the original packed type or to a larger type that is a 4608 // multiple of 32 bit for D16. Widening the return type is a required for 4609 // legalization. 4610 EVT FittingLoadVT = LoadVT; 4611 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4612 FittingLoadVT = 4613 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4614 LoadVT.getVectorNumElements() + 1); 4615 } 4616 4617 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4618 // Truncate to v2i16/v4i16. 4619 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4620 4621 // Workaround legalizer not scalarizing truncate after vector op 4622 // legalization but not creating intermediate vector trunc. 4623 SmallVector<SDValue, 4> Elts; 4624 DAG.ExtractVectorElements(Result, Elts); 4625 for (SDValue &Elt : Elts) 4626 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4627 4628 // Pad illegal v1i16/v3fi6 to v4i16 4629 if ((LoadVT.getVectorNumElements() % 2) == 1) 4630 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4631 4632 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4633 4634 // Bitcast to original type (v2f16/v4f16). 4635 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4636 } 4637 4638 // Cast back to the original packed type. 4639 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4640 } 4641 4642 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4643 MemSDNode *M, 4644 SelectionDAG &DAG, 4645 ArrayRef<SDValue> Ops, 4646 bool IsIntrinsic) const { 4647 SDLoc DL(M); 4648 4649 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4650 EVT LoadVT = M->getValueType(0); 4651 4652 EVT EquivLoadVT = LoadVT; 4653 if (LoadVT.isVector()) { 4654 if (Unpacked) { 4655 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4656 LoadVT.getVectorNumElements()); 4657 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4658 // Widen v3f16 to legal type 4659 EquivLoadVT = 4660 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4661 LoadVT.getVectorNumElements() + 1); 4662 } 4663 } 4664 4665 // Change from v4f16/v2f16 to EquivLoadVT. 4666 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4667 4668 SDValue Load 4669 = DAG.getMemIntrinsicNode( 4670 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4671 VTList, Ops, M->getMemoryVT(), 4672 M->getMemOperand()); 4673 4674 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4675 4676 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4677 } 4678 4679 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4680 SelectionDAG &DAG, 4681 ArrayRef<SDValue> Ops) const { 4682 SDLoc DL(M); 4683 EVT LoadVT = M->getValueType(0); 4684 EVT EltType = LoadVT.getScalarType(); 4685 EVT IntVT = LoadVT.changeTypeToInteger(); 4686 4687 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4688 4689 unsigned Opc = 4690 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4691 4692 if (IsD16) { 4693 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4694 } 4695 4696 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4697 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4698 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4699 4700 if (isTypeLegal(LoadVT)) { 4701 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4702 M->getMemOperand(), DAG); 4703 } 4704 4705 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4706 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4707 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4708 M->getMemOperand(), DAG); 4709 return DAG.getMergeValues( 4710 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4711 DL); 4712 } 4713 4714 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4715 SDNode *N, SelectionDAG &DAG) { 4716 EVT VT = N->getValueType(0); 4717 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4718 unsigned CondCode = CD->getZExtValue(); 4719 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4720 return DAG.getUNDEF(VT); 4721 4722 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4723 4724 SDValue LHS = N->getOperand(1); 4725 SDValue RHS = N->getOperand(2); 4726 4727 SDLoc DL(N); 4728 4729 EVT CmpVT = LHS.getValueType(); 4730 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4731 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4732 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4733 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4734 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4735 } 4736 4737 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4738 4739 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4740 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4741 4742 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4743 DAG.getCondCode(CCOpcode)); 4744 if (VT.bitsEq(CCVT)) 4745 return SetCC; 4746 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4747 } 4748 4749 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4750 SDNode *N, SelectionDAG &DAG) { 4751 EVT VT = N->getValueType(0); 4752 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4753 4754 unsigned CondCode = CD->getZExtValue(); 4755 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4756 return DAG.getUNDEF(VT); 4757 4758 SDValue Src0 = N->getOperand(1); 4759 SDValue Src1 = N->getOperand(2); 4760 EVT CmpVT = Src0.getValueType(); 4761 SDLoc SL(N); 4762 4763 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4764 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4765 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4766 } 4767 4768 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4769 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4770 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4771 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4772 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4773 Src1, DAG.getCondCode(CCOpcode)); 4774 if (VT.bitsEq(CCVT)) 4775 return SetCC; 4776 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4777 } 4778 4779 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4780 SelectionDAG &DAG) { 4781 EVT VT = N->getValueType(0); 4782 SDValue Src = N->getOperand(1); 4783 SDLoc SL(N); 4784 4785 if (Src.getOpcode() == ISD::SETCC) { 4786 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4787 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4788 Src.getOperand(1), Src.getOperand(2)); 4789 } 4790 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4791 // (ballot 0) -> 0 4792 if (Arg->isNullValue()) 4793 return DAG.getConstant(0, SL, VT); 4794 4795 // (ballot 1) -> EXEC/EXEC_LO 4796 if (Arg->isOne()) { 4797 Register Exec; 4798 if (VT.getScalarSizeInBits() == 32) 4799 Exec = AMDGPU::EXEC_LO; 4800 else if (VT.getScalarSizeInBits() == 64) 4801 Exec = AMDGPU::EXEC; 4802 else 4803 return SDValue(); 4804 4805 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4806 } 4807 } 4808 4809 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4810 // ISD::SETNE) 4811 return DAG.getNode( 4812 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4813 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4814 } 4815 4816 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4817 SmallVectorImpl<SDValue> &Results, 4818 SelectionDAG &DAG) const { 4819 switch (N->getOpcode()) { 4820 case ISD::INSERT_VECTOR_ELT: { 4821 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4822 Results.push_back(Res); 4823 return; 4824 } 4825 case ISD::EXTRACT_VECTOR_ELT: { 4826 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4827 Results.push_back(Res); 4828 return; 4829 } 4830 case ISD::INTRINSIC_WO_CHAIN: { 4831 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4832 switch (IID) { 4833 case Intrinsic::amdgcn_cvt_pkrtz: { 4834 SDValue Src0 = N->getOperand(1); 4835 SDValue Src1 = N->getOperand(2); 4836 SDLoc SL(N); 4837 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4838 Src0, Src1); 4839 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4840 return; 4841 } 4842 case Intrinsic::amdgcn_cvt_pknorm_i16: 4843 case Intrinsic::amdgcn_cvt_pknorm_u16: 4844 case Intrinsic::amdgcn_cvt_pk_i16: 4845 case Intrinsic::amdgcn_cvt_pk_u16: { 4846 SDValue Src0 = N->getOperand(1); 4847 SDValue Src1 = N->getOperand(2); 4848 SDLoc SL(N); 4849 unsigned Opcode; 4850 4851 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4852 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4853 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4854 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4855 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4856 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4857 else 4858 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4859 4860 EVT VT = N->getValueType(0); 4861 if (isTypeLegal(VT)) 4862 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4863 else { 4864 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4865 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4866 } 4867 return; 4868 } 4869 } 4870 break; 4871 } 4872 case ISD::INTRINSIC_W_CHAIN: { 4873 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4874 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4875 // FIXME: Hacky 4876 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4877 Results.push_back(Res.getOperand(I)); 4878 } 4879 } else { 4880 Results.push_back(Res); 4881 Results.push_back(Res.getValue(1)); 4882 } 4883 return; 4884 } 4885 4886 break; 4887 } 4888 case ISD::SELECT: { 4889 SDLoc SL(N); 4890 EVT VT = N->getValueType(0); 4891 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4892 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4893 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4894 4895 EVT SelectVT = NewVT; 4896 if (NewVT.bitsLT(MVT::i32)) { 4897 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4898 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4899 SelectVT = MVT::i32; 4900 } 4901 4902 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4903 N->getOperand(0), LHS, RHS); 4904 4905 if (NewVT != SelectVT) 4906 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4907 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4908 return; 4909 } 4910 case ISD::FNEG: { 4911 if (N->getValueType(0) != MVT::v2f16) 4912 break; 4913 4914 SDLoc SL(N); 4915 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4916 4917 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4918 BC, 4919 DAG.getConstant(0x80008000, SL, MVT::i32)); 4920 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4921 return; 4922 } 4923 case ISD::FABS: { 4924 if (N->getValueType(0) != MVT::v2f16) 4925 break; 4926 4927 SDLoc SL(N); 4928 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4929 4930 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4931 BC, 4932 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4933 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4934 return; 4935 } 4936 default: 4937 break; 4938 } 4939 } 4940 4941 /// Helper function for LowerBRCOND 4942 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4943 4944 SDNode *Parent = Value.getNode(); 4945 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4946 I != E; ++I) { 4947 4948 if (I.getUse().get() != Value) 4949 continue; 4950 4951 if (I->getOpcode() == Opcode) 4952 return *I; 4953 } 4954 return nullptr; 4955 } 4956 4957 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4958 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4959 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4960 case Intrinsic::amdgcn_if: 4961 return AMDGPUISD::IF; 4962 case Intrinsic::amdgcn_else: 4963 return AMDGPUISD::ELSE; 4964 case Intrinsic::amdgcn_loop: 4965 return AMDGPUISD::LOOP; 4966 case Intrinsic::amdgcn_end_cf: 4967 llvm_unreachable("should not occur"); 4968 default: 4969 return 0; 4970 } 4971 } 4972 4973 // break, if_break, else_break are all only used as inputs to loop, not 4974 // directly as branch conditions. 4975 return 0; 4976 } 4977 4978 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4979 const Triple &TT = getTargetMachine().getTargetTriple(); 4980 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4981 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4982 AMDGPU::shouldEmitConstantsToTextSection(TT); 4983 } 4984 4985 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4986 // FIXME: Either avoid relying on address space here or change the default 4987 // address space for functions to avoid the explicit check. 4988 return (GV->getValueType()->isFunctionTy() || 4989 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4990 !shouldEmitFixup(GV) && 4991 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4992 } 4993 4994 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4995 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4996 } 4997 4998 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4999 if (!GV->hasExternalLinkage()) 5000 return true; 5001 5002 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5003 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5004 } 5005 5006 /// This transforms the control flow intrinsics to get the branch destination as 5007 /// last parameter, also switches branch target with BR if the need arise 5008 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5009 SelectionDAG &DAG) const { 5010 SDLoc DL(BRCOND); 5011 5012 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5013 SDValue Target = BRCOND.getOperand(2); 5014 SDNode *BR = nullptr; 5015 SDNode *SetCC = nullptr; 5016 5017 if (Intr->getOpcode() == ISD::SETCC) { 5018 // As long as we negate the condition everything is fine 5019 SetCC = Intr; 5020 Intr = SetCC->getOperand(0).getNode(); 5021 5022 } else { 5023 // Get the target from BR if we don't negate the condition 5024 BR = findUser(BRCOND, ISD::BR); 5025 assert(BR && "brcond missing unconditional branch user"); 5026 Target = BR->getOperand(1); 5027 } 5028 5029 unsigned CFNode = isCFIntrinsic(Intr); 5030 if (CFNode == 0) { 5031 // This is a uniform branch so we don't need to legalize. 5032 return BRCOND; 5033 } 5034 5035 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5036 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5037 5038 assert(!SetCC || 5039 (SetCC->getConstantOperandVal(1) == 1 && 5040 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5041 ISD::SETNE)); 5042 5043 // operands of the new intrinsic call 5044 SmallVector<SDValue, 4> Ops; 5045 if (HaveChain) 5046 Ops.push_back(BRCOND.getOperand(0)); 5047 5048 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5049 Ops.push_back(Target); 5050 5051 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5052 5053 // build the new intrinsic call 5054 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5055 5056 if (!HaveChain) { 5057 SDValue Ops[] = { 5058 SDValue(Result, 0), 5059 BRCOND.getOperand(0) 5060 }; 5061 5062 Result = DAG.getMergeValues(Ops, DL).getNode(); 5063 } 5064 5065 if (BR) { 5066 // Give the branch instruction our target 5067 SDValue Ops[] = { 5068 BR->getOperand(0), 5069 BRCOND.getOperand(2) 5070 }; 5071 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5072 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5073 } 5074 5075 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5076 5077 // Copy the intrinsic results to registers 5078 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5079 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5080 if (!CopyToReg) 5081 continue; 5082 5083 Chain = DAG.getCopyToReg( 5084 Chain, DL, 5085 CopyToReg->getOperand(1), 5086 SDValue(Result, i - 1), 5087 SDValue()); 5088 5089 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5090 } 5091 5092 // Remove the old intrinsic from the chain 5093 DAG.ReplaceAllUsesOfValueWith( 5094 SDValue(Intr, Intr->getNumValues() - 1), 5095 Intr->getOperand(0)); 5096 5097 return Chain; 5098 } 5099 5100 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5101 SelectionDAG &DAG) const { 5102 MVT VT = Op.getSimpleValueType(); 5103 SDLoc DL(Op); 5104 // Checking the depth 5105 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5106 return DAG.getConstant(0, DL, VT); 5107 5108 MachineFunction &MF = DAG.getMachineFunction(); 5109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5110 // Check for kernel and shader functions 5111 if (Info->isEntryFunction()) 5112 return DAG.getConstant(0, DL, VT); 5113 5114 MachineFrameInfo &MFI = MF.getFrameInfo(); 5115 // There is a call to @llvm.returnaddress in this function 5116 MFI.setReturnAddressIsTaken(true); 5117 5118 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5119 // Get the return address reg and mark it as an implicit live-in 5120 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5121 5122 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5123 } 5124 5125 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5126 SDValue Op, 5127 const SDLoc &DL, 5128 EVT VT) const { 5129 return Op.getValueType().bitsLE(VT) ? 5130 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5131 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5132 DAG.getTargetConstant(0, DL, MVT::i32)); 5133 } 5134 5135 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5136 assert(Op.getValueType() == MVT::f16 && 5137 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5138 5139 SDValue Src = Op.getOperand(0); 5140 EVT SrcVT = Src.getValueType(); 5141 if (SrcVT != MVT::f64) 5142 return Op; 5143 5144 SDLoc DL(Op); 5145 5146 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5147 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5148 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5149 } 5150 5151 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5152 SelectionDAG &DAG) const { 5153 EVT VT = Op.getValueType(); 5154 const MachineFunction &MF = DAG.getMachineFunction(); 5155 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5156 bool IsIEEEMode = Info->getMode().IEEE; 5157 5158 // FIXME: Assert during selection that this is only selected for 5159 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5160 // mode functions, but this happens to be OK since it's only done in cases 5161 // where there is known no sNaN. 5162 if (IsIEEEMode) 5163 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5164 5165 if (VT == MVT::v4f16) 5166 return splitBinaryVectorOp(Op, DAG); 5167 return Op; 5168 } 5169 5170 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5171 EVT VT = Op.getValueType(); 5172 SDLoc SL(Op); 5173 SDValue LHS = Op.getOperand(0); 5174 SDValue RHS = Op.getOperand(1); 5175 bool isSigned = Op.getOpcode() == ISD::SMULO; 5176 5177 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5178 const APInt &C = RHSC->getAPIntValue(); 5179 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5180 if (C.isPowerOf2()) { 5181 // smulo(x, signed_min) is same as umulo(x, signed_min). 5182 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5183 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5184 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5185 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5186 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5187 SL, VT, Result, ShiftAmt), 5188 LHS, ISD::SETNE); 5189 return DAG.getMergeValues({ Result, Overflow }, SL); 5190 } 5191 } 5192 5193 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5194 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5195 SL, VT, LHS, RHS); 5196 5197 SDValue Sign = isSigned 5198 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5199 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5200 : DAG.getConstant(0, SL, VT); 5201 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5202 5203 return DAG.getMergeValues({ Result, Overflow }, SL); 5204 } 5205 5206 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5207 SDLoc SL(Op); 5208 SDValue Chain = Op.getOperand(0); 5209 5210 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5211 !Subtarget->isTrapHandlerEnabled()) 5212 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5213 5214 MachineFunction &MF = DAG.getMachineFunction(); 5215 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5216 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5217 assert(UserSGPR != AMDGPU::NoRegister); 5218 SDValue QueuePtr = CreateLiveInRegister( 5219 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5220 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5221 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5222 QueuePtr, SDValue()); 5223 SDValue Ops[] = { 5224 ToReg, 5225 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5226 SGPR01, 5227 ToReg.getValue(1) 5228 }; 5229 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5230 } 5231 5232 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5233 SDLoc SL(Op); 5234 SDValue Chain = Op.getOperand(0); 5235 MachineFunction &MF = DAG.getMachineFunction(); 5236 5237 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5238 !Subtarget->isTrapHandlerEnabled()) { 5239 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5240 "debugtrap handler not supported", 5241 Op.getDebugLoc(), 5242 DS_Warning); 5243 LLVMContext &Ctx = MF.getFunction().getContext(); 5244 Ctx.diagnose(NoTrap); 5245 return Chain; 5246 } 5247 5248 SDValue Ops[] = { 5249 Chain, 5250 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5251 }; 5252 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5253 } 5254 5255 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5256 SelectionDAG &DAG) const { 5257 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5258 if (Subtarget->hasApertureRegs()) { 5259 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5260 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5261 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5262 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5263 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5264 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5265 unsigned Encoding = 5266 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5267 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5268 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5269 5270 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5271 SDValue ApertureReg = SDValue( 5272 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5273 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5274 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5275 } 5276 5277 MachineFunction &MF = DAG.getMachineFunction(); 5278 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5279 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5280 assert(UserSGPR != AMDGPU::NoRegister); 5281 5282 SDValue QueuePtr = CreateLiveInRegister( 5283 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5284 5285 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5286 // private_segment_aperture_base_hi. 5287 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5288 5289 SDValue Ptr = 5290 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5291 5292 // TODO: Use custom target PseudoSourceValue. 5293 // TODO: We should use the value from the IR intrinsic call, but it might not 5294 // be available and how do we get it? 5295 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5296 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5297 commonAlignment(Align(64), StructOffset), 5298 MachineMemOperand::MODereferenceable | 5299 MachineMemOperand::MOInvariant); 5300 } 5301 5302 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5303 SelectionDAG &DAG) const { 5304 SDLoc SL(Op); 5305 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5306 5307 SDValue Src = ASC->getOperand(0); 5308 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5309 5310 const AMDGPUTargetMachine &TM = 5311 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5312 5313 // flat -> local/private 5314 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5315 unsigned DestAS = ASC->getDestAddressSpace(); 5316 5317 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5318 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5319 unsigned NullVal = TM.getNullPointerValue(DestAS); 5320 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5321 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5322 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5323 5324 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5325 NonNull, Ptr, SegmentNullPtr); 5326 } 5327 } 5328 5329 // local/private -> flat 5330 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5331 unsigned SrcAS = ASC->getSrcAddressSpace(); 5332 5333 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5334 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5335 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5336 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5337 5338 SDValue NonNull 5339 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5340 5341 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5342 SDValue CvtPtr 5343 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5344 5345 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5346 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5347 FlatNullPtr); 5348 } 5349 } 5350 5351 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5352 Src.getValueType() == MVT::i64) 5353 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5354 5355 // global <-> flat are no-ops and never emitted. 5356 5357 const MachineFunction &MF = DAG.getMachineFunction(); 5358 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5359 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5360 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5361 5362 return DAG.getUNDEF(ASC->getValueType(0)); 5363 } 5364 5365 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5366 // the small vector and inserting them into the big vector. That is better than 5367 // the default expansion of doing it via a stack slot. Even though the use of 5368 // the stack slot would be optimized away afterwards, the stack slot itself 5369 // remains. 5370 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5371 SelectionDAG &DAG) const { 5372 SDValue Vec = Op.getOperand(0); 5373 SDValue Ins = Op.getOperand(1); 5374 SDValue Idx = Op.getOperand(2); 5375 EVT VecVT = Vec.getValueType(); 5376 EVT InsVT = Ins.getValueType(); 5377 EVT EltVT = VecVT.getVectorElementType(); 5378 unsigned InsNumElts = InsVT.getVectorNumElements(); 5379 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5380 SDLoc SL(Op); 5381 5382 for (unsigned I = 0; I != InsNumElts; ++I) { 5383 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5384 DAG.getConstant(I, SL, MVT::i32)); 5385 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5386 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5387 } 5388 return Vec; 5389 } 5390 5391 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5392 SelectionDAG &DAG) const { 5393 SDValue Vec = Op.getOperand(0); 5394 SDValue InsVal = Op.getOperand(1); 5395 SDValue Idx = Op.getOperand(2); 5396 EVT VecVT = Vec.getValueType(); 5397 EVT EltVT = VecVT.getVectorElementType(); 5398 unsigned VecSize = VecVT.getSizeInBits(); 5399 unsigned EltSize = EltVT.getSizeInBits(); 5400 5401 5402 assert(VecSize <= 64); 5403 5404 unsigned NumElts = VecVT.getVectorNumElements(); 5405 SDLoc SL(Op); 5406 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5407 5408 if (NumElts == 4 && EltSize == 16 && KIdx) { 5409 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5410 5411 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5412 DAG.getConstant(0, SL, MVT::i32)); 5413 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5414 DAG.getConstant(1, SL, MVT::i32)); 5415 5416 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5417 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5418 5419 unsigned Idx = KIdx->getZExtValue(); 5420 bool InsertLo = Idx < 2; 5421 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5422 InsertLo ? LoVec : HiVec, 5423 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5424 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5425 5426 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5427 5428 SDValue Concat = InsertLo ? 5429 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5430 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5431 5432 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5433 } 5434 5435 if (isa<ConstantSDNode>(Idx)) 5436 return SDValue(); 5437 5438 MVT IntVT = MVT::getIntegerVT(VecSize); 5439 5440 // Avoid stack access for dynamic indexing. 5441 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5442 5443 // Create a congruent vector with the target value in each element so that 5444 // the required element can be masked and ORed into the target vector. 5445 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5446 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5447 5448 assert(isPowerOf2_32(EltSize)); 5449 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5450 5451 // Convert vector index to bit-index. 5452 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5453 5454 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5455 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5456 DAG.getConstant(0xffff, SL, IntVT), 5457 ScaledIdx); 5458 5459 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5460 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5461 DAG.getNOT(SL, BFM, IntVT), BCVec); 5462 5463 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5464 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5465 } 5466 5467 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5468 SelectionDAG &DAG) const { 5469 SDLoc SL(Op); 5470 5471 EVT ResultVT = Op.getValueType(); 5472 SDValue Vec = Op.getOperand(0); 5473 SDValue Idx = Op.getOperand(1); 5474 EVT VecVT = Vec.getValueType(); 5475 unsigned VecSize = VecVT.getSizeInBits(); 5476 EVT EltVT = VecVT.getVectorElementType(); 5477 assert(VecSize <= 64); 5478 5479 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5480 5481 // Make sure we do any optimizations that will make it easier to fold 5482 // source modifiers before obscuring it with bit operations. 5483 5484 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5485 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5486 return Combined; 5487 5488 unsigned EltSize = EltVT.getSizeInBits(); 5489 assert(isPowerOf2_32(EltSize)); 5490 5491 MVT IntVT = MVT::getIntegerVT(VecSize); 5492 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5493 5494 // Convert vector index to bit-index (* EltSize) 5495 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5496 5497 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5498 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5499 5500 if (ResultVT == MVT::f16) { 5501 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5502 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5503 } 5504 5505 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5506 } 5507 5508 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5509 assert(Elt % 2 == 0); 5510 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5511 } 5512 5513 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5514 SelectionDAG &DAG) const { 5515 SDLoc SL(Op); 5516 EVT ResultVT = Op.getValueType(); 5517 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5518 5519 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5520 EVT EltVT = PackVT.getVectorElementType(); 5521 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5522 5523 // vector_shuffle <0,1,6,7> lhs, rhs 5524 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5525 // 5526 // vector_shuffle <6,7,2,3> lhs, rhs 5527 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5528 // 5529 // vector_shuffle <6,7,0,1> lhs, rhs 5530 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5531 5532 // Avoid scalarizing when both halves are reading from consecutive elements. 5533 SmallVector<SDValue, 4> Pieces; 5534 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5535 if (elementPairIsContiguous(SVN->getMask(), I)) { 5536 const int Idx = SVN->getMaskElt(I); 5537 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5538 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5539 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5540 PackVT, SVN->getOperand(VecIdx), 5541 DAG.getConstant(EltIdx, SL, MVT::i32)); 5542 Pieces.push_back(SubVec); 5543 } else { 5544 const int Idx0 = SVN->getMaskElt(I); 5545 const int Idx1 = SVN->getMaskElt(I + 1); 5546 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5547 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5548 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5549 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5550 5551 SDValue Vec0 = SVN->getOperand(VecIdx0); 5552 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5553 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5554 5555 SDValue Vec1 = SVN->getOperand(VecIdx1); 5556 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5557 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5558 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5559 } 5560 } 5561 5562 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5563 } 5564 5565 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5566 SelectionDAG &DAG) const { 5567 SDLoc SL(Op); 5568 EVT VT = Op.getValueType(); 5569 5570 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5571 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5572 5573 // Turn into pair of packed build_vectors. 5574 // TODO: Special case for constants that can be materialized with s_mov_b64. 5575 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5576 { Op.getOperand(0), Op.getOperand(1) }); 5577 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5578 { Op.getOperand(2), Op.getOperand(3) }); 5579 5580 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5581 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5582 5583 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5584 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5585 } 5586 5587 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5588 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5589 5590 SDValue Lo = Op.getOperand(0); 5591 SDValue Hi = Op.getOperand(1); 5592 5593 // Avoid adding defined bits with the zero_extend. 5594 if (Hi.isUndef()) { 5595 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5596 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5597 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5598 } 5599 5600 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5601 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5602 5603 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5604 DAG.getConstant(16, SL, MVT::i32)); 5605 if (Lo.isUndef()) 5606 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5607 5608 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5609 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5610 5611 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5612 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5613 } 5614 5615 bool 5616 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5617 // We can fold offsets for anything that doesn't require a GOT relocation. 5618 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5619 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5620 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5621 !shouldEmitGOTReloc(GA->getGlobal()); 5622 } 5623 5624 static SDValue 5625 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5626 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5627 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5628 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5629 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5630 // lowered to the following code sequence: 5631 // 5632 // For constant address space: 5633 // s_getpc_b64 s[0:1] 5634 // s_add_u32 s0, s0, $symbol 5635 // s_addc_u32 s1, s1, 0 5636 // 5637 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5638 // a fixup or relocation is emitted to replace $symbol with a literal 5639 // constant, which is a pc-relative offset from the encoding of the $symbol 5640 // operand to the global variable. 5641 // 5642 // For global address space: 5643 // s_getpc_b64 s[0:1] 5644 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5645 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5646 // 5647 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5648 // fixups or relocations are emitted to replace $symbol@*@lo and 5649 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5650 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5651 // operand to the global variable. 5652 // 5653 // What we want here is an offset from the value returned by s_getpc 5654 // (which is the address of the s_add_u32 instruction) to the global 5655 // variable, but since the encoding of $symbol starts 4 bytes after the start 5656 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5657 // small. This requires us to add 4 to the global variable offset in order to 5658 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5659 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5660 // instruction. 5661 SDValue PtrLo = 5662 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5663 SDValue PtrHi; 5664 if (GAFlags == SIInstrInfo::MO_NONE) { 5665 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5666 } else { 5667 PtrHi = 5668 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5669 } 5670 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5671 } 5672 5673 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5674 SDValue Op, 5675 SelectionDAG &DAG) const { 5676 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5677 SDLoc DL(GSD); 5678 EVT PtrVT = Op.getValueType(); 5679 5680 const GlobalValue *GV = GSD->getGlobal(); 5681 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5682 shouldUseLDSConstAddress(GV)) || 5683 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5684 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5685 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5686 GV->hasExternalLinkage()) { 5687 Type *Ty = GV->getValueType(); 5688 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5689 // zero-sized type in other languages to declare the dynamic shared 5690 // memory which size is not known at the compile time. They will be 5691 // allocated by the runtime and placed directly after the static 5692 // allocated ones. They all share the same offset. 5693 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5694 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5695 // Adjust alignment for that dynamic shared memory array. 5696 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5697 return SDValue( 5698 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5699 } 5700 } 5701 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5702 } 5703 5704 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5705 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5706 SIInstrInfo::MO_ABS32_LO); 5707 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5708 } 5709 5710 if (shouldEmitFixup(GV)) 5711 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5712 else if (shouldEmitPCReloc(GV)) 5713 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5714 SIInstrInfo::MO_REL32); 5715 5716 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5717 SIInstrInfo::MO_GOTPCREL32); 5718 5719 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5720 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5721 const DataLayout &DataLayout = DAG.getDataLayout(); 5722 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5723 MachinePointerInfo PtrInfo 5724 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5725 5726 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5727 MachineMemOperand::MODereferenceable | 5728 MachineMemOperand::MOInvariant); 5729 } 5730 5731 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5732 const SDLoc &DL, SDValue V) const { 5733 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5734 // the destination register. 5735 // 5736 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5737 // so we will end up with redundant moves to m0. 5738 // 5739 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5740 5741 // A Null SDValue creates a glue result. 5742 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5743 V, Chain); 5744 return SDValue(M0, 0); 5745 } 5746 5747 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5748 SDValue Op, 5749 MVT VT, 5750 unsigned Offset) const { 5751 SDLoc SL(Op); 5752 SDValue Param = lowerKernargMemParameter( 5753 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5754 // The local size values will have the hi 16-bits as zero. 5755 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5756 DAG.getValueType(VT)); 5757 } 5758 5759 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5760 EVT VT) { 5761 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5762 "non-hsa intrinsic with hsa target", 5763 DL.getDebugLoc()); 5764 DAG.getContext()->diagnose(BadIntrin); 5765 return DAG.getUNDEF(VT); 5766 } 5767 5768 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5769 EVT VT) { 5770 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5771 "intrinsic not supported on subtarget", 5772 DL.getDebugLoc()); 5773 DAG.getContext()->diagnose(BadIntrin); 5774 return DAG.getUNDEF(VT); 5775 } 5776 5777 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5778 ArrayRef<SDValue> Elts) { 5779 assert(!Elts.empty()); 5780 MVT Type; 5781 unsigned NumElts; 5782 5783 if (Elts.size() == 1) { 5784 Type = MVT::f32; 5785 NumElts = 1; 5786 } else if (Elts.size() == 2) { 5787 Type = MVT::v2f32; 5788 NumElts = 2; 5789 } else if (Elts.size() == 3) { 5790 Type = MVT::v3f32; 5791 NumElts = 3; 5792 } else if (Elts.size() <= 4) { 5793 Type = MVT::v4f32; 5794 NumElts = 4; 5795 } else if (Elts.size() <= 8) { 5796 Type = MVT::v8f32; 5797 NumElts = 8; 5798 } else { 5799 assert(Elts.size() <= 16); 5800 Type = MVT::v16f32; 5801 NumElts = 16; 5802 } 5803 5804 SmallVector<SDValue, 16> VecElts(NumElts); 5805 for (unsigned i = 0; i < Elts.size(); ++i) { 5806 SDValue Elt = Elts[i]; 5807 if (Elt.getValueType() != MVT::f32) 5808 Elt = DAG.getBitcast(MVT::f32, Elt); 5809 VecElts[i] = Elt; 5810 } 5811 for (unsigned i = Elts.size(); i < NumElts; ++i) 5812 VecElts[i] = DAG.getUNDEF(MVT::f32); 5813 5814 if (NumElts == 1) 5815 return VecElts[0]; 5816 return DAG.getBuildVector(Type, DL, VecElts); 5817 } 5818 5819 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5820 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5821 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5822 5823 uint64_t Value = CachePolicyConst->getZExtValue(); 5824 SDLoc DL(CachePolicy); 5825 if (GLC) { 5826 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5827 Value &= ~(uint64_t)0x1; 5828 } 5829 if (SLC) { 5830 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5831 Value &= ~(uint64_t)0x2; 5832 } 5833 if (DLC) { 5834 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5835 Value &= ~(uint64_t)0x4; 5836 } 5837 5838 return Value == 0; 5839 } 5840 5841 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5842 SDValue Src, int ExtraElts) { 5843 EVT SrcVT = Src.getValueType(); 5844 5845 SmallVector<SDValue, 8> Elts; 5846 5847 if (SrcVT.isVector()) 5848 DAG.ExtractVectorElements(Src, Elts); 5849 else 5850 Elts.push_back(Src); 5851 5852 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5853 while (ExtraElts--) 5854 Elts.push_back(Undef); 5855 5856 return DAG.getBuildVector(CastVT, DL, Elts); 5857 } 5858 5859 // Re-construct the required return value for a image load intrinsic. 5860 // This is more complicated due to the optional use TexFailCtrl which means the required 5861 // return type is an aggregate 5862 static SDValue constructRetValue(SelectionDAG &DAG, 5863 MachineSDNode *Result, 5864 ArrayRef<EVT> ResultTypes, 5865 bool IsTexFail, bool Unpacked, bool IsD16, 5866 int DMaskPop, int NumVDataDwords, 5867 const SDLoc &DL, LLVMContext &Context) { 5868 // Determine the required return type. This is the same regardless of IsTexFail flag 5869 EVT ReqRetVT = ResultTypes[0]; 5870 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5871 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5872 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5873 5874 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5875 DMaskPop : (DMaskPop + 1) / 2; 5876 5877 MVT DataDwordVT = NumDataDwords == 1 ? 5878 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5879 5880 MVT MaskPopVT = MaskPopDwords == 1 ? 5881 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5882 5883 SDValue Data(Result, 0); 5884 SDValue TexFail; 5885 5886 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5887 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5888 if (MaskPopVT.isVector()) { 5889 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5890 SDValue(Result, 0), ZeroIdx); 5891 } else { 5892 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5893 SDValue(Result, 0), ZeroIdx); 5894 } 5895 } 5896 5897 if (DataDwordVT.isVector()) 5898 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5899 NumDataDwords - MaskPopDwords); 5900 5901 if (IsD16) 5902 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5903 5904 EVT LegalReqRetVT = ReqRetVT; 5905 if (!ReqRetVT.isVector()) { 5906 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5907 } else { 5908 // We need to widen the return vector to a legal type 5909 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5910 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5911 LegalReqRetVT = 5912 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5913 ReqRetVT.getVectorNumElements() + 1); 5914 } 5915 } 5916 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5917 5918 if (IsTexFail) { 5919 TexFail = 5920 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5921 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5922 5923 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5924 } 5925 5926 if (Result->getNumValues() == 1) 5927 return Data; 5928 5929 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5930 } 5931 5932 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5933 SDValue *LWE, bool &IsTexFail) { 5934 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5935 5936 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5937 if (Value) { 5938 IsTexFail = true; 5939 } 5940 5941 SDLoc DL(TexFailCtrlConst); 5942 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5943 Value &= ~(uint64_t)0x1; 5944 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5945 Value &= ~(uint64_t)0x2; 5946 5947 return Value == 0; 5948 } 5949 5950 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5951 MVT PackVectorVT, 5952 SmallVectorImpl<SDValue> &PackedAddrs, 5953 unsigned DimIdx, unsigned EndIdx, 5954 unsigned NumGradients) { 5955 SDLoc DL(Op); 5956 for (unsigned I = DimIdx; I < EndIdx; I++) { 5957 SDValue Addr = Op.getOperand(I); 5958 5959 // Gradients are packed with undef for each coordinate. 5960 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5961 // 1D: undef,dx/dh; undef,dx/dv 5962 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5963 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5964 if (((I + 1) >= EndIdx) || 5965 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5966 I == DimIdx + NumGradients - 1))) { 5967 if (Addr.getValueType() != MVT::i16) 5968 Addr = DAG.getBitcast(MVT::i16, Addr); 5969 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5970 } else { 5971 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5972 I++; 5973 } 5974 Addr = DAG.getBitcast(MVT::f32, Addr); 5975 PackedAddrs.push_back(Addr); 5976 } 5977 } 5978 5979 SDValue SITargetLowering::lowerImage(SDValue Op, 5980 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5981 SelectionDAG &DAG, bool WithChain) const { 5982 SDLoc DL(Op); 5983 MachineFunction &MF = DAG.getMachineFunction(); 5984 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5985 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5986 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5987 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5988 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5989 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5990 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5991 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5992 unsigned IntrOpcode = Intr->BaseOpcode; 5993 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5994 5995 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5996 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5997 bool IsD16 = false; 5998 bool IsG16 = false; 5999 bool IsA16 = false; 6000 SDValue VData; 6001 int NumVDataDwords; 6002 bool AdjustRetType = false; 6003 6004 // Offset of intrinsic arguments 6005 const unsigned ArgOffset = WithChain ? 2 : 1; 6006 6007 unsigned DMask; 6008 unsigned DMaskLanes = 0; 6009 6010 if (BaseOpcode->Atomic) { 6011 VData = Op.getOperand(2); 6012 6013 bool Is64Bit = VData.getValueType() == MVT::i64; 6014 if (BaseOpcode->AtomicX2) { 6015 SDValue VData2 = Op.getOperand(3); 6016 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6017 {VData, VData2}); 6018 if (Is64Bit) 6019 VData = DAG.getBitcast(MVT::v4i32, VData); 6020 6021 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6022 DMask = Is64Bit ? 0xf : 0x3; 6023 NumVDataDwords = Is64Bit ? 4 : 2; 6024 } else { 6025 DMask = Is64Bit ? 0x3 : 0x1; 6026 NumVDataDwords = Is64Bit ? 2 : 1; 6027 } 6028 } else { 6029 auto *DMaskConst = 6030 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6031 DMask = DMaskConst->getZExtValue(); 6032 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6033 6034 if (BaseOpcode->Store) { 6035 VData = Op.getOperand(2); 6036 6037 MVT StoreVT = VData.getSimpleValueType(); 6038 if (StoreVT.getScalarType() == MVT::f16) { 6039 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6040 return Op; // D16 is unsupported for this instruction 6041 6042 IsD16 = true; 6043 VData = handleD16VData(VData, DAG, true); 6044 } 6045 6046 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6047 } else { 6048 // Work out the num dwords based on the dmask popcount and underlying type 6049 // and whether packing is supported. 6050 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6051 if (LoadVT.getScalarType() == MVT::f16) { 6052 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6053 return Op; // D16 is unsupported for this instruction 6054 6055 IsD16 = true; 6056 } 6057 6058 // Confirm that the return type is large enough for the dmask specified 6059 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6060 (!LoadVT.isVector() && DMaskLanes > 1)) 6061 return Op; 6062 6063 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6064 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6065 // instructions. 6066 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6067 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6068 NumVDataDwords = (DMaskLanes + 1) / 2; 6069 else 6070 NumVDataDwords = DMaskLanes; 6071 6072 AdjustRetType = true; 6073 } 6074 } 6075 6076 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6077 SmallVector<SDValue, 4> VAddrs; 6078 6079 // Optimize _L to _LZ when _L is zero 6080 if (LZMappingInfo) { 6081 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6082 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6083 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6084 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6085 VAddrEnd--; // remove 'lod' 6086 } 6087 } 6088 } 6089 6090 // Optimize _mip away, when 'lod' is zero 6091 if (MIPMappingInfo) { 6092 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6093 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6094 if (ConstantLod->isNullValue()) { 6095 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6096 VAddrEnd--; // remove 'mip' 6097 } 6098 } 6099 } 6100 6101 // Push back extra arguments. 6102 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6103 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6104 6105 // Check for 16 bit addresses or derivatives and pack if true. 6106 MVT VAddrVT = 6107 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6108 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6109 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6110 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6111 6112 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6113 VAddrScalarVT = VAddrVT.getScalarType(); 6114 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6115 if (IsA16 || IsG16) { 6116 if (IsA16) { 6117 if (!ST->hasA16()) { 6118 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6119 "support 16 bit addresses\n"); 6120 return Op; 6121 } 6122 if (!IsG16) { 6123 LLVM_DEBUG( 6124 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6125 "need 16 bit derivatives but got 32 bit derivatives\n"); 6126 return Op; 6127 } 6128 } else if (!ST->hasG16()) { 6129 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6130 "support 16 bit derivatives\n"); 6131 return Op; 6132 } 6133 6134 if (BaseOpcode->Gradients && !IsA16) { 6135 if (!ST->hasG16()) { 6136 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6137 "support 16 bit derivatives\n"); 6138 return Op; 6139 } 6140 // Activate g16 6141 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6142 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6143 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6144 } 6145 6146 // Don't compress addresses for G16 6147 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6148 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6149 ArgOffset + Intr->GradientStart, PackEndIdx, 6150 Intr->NumGradients); 6151 6152 if (!IsA16) { 6153 // Add uncompressed address 6154 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6155 VAddrs.push_back(Op.getOperand(I)); 6156 } 6157 } else { 6158 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6159 VAddrs.push_back(Op.getOperand(I)); 6160 } 6161 6162 // If the register allocator cannot place the address registers contiguously 6163 // without introducing moves, then using the non-sequential address encoding 6164 // is always preferable, since it saves VALU instructions and is usually a 6165 // wash in terms of code size or even better. 6166 // 6167 // However, we currently have no way of hinting to the register allocator that 6168 // MIMG addresses should be placed contiguously when it is possible to do so, 6169 // so force non-NSA for the common 2-address case as a heuristic. 6170 // 6171 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6172 // allocation when possible. 6173 bool UseNSA = 6174 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6175 SDValue VAddr; 6176 if (!UseNSA) 6177 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6178 6179 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6180 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6181 SDValue Unorm; 6182 if (!BaseOpcode->Sampler) { 6183 Unorm = True; 6184 } else { 6185 auto UnormConst = 6186 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6187 6188 Unorm = UnormConst->getZExtValue() ? True : False; 6189 } 6190 6191 SDValue TFE; 6192 SDValue LWE; 6193 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6194 bool IsTexFail = false; 6195 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6196 return Op; 6197 6198 if (IsTexFail) { 6199 if (!DMaskLanes) { 6200 // Expecting to get an error flag since TFC is on - and dmask is 0 6201 // Force dmask to be at least 1 otherwise the instruction will fail 6202 DMask = 0x1; 6203 DMaskLanes = 1; 6204 NumVDataDwords = 1; 6205 } 6206 NumVDataDwords += 1; 6207 AdjustRetType = true; 6208 } 6209 6210 // Has something earlier tagged that the return type needs adjusting 6211 // This happens if the instruction is a load or has set TexFailCtrl flags 6212 if (AdjustRetType) { 6213 // NumVDataDwords reflects the true number of dwords required in the return type 6214 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6215 // This is a no-op load. This can be eliminated 6216 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6217 if (isa<MemSDNode>(Op)) 6218 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6219 return Undef; 6220 } 6221 6222 EVT NewVT = NumVDataDwords > 1 ? 6223 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6224 : MVT::i32; 6225 6226 ResultTypes[0] = NewVT; 6227 if (ResultTypes.size() == 3) { 6228 // Original result was aggregate type used for TexFailCtrl results 6229 // The actual instruction returns as a vector type which has now been 6230 // created. Remove the aggregate result. 6231 ResultTypes.erase(&ResultTypes[1]); 6232 } 6233 } 6234 6235 SDValue GLC; 6236 SDValue SLC; 6237 SDValue DLC; 6238 if (BaseOpcode->Atomic) { 6239 GLC = True; // TODO no-return optimization 6240 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6241 DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6242 return Op; 6243 } else { 6244 if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex), 6245 DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr)) 6246 return Op; 6247 } 6248 6249 SmallVector<SDValue, 26> Ops; 6250 if (BaseOpcode->Store || BaseOpcode->Atomic) 6251 Ops.push_back(VData); // vdata 6252 if (UseNSA) { 6253 for (const SDValue &Addr : VAddrs) 6254 Ops.push_back(Addr); 6255 } else { 6256 Ops.push_back(VAddr); 6257 } 6258 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6259 if (BaseOpcode->Sampler) 6260 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6261 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6262 if (IsGFX10Plus) 6263 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6264 Ops.push_back(Unorm); 6265 if (IsGFX10Plus) 6266 Ops.push_back(DLC); 6267 Ops.push_back(GLC); 6268 Ops.push_back(SLC); 6269 Ops.push_back(IsA16 && // r128, a16 for gfx9 6270 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6271 if (IsGFX10Plus) 6272 Ops.push_back(IsA16 ? True : False); 6273 Ops.push_back(TFE); 6274 Ops.push_back(LWE); 6275 if (!IsGFX10Plus) 6276 Ops.push_back(DimInfo->DA ? True : False); 6277 if (BaseOpcode->HasD16) 6278 Ops.push_back(IsD16 ? True : False); 6279 if (isa<MemSDNode>(Op)) 6280 Ops.push_back(Op.getOperand(0)); // chain 6281 6282 int NumVAddrDwords = 6283 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6284 int Opcode = -1; 6285 6286 if (IsGFX10Plus) { 6287 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6288 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6289 : AMDGPU::MIMGEncGfx10Default, 6290 NumVDataDwords, NumVAddrDwords); 6291 } else { 6292 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6293 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6294 NumVDataDwords, NumVAddrDwords); 6295 if (Opcode == -1) 6296 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6297 NumVDataDwords, NumVAddrDwords); 6298 } 6299 assert(Opcode != -1); 6300 6301 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6302 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6303 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6304 DAG.setNodeMemRefs(NewNode, {MemRef}); 6305 } 6306 6307 if (BaseOpcode->AtomicX2) { 6308 SmallVector<SDValue, 1> Elt; 6309 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6310 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6311 } else if (!BaseOpcode->Store) { 6312 return constructRetValue(DAG, NewNode, 6313 OrigResultTypes, IsTexFail, 6314 Subtarget->hasUnpackedD16VMem(), IsD16, 6315 DMaskLanes, NumVDataDwords, DL, 6316 *DAG.getContext()); 6317 } 6318 6319 return SDValue(NewNode, 0); 6320 } 6321 6322 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6323 SDValue Offset, SDValue CachePolicy, 6324 SelectionDAG &DAG) const { 6325 MachineFunction &MF = DAG.getMachineFunction(); 6326 6327 const DataLayout &DataLayout = DAG.getDataLayout(); 6328 Align Alignment = 6329 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6330 6331 MachineMemOperand *MMO = MF.getMachineMemOperand( 6332 MachinePointerInfo(), 6333 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6334 MachineMemOperand::MOInvariant, 6335 VT.getStoreSize(), Alignment); 6336 6337 if (!Offset->isDivergent()) { 6338 SDValue Ops[] = { 6339 Rsrc, 6340 Offset, // Offset 6341 CachePolicy 6342 }; 6343 6344 // Widen vec3 load to vec4. 6345 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6346 EVT WidenedVT = 6347 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6348 auto WidenedOp = DAG.getMemIntrinsicNode( 6349 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6350 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6351 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6352 DAG.getVectorIdxConstant(0, DL)); 6353 return Subvector; 6354 } 6355 6356 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6357 DAG.getVTList(VT), Ops, VT, MMO); 6358 } 6359 6360 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6361 // assume that the buffer is unswizzled. 6362 SmallVector<SDValue, 4> Loads; 6363 unsigned NumLoads = 1; 6364 MVT LoadVT = VT.getSimpleVT(); 6365 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6366 assert((LoadVT.getScalarType() == MVT::i32 || 6367 LoadVT.getScalarType() == MVT::f32)); 6368 6369 if (NumElts == 8 || NumElts == 16) { 6370 NumLoads = NumElts / 4; 6371 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6372 } 6373 6374 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6375 SDValue Ops[] = { 6376 DAG.getEntryNode(), // Chain 6377 Rsrc, // rsrc 6378 DAG.getConstant(0, DL, MVT::i32), // vindex 6379 {}, // voffset 6380 {}, // soffset 6381 {}, // offset 6382 CachePolicy, // cachepolicy 6383 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6384 }; 6385 6386 // Use the alignment to ensure that the required offsets will fit into the 6387 // immediate offsets. 6388 setBufferOffsets(Offset, DAG, &Ops[3], 6389 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6390 6391 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6392 for (unsigned i = 0; i < NumLoads; ++i) { 6393 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6394 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6395 LoadVT, MMO, DAG)); 6396 } 6397 6398 if (NumElts == 8 || NumElts == 16) 6399 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6400 6401 return Loads[0]; 6402 } 6403 6404 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6405 SelectionDAG &DAG) const { 6406 MachineFunction &MF = DAG.getMachineFunction(); 6407 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6408 6409 EVT VT = Op.getValueType(); 6410 SDLoc DL(Op); 6411 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6412 6413 // TODO: Should this propagate fast-math-flags? 6414 6415 switch (IntrinsicID) { 6416 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6417 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6418 return emitNonHSAIntrinsicError(DAG, DL, VT); 6419 return getPreloadedValue(DAG, *MFI, VT, 6420 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6421 } 6422 case Intrinsic::amdgcn_dispatch_ptr: 6423 case Intrinsic::amdgcn_queue_ptr: { 6424 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6425 DiagnosticInfoUnsupported BadIntrin( 6426 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6427 DL.getDebugLoc()); 6428 DAG.getContext()->diagnose(BadIntrin); 6429 return DAG.getUNDEF(VT); 6430 } 6431 6432 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6433 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6434 return getPreloadedValue(DAG, *MFI, VT, RegID); 6435 } 6436 case Intrinsic::amdgcn_implicitarg_ptr: { 6437 if (MFI->isEntryFunction()) 6438 return getImplicitArgPtr(DAG, DL); 6439 return getPreloadedValue(DAG, *MFI, VT, 6440 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6441 } 6442 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6443 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6444 // This only makes sense to call in a kernel, so just lower to null. 6445 return DAG.getConstant(0, DL, VT); 6446 } 6447 6448 return getPreloadedValue(DAG, *MFI, VT, 6449 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6450 } 6451 case Intrinsic::amdgcn_dispatch_id: { 6452 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6453 } 6454 case Intrinsic::amdgcn_rcp: 6455 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6456 case Intrinsic::amdgcn_rsq: 6457 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6458 case Intrinsic::amdgcn_rsq_legacy: 6459 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6460 return emitRemovedIntrinsicError(DAG, DL, VT); 6461 return SDValue(); 6462 case Intrinsic::amdgcn_rcp_legacy: 6463 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6464 return emitRemovedIntrinsicError(DAG, DL, VT); 6465 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6466 case Intrinsic::amdgcn_rsq_clamp: { 6467 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6468 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6469 6470 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6471 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6472 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6473 6474 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6475 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6476 DAG.getConstantFP(Max, DL, VT)); 6477 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6478 DAG.getConstantFP(Min, DL, VT)); 6479 } 6480 case Intrinsic::r600_read_ngroups_x: 6481 if (Subtarget->isAmdHsaOS()) 6482 return emitNonHSAIntrinsicError(DAG, DL, VT); 6483 6484 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6485 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6486 false); 6487 case Intrinsic::r600_read_ngroups_y: 6488 if (Subtarget->isAmdHsaOS()) 6489 return emitNonHSAIntrinsicError(DAG, DL, VT); 6490 6491 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6492 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6493 false); 6494 case Intrinsic::r600_read_ngroups_z: 6495 if (Subtarget->isAmdHsaOS()) 6496 return emitNonHSAIntrinsicError(DAG, DL, VT); 6497 6498 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6499 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6500 false); 6501 case Intrinsic::r600_read_global_size_x: 6502 if (Subtarget->isAmdHsaOS()) 6503 return emitNonHSAIntrinsicError(DAG, DL, VT); 6504 6505 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6506 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6507 Align(4), false); 6508 case Intrinsic::r600_read_global_size_y: 6509 if (Subtarget->isAmdHsaOS()) 6510 return emitNonHSAIntrinsicError(DAG, DL, VT); 6511 6512 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6513 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6514 Align(4), false); 6515 case Intrinsic::r600_read_global_size_z: 6516 if (Subtarget->isAmdHsaOS()) 6517 return emitNonHSAIntrinsicError(DAG, DL, VT); 6518 6519 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6520 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6521 Align(4), false); 6522 case Intrinsic::r600_read_local_size_x: 6523 if (Subtarget->isAmdHsaOS()) 6524 return emitNonHSAIntrinsicError(DAG, DL, VT); 6525 6526 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6527 SI::KernelInputOffsets::LOCAL_SIZE_X); 6528 case Intrinsic::r600_read_local_size_y: 6529 if (Subtarget->isAmdHsaOS()) 6530 return emitNonHSAIntrinsicError(DAG, DL, VT); 6531 6532 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6533 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6534 case Intrinsic::r600_read_local_size_z: 6535 if (Subtarget->isAmdHsaOS()) 6536 return emitNonHSAIntrinsicError(DAG, DL, VT); 6537 6538 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6539 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6540 case Intrinsic::amdgcn_workgroup_id_x: 6541 return getPreloadedValue(DAG, *MFI, VT, 6542 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6543 case Intrinsic::amdgcn_workgroup_id_y: 6544 return getPreloadedValue(DAG, *MFI, VT, 6545 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6546 case Intrinsic::amdgcn_workgroup_id_z: 6547 return getPreloadedValue(DAG, *MFI, VT, 6548 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6549 case Intrinsic::amdgcn_workitem_id_x: 6550 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6551 SDLoc(DAG.getEntryNode()), 6552 MFI->getArgInfo().WorkItemIDX); 6553 case Intrinsic::amdgcn_workitem_id_y: 6554 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6555 SDLoc(DAG.getEntryNode()), 6556 MFI->getArgInfo().WorkItemIDY); 6557 case Intrinsic::amdgcn_workitem_id_z: 6558 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6559 SDLoc(DAG.getEntryNode()), 6560 MFI->getArgInfo().WorkItemIDZ); 6561 case Intrinsic::amdgcn_wavefrontsize: 6562 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6563 SDLoc(Op), MVT::i32); 6564 case Intrinsic::amdgcn_s_buffer_load: { 6565 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6566 SDValue GLC; 6567 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6568 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6569 IsGFX10Plus ? &DLC : nullptr)) 6570 return Op; 6571 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6572 DAG); 6573 } 6574 case Intrinsic::amdgcn_fdiv_fast: 6575 return lowerFDIV_FAST(Op, DAG); 6576 case Intrinsic::amdgcn_sin: 6577 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6578 6579 case Intrinsic::amdgcn_cos: 6580 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6581 6582 case Intrinsic::amdgcn_mul_u24: 6583 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6584 case Intrinsic::amdgcn_mul_i24: 6585 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6586 6587 case Intrinsic::amdgcn_log_clamp: { 6588 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6589 return SDValue(); 6590 6591 return emitRemovedIntrinsicError(DAG, DL, VT); 6592 } 6593 case Intrinsic::amdgcn_ldexp: 6594 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6595 Op.getOperand(1), Op.getOperand(2)); 6596 6597 case Intrinsic::amdgcn_fract: 6598 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6599 6600 case Intrinsic::amdgcn_class: 6601 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6602 Op.getOperand(1), Op.getOperand(2)); 6603 case Intrinsic::amdgcn_div_fmas: 6604 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6605 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6606 Op.getOperand(4)); 6607 6608 case Intrinsic::amdgcn_div_fixup: 6609 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6610 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6611 6612 case Intrinsic::amdgcn_div_scale: { 6613 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6614 6615 // Translate to the operands expected by the machine instruction. The 6616 // first parameter must be the same as the first instruction. 6617 SDValue Numerator = Op.getOperand(1); 6618 SDValue Denominator = Op.getOperand(2); 6619 6620 // Note this order is opposite of the machine instruction's operations, 6621 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6622 // intrinsic has the numerator as the first operand to match a normal 6623 // division operation. 6624 6625 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6626 6627 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6628 Denominator, Numerator); 6629 } 6630 case Intrinsic::amdgcn_icmp: { 6631 // There is a Pat that handles this variant, so return it as-is. 6632 if (Op.getOperand(1).getValueType() == MVT::i1 && 6633 Op.getConstantOperandVal(2) == 0 && 6634 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6635 return Op; 6636 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6637 } 6638 case Intrinsic::amdgcn_fcmp: { 6639 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6640 } 6641 case Intrinsic::amdgcn_ballot: 6642 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6643 case Intrinsic::amdgcn_fmed3: 6644 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6645 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6646 case Intrinsic::amdgcn_fdot2: 6647 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6648 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6649 Op.getOperand(4)); 6650 case Intrinsic::amdgcn_fmul_legacy: 6651 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6652 Op.getOperand(1), Op.getOperand(2)); 6653 case Intrinsic::amdgcn_sffbh: 6654 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6655 case Intrinsic::amdgcn_sbfe: 6656 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6657 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6658 case Intrinsic::amdgcn_ubfe: 6659 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6660 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6661 case Intrinsic::amdgcn_cvt_pkrtz: 6662 case Intrinsic::amdgcn_cvt_pknorm_i16: 6663 case Intrinsic::amdgcn_cvt_pknorm_u16: 6664 case Intrinsic::amdgcn_cvt_pk_i16: 6665 case Intrinsic::amdgcn_cvt_pk_u16: { 6666 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6667 EVT VT = Op.getValueType(); 6668 unsigned Opcode; 6669 6670 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6671 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6672 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6673 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6674 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6675 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6676 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6677 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6678 else 6679 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6680 6681 if (isTypeLegal(VT)) 6682 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6683 6684 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6685 Op.getOperand(1), Op.getOperand(2)); 6686 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6687 } 6688 case Intrinsic::amdgcn_fmad_ftz: 6689 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6690 Op.getOperand(2), Op.getOperand(3)); 6691 6692 case Intrinsic::amdgcn_if_break: 6693 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6694 Op->getOperand(1), Op->getOperand(2)), 0); 6695 6696 case Intrinsic::amdgcn_groupstaticsize: { 6697 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6698 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6699 return Op; 6700 6701 const Module *M = MF.getFunction().getParent(); 6702 const GlobalValue *GV = 6703 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6704 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6705 SIInstrInfo::MO_ABS32_LO); 6706 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6707 } 6708 case Intrinsic::amdgcn_is_shared: 6709 case Intrinsic::amdgcn_is_private: { 6710 SDLoc SL(Op); 6711 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6712 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6713 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6714 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6715 Op.getOperand(1)); 6716 6717 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6718 DAG.getConstant(1, SL, MVT::i32)); 6719 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6720 } 6721 case Intrinsic::amdgcn_alignbit: 6722 return DAG.getNode(ISD::FSHR, DL, VT, 6723 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6724 case Intrinsic::amdgcn_reloc_constant: { 6725 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6726 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6727 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6728 auto RelocSymbol = cast<GlobalVariable>( 6729 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6730 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6731 SIInstrInfo::MO_ABS32_LO); 6732 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6733 } 6734 default: 6735 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6736 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6737 return lowerImage(Op, ImageDimIntr, DAG, false); 6738 6739 return Op; 6740 } 6741 } 6742 6743 // This function computes an appropriate offset to pass to 6744 // MachineMemOperand::setOffset() based on the offset inputs to 6745 // an intrinsic. If any of the offsets are non-contstant or 6746 // if VIndex is non-zero then this function returns 0. Otherwise, 6747 // it returns the sum of VOffset, SOffset, and Offset. 6748 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6749 SDValue SOffset, 6750 SDValue Offset, 6751 SDValue VIndex = SDValue()) { 6752 6753 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6754 !isa<ConstantSDNode>(Offset)) 6755 return 0; 6756 6757 if (VIndex) { 6758 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6759 return 0; 6760 } 6761 6762 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6763 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6764 cast<ConstantSDNode>(Offset)->getSExtValue(); 6765 } 6766 6767 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6768 SelectionDAG &DAG, 6769 unsigned NewOpcode) const { 6770 SDLoc DL(Op); 6771 6772 SDValue VData = Op.getOperand(2); 6773 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6774 SDValue Ops[] = { 6775 Op.getOperand(0), // Chain 6776 VData, // vdata 6777 Op.getOperand(3), // rsrc 6778 DAG.getConstant(0, DL, MVT::i32), // vindex 6779 Offsets.first, // voffset 6780 Op.getOperand(5), // soffset 6781 Offsets.second, // offset 6782 Op.getOperand(6), // cachepolicy 6783 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6784 }; 6785 6786 auto *M = cast<MemSDNode>(Op); 6787 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6788 6789 EVT MemVT = VData.getValueType(); 6790 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6791 M->getMemOperand()); 6792 } 6793 6794 SDValue 6795 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6796 unsigned NewOpcode) const { 6797 SDLoc DL(Op); 6798 6799 SDValue VData = Op.getOperand(2); 6800 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6801 SDValue Ops[] = { 6802 Op.getOperand(0), // Chain 6803 VData, // vdata 6804 Op.getOperand(3), // rsrc 6805 Op.getOperand(4), // vindex 6806 Offsets.first, // voffset 6807 Op.getOperand(6), // soffset 6808 Offsets.second, // offset 6809 Op.getOperand(7), // cachepolicy 6810 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6811 }; 6812 6813 auto *M = cast<MemSDNode>(Op); 6814 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6815 Ops[3])); 6816 6817 EVT MemVT = VData.getValueType(); 6818 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6819 M->getMemOperand()); 6820 } 6821 6822 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6823 SelectionDAG &DAG) const { 6824 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6825 SDLoc DL(Op); 6826 6827 switch (IntrID) { 6828 case Intrinsic::amdgcn_ds_ordered_add: 6829 case Intrinsic::amdgcn_ds_ordered_swap: { 6830 MemSDNode *M = cast<MemSDNode>(Op); 6831 SDValue Chain = M->getOperand(0); 6832 SDValue M0 = M->getOperand(2); 6833 SDValue Value = M->getOperand(3); 6834 unsigned IndexOperand = M->getConstantOperandVal(7); 6835 unsigned WaveRelease = M->getConstantOperandVal(8); 6836 unsigned WaveDone = M->getConstantOperandVal(9); 6837 6838 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6839 IndexOperand &= ~0x3f; 6840 unsigned CountDw = 0; 6841 6842 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6843 CountDw = (IndexOperand >> 24) & 0xf; 6844 IndexOperand &= ~(0xf << 24); 6845 6846 if (CountDw < 1 || CountDw > 4) { 6847 report_fatal_error( 6848 "ds_ordered_count: dword count must be between 1 and 4"); 6849 } 6850 } 6851 6852 if (IndexOperand) 6853 report_fatal_error("ds_ordered_count: bad index operand"); 6854 6855 if (WaveDone && !WaveRelease) 6856 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6857 6858 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6859 unsigned ShaderType = 6860 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6861 unsigned Offset0 = OrderedCountIndex << 2; 6862 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6863 (Instruction << 4); 6864 6865 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6866 Offset1 |= (CountDw - 1) << 6; 6867 6868 unsigned Offset = Offset0 | (Offset1 << 8); 6869 6870 SDValue Ops[] = { 6871 Chain, 6872 Value, 6873 DAG.getTargetConstant(Offset, DL, MVT::i16), 6874 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6875 }; 6876 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6877 M->getVTList(), Ops, M->getMemoryVT(), 6878 M->getMemOperand()); 6879 } 6880 case Intrinsic::amdgcn_ds_fadd: { 6881 MemSDNode *M = cast<MemSDNode>(Op); 6882 unsigned Opc; 6883 switch (IntrID) { 6884 case Intrinsic::amdgcn_ds_fadd: 6885 Opc = ISD::ATOMIC_LOAD_FADD; 6886 break; 6887 } 6888 6889 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6890 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6891 M->getMemOperand()); 6892 } 6893 case Intrinsic::amdgcn_atomic_inc: 6894 case Intrinsic::amdgcn_atomic_dec: 6895 case Intrinsic::amdgcn_ds_fmin: 6896 case Intrinsic::amdgcn_ds_fmax: { 6897 MemSDNode *M = cast<MemSDNode>(Op); 6898 unsigned Opc; 6899 switch (IntrID) { 6900 case Intrinsic::amdgcn_atomic_inc: 6901 Opc = AMDGPUISD::ATOMIC_INC; 6902 break; 6903 case Intrinsic::amdgcn_atomic_dec: 6904 Opc = AMDGPUISD::ATOMIC_DEC; 6905 break; 6906 case Intrinsic::amdgcn_ds_fmin: 6907 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6908 break; 6909 case Intrinsic::amdgcn_ds_fmax: 6910 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6911 break; 6912 default: 6913 llvm_unreachable("Unknown intrinsic!"); 6914 } 6915 SDValue Ops[] = { 6916 M->getOperand(0), // Chain 6917 M->getOperand(2), // Ptr 6918 M->getOperand(3) // Value 6919 }; 6920 6921 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6922 M->getMemoryVT(), M->getMemOperand()); 6923 } 6924 case Intrinsic::amdgcn_buffer_load: 6925 case Intrinsic::amdgcn_buffer_load_format: { 6926 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6927 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6928 unsigned IdxEn = 1; 6929 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6930 IdxEn = Idx->getZExtValue() != 0; 6931 SDValue Ops[] = { 6932 Op.getOperand(0), // Chain 6933 Op.getOperand(2), // rsrc 6934 Op.getOperand(3), // vindex 6935 SDValue(), // voffset -- will be set by setBufferOffsets 6936 SDValue(), // soffset -- will be set by setBufferOffsets 6937 SDValue(), // offset -- will be set by setBufferOffsets 6938 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6939 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6940 }; 6941 6942 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6943 // We don't know the offset if vindex is non-zero, so clear it. 6944 if (IdxEn) 6945 Offset = 0; 6946 6947 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6948 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6949 6950 EVT VT = Op.getValueType(); 6951 EVT IntVT = VT.changeTypeToInteger(); 6952 auto *M = cast<MemSDNode>(Op); 6953 M->getMemOperand()->setOffset(Offset); 6954 EVT LoadVT = Op.getValueType(); 6955 6956 if (LoadVT.getScalarType() == MVT::f16) 6957 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6958 M, DAG, Ops); 6959 6960 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6961 if (LoadVT.getScalarType() == MVT::i8 || 6962 LoadVT.getScalarType() == MVT::i16) 6963 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6964 6965 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6966 M->getMemOperand(), DAG); 6967 } 6968 case Intrinsic::amdgcn_raw_buffer_load: 6969 case Intrinsic::amdgcn_raw_buffer_load_format: { 6970 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6971 6972 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6973 SDValue Ops[] = { 6974 Op.getOperand(0), // Chain 6975 Op.getOperand(2), // rsrc 6976 DAG.getConstant(0, DL, MVT::i32), // vindex 6977 Offsets.first, // voffset 6978 Op.getOperand(4), // soffset 6979 Offsets.second, // offset 6980 Op.getOperand(5), // cachepolicy, swizzled buffer 6981 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6982 }; 6983 6984 auto *M = cast<MemSDNode>(Op); 6985 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6986 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6987 } 6988 case Intrinsic::amdgcn_struct_buffer_load: 6989 case Intrinsic::amdgcn_struct_buffer_load_format: { 6990 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6991 6992 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6993 SDValue Ops[] = { 6994 Op.getOperand(0), // Chain 6995 Op.getOperand(2), // rsrc 6996 Op.getOperand(3), // vindex 6997 Offsets.first, // voffset 6998 Op.getOperand(5), // soffset 6999 Offsets.second, // offset 7000 Op.getOperand(6), // cachepolicy, swizzled buffer 7001 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7002 }; 7003 7004 auto *M = cast<MemSDNode>(Op); 7005 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 7006 Ops[2])); 7007 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7008 } 7009 case Intrinsic::amdgcn_tbuffer_load: { 7010 MemSDNode *M = cast<MemSDNode>(Op); 7011 EVT LoadVT = Op.getValueType(); 7012 7013 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7014 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7015 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7016 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7017 unsigned IdxEn = 1; 7018 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 7019 IdxEn = Idx->getZExtValue() != 0; 7020 SDValue Ops[] = { 7021 Op.getOperand(0), // Chain 7022 Op.getOperand(2), // rsrc 7023 Op.getOperand(3), // vindex 7024 Op.getOperand(4), // voffset 7025 Op.getOperand(5), // soffset 7026 Op.getOperand(6), // offset 7027 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7028 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7029 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7030 }; 7031 7032 if (LoadVT.getScalarType() == MVT::f16) 7033 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7034 M, DAG, Ops); 7035 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7036 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7037 DAG); 7038 } 7039 case Intrinsic::amdgcn_raw_tbuffer_load: { 7040 MemSDNode *M = cast<MemSDNode>(Op); 7041 EVT LoadVT = Op.getValueType(); 7042 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7043 7044 SDValue Ops[] = { 7045 Op.getOperand(0), // Chain 7046 Op.getOperand(2), // rsrc 7047 DAG.getConstant(0, DL, MVT::i32), // vindex 7048 Offsets.first, // voffset 7049 Op.getOperand(4), // soffset 7050 Offsets.second, // offset 7051 Op.getOperand(5), // format 7052 Op.getOperand(6), // cachepolicy, swizzled buffer 7053 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7054 }; 7055 7056 if (LoadVT.getScalarType() == MVT::f16) 7057 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7058 M, DAG, Ops); 7059 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7060 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7061 DAG); 7062 } 7063 case Intrinsic::amdgcn_struct_tbuffer_load: { 7064 MemSDNode *M = cast<MemSDNode>(Op); 7065 EVT LoadVT = Op.getValueType(); 7066 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7067 7068 SDValue Ops[] = { 7069 Op.getOperand(0), // Chain 7070 Op.getOperand(2), // rsrc 7071 Op.getOperand(3), // vindex 7072 Offsets.first, // voffset 7073 Op.getOperand(5), // soffset 7074 Offsets.second, // offset 7075 Op.getOperand(6), // format 7076 Op.getOperand(7), // cachepolicy, swizzled buffer 7077 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7078 }; 7079 7080 if (LoadVT.getScalarType() == MVT::f16) 7081 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7082 M, DAG, Ops); 7083 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7084 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7085 DAG); 7086 } 7087 case Intrinsic::amdgcn_buffer_atomic_swap: 7088 case Intrinsic::amdgcn_buffer_atomic_add: 7089 case Intrinsic::amdgcn_buffer_atomic_sub: 7090 case Intrinsic::amdgcn_buffer_atomic_csub: 7091 case Intrinsic::amdgcn_buffer_atomic_smin: 7092 case Intrinsic::amdgcn_buffer_atomic_umin: 7093 case Intrinsic::amdgcn_buffer_atomic_smax: 7094 case Intrinsic::amdgcn_buffer_atomic_umax: 7095 case Intrinsic::amdgcn_buffer_atomic_and: 7096 case Intrinsic::amdgcn_buffer_atomic_or: 7097 case Intrinsic::amdgcn_buffer_atomic_xor: 7098 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7099 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7100 unsigned IdxEn = 1; 7101 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7102 IdxEn = Idx->getZExtValue() != 0; 7103 SDValue Ops[] = { 7104 Op.getOperand(0), // Chain 7105 Op.getOperand(2), // vdata 7106 Op.getOperand(3), // rsrc 7107 Op.getOperand(4), // vindex 7108 SDValue(), // voffset -- will be set by setBufferOffsets 7109 SDValue(), // soffset -- will be set by setBufferOffsets 7110 SDValue(), // offset -- will be set by setBufferOffsets 7111 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7112 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7113 }; 7114 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7115 // We don't know the offset if vindex is non-zero, so clear it. 7116 if (IdxEn) 7117 Offset = 0; 7118 EVT VT = Op.getValueType(); 7119 7120 auto *M = cast<MemSDNode>(Op); 7121 M->getMemOperand()->setOffset(Offset); 7122 unsigned Opcode = 0; 7123 7124 switch (IntrID) { 7125 case Intrinsic::amdgcn_buffer_atomic_swap: 7126 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7127 break; 7128 case Intrinsic::amdgcn_buffer_atomic_add: 7129 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7130 break; 7131 case Intrinsic::amdgcn_buffer_atomic_sub: 7132 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7133 break; 7134 case Intrinsic::amdgcn_buffer_atomic_csub: 7135 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7136 break; 7137 case Intrinsic::amdgcn_buffer_atomic_smin: 7138 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7139 break; 7140 case Intrinsic::amdgcn_buffer_atomic_umin: 7141 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7142 break; 7143 case Intrinsic::amdgcn_buffer_atomic_smax: 7144 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7145 break; 7146 case Intrinsic::amdgcn_buffer_atomic_umax: 7147 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7148 break; 7149 case Intrinsic::amdgcn_buffer_atomic_and: 7150 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7151 break; 7152 case Intrinsic::amdgcn_buffer_atomic_or: 7153 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7154 break; 7155 case Intrinsic::amdgcn_buffer_atomic_xor: 7156 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7157 break; 7158 case Intrinsic::amdgcn_buffer_atomic_fadd: 7159 if (!Op.getValue(0).use_empty()) { 7160 DiagnosticInfoUnsupported 7161 NoFpRet(DAG.getMachineFunction().getFunction(), 7162 "return versions of fp atomics not supported", 7163 DL.getDebugLoc(), DS_Error); 7164 DAG.getContext()->diagnose(NoFpRet); 7165 return SDValue(); 7166 } 7167 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7168 break; 7169 default: 7170 llvm_unreachable("unhandled atomic opcode"); 7171 } 7172 7173 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7174 M->getMemOperand()); 7175 } 7176 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7177 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7178 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7179 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7180 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7181 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7182 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7183 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7184 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7185 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7186 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7187 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7188 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7189 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7190 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7191 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7192 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7193 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7194 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7195 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7196 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7197 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7198 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7199 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7200 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7201 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7202 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7203 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7204 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7205 return lowerStructBufferAtomicIntrin(Op, DAG, 7206 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7207 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7208 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7209 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7210 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7211 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7212 return lowerStructBufferAtomicIntrin(Op, DAG, 7213 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7214 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7215 return lowerStructBufferAtomicIntrin(Op, DAG, 7216 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7217 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7218 return lowerStructBufferAtomicIntrin(Op, DAG, 7219 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7220 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7221 return lowerStructBufferAtomicIntrin(Op, DAG, 7222 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7223 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7224 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7225 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7226 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7227 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7228 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7229 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7230 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7231 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7232 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7233 7234 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7235 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7236 unsigned IdxEn = 1; 7237 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7238 IdxEn = Idx->getZExtValue() != 0; 7239 SDValue Ops[] = { 7240 Op.getOperand(0), // Chain 7241 Op.getOperand(2), // src 7242 Op.getOperand(3), // cmp 7243 Op.getOperand(4), // rsrc 7244 Op.getOperand(5), // vindex 7245 SDValue(), // voffset -- will be set by setBufferOffsets 7246 SDValue(), // soffset -- will be set by setBufferOffsets 7247 SDValue(), // offset -- will be set by setBufferOffsets 7248 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7249 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7250 }; 7251 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7252 // We don't know the offset if vindex is non-zero, so clear it. 7253 if (IdxEn) 7254 Offset = 0; 7255 EVT VT = Op.getValueType(); 7256 auto *M = cast<MemSDNode>(Op); 7257 M->getMemOperand()->setOffset(Offset); 7258 7259 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7260 Op->getVTList(), Ops, VT, M->getMemOperand()); 7261 } 7262 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7263 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7264 SDValue Ops[] = { 7265 Op.getOperand(0), // Chain 7266 Op.getOperand(2), // src 7267 Op.getOperand(3), // cmp 7268 Op.getOperand(4), // rsrc 7269 DAG.getConstant(0, DL, MVT::i32), // vindex 7270 Offsets.first, // voffset 7271 Op.getOperand(6), // soffset 7272 Offsets.second, // offset 7273 Op.getOperand(7), // cachepolicy 7274 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7275 }; 7276 EVT VT = Op.getValueType(); 7277 auto *M = cast<MemSDNode>(Op); 7278 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7279 7280 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7281 Op->getVTList(), Ops, VT, M->getMemOperand()); 7282 } 7283 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7284 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7285 SDValue Ops[] = { 7286 Op.getOperand(0), // Chain 7287 Op.getOperand(2), // src 7288 Op.getOperand(3), // cmp 7289 Op.getOperand(4), // rsrc 7290 Op.getOperand(5), // vindex 7291 Offsets.first, // voffset 7292 Op.getOperand(7), // soffset 7293 Offsets.second, // offset 7294 Op.getOperand(8), // cachepolicy 7295 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7296 }; 7297 EVT VT = Op.getValueType(); 7298 auto *M = cast<MemSDNode>(Op); 7299 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7300 Ops[4])); 7301 7302 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7303 Op->getVTList(), Ops, VT, M->getMemOperand()); 7304 } 7305 case Intrinsic::amdgcn_global_atomic_fadd: { 7306 if (!Op.getValue(0).use_empty()) { 7307 DiagnosticInfoUnsupported 7308 NoFpRet(DAG.getMachineFunction().getFunction(), 7309 "return versions of fp atomics not supported", 7310 DL.getDebugLoc(), DS_Error); 7311 DAG.getContext()->diagnose(NoFpRet); 7312 return SDValue(); 7313 } 7314 MemSDNode *M = cast<MemSDNode>(Op); 7315 SDValue Ops[] = { 7316 M->getOperand(0), // Chain 7317 M->getOperand(2), // Ptr 7318 M->getOperand(3) // Value 7319 }; 7320 7321 EVT VT = Op.getOperand(3).getValueType(); 7322 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7323 DAG.getVTList(VT, MVT::Other), Ops, 7324 M->getMemOperand()); 7325 } 7326 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7327 SDLoc DL(Op); 7328 MemSDNode *M = cast<MemSDNode>(Op); 7329 SDValue NodePtr = M->getOperand(2); 7330 SDValue RayExtent = M->getOperand(3); 7331 SDValue RayOrigin = M->getOperand(4); 7332 SDValue RayDir = M->getOperand(5); 7333 SDValue RayInvDir = M->getOperand(6); 7334 SDValue TDescr = M->getOperand(7); 7335 7336 assert(NodePtr.getValueType() == MVT::i32 || 7337 NodePtr.getValueType() == MVT::i64); 7338 assert(RayDir.getValueType() == MVT::v4f16 || 7339 RayDir.getValueType() == MVT::v4f32); 7340 7341 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7342 bool Is64 = NodePtr.getValueType() == MVT::i64; 7343 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7344 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7345 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7346 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7347 7348 SmallVector<SDValue, 16> Ops; 7349 7350 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7351 SmallVector<SDValue, 3> Lanes; 7352 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7353 if (Lanes[0].getValueSizeInBits() == 32) { 7354 for (unsigned I = 0; I < 3; ++I) 7355 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7356 } else { 7357 if (IsAligned) { 7358 Ops.push_back( 7359 DAG.getBitcast(MVT::i32, 7360 DAG.getBuildVector(MVT::v2f16, DL, 7361 { Lanes[0], Lanes[1] }))); 7362 Ops.push_back(Lanes[2]); 7363 } else { 7364 SDValue Elt0 = Ops.pop_back_val(); 7365 Ops.push_back( 7366 DAG.getBitcast(MVT::i32, 7367 DAG.getBuildVector(MVT::v2f16, DL, 7368 { Elt0, Lanes[0] }))); 7369 Ops.push_back( 7370 DAG.getBitcast(MVT::i32, 7371 DAG.getBuildVector(MVT::v2f16, DL, 7372 { Lanes[1], Lanes[2] }))); 7373 } 7374 } 7375 }; 7376 7377 if (Is64) 7378 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7379 else 7380 Ops.push_back(NodePtr); 7381 7382 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7383 packLanes(RayOrigin, true); 7384 packLanes(RayDir, true); 7385 packLanes(RayInvDir, false); 7386 Ops.push_back(TDescr); 7387 if (IsA16) 7388 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7389 Ops.push_back(M->getChain()); 7390 7391 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7392 MachineMemOperand *MemRef = M->getMemOperand(); 7393 DAG.setNodeMemRefs(NewNode, {MemRef}); 7394 return SDValue(NewNode, 0); 7395 } 7396 default: 7397 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7398 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7399 return lowerImage(Op, ImageDimIntr, DAG, true); 7400 7401 return SDValue(); 7402 } 7403 } 7404 7405 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7406 // dwordx4 if on SI. 7407 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7408 SDVTList VTList, 7409 ArrayRef<SDValue> Ops, EVT MemVT, 7410 MachineMemOperand *MMO, 7411 SelectionDAG &DAG) const { 7412 EVT VT = VTList.VTs[0]; 7413 EVT WidenedVT = VT; 7414 EVT WidenedMemVT = MemVT; 7415 if (!Subtarget->hasDwordx3LoadStores() && 7416 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7417 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7418 WidenedVT.getVectorElementType(), 4); 7419 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7420 WidenedMemVT.getVectorElementType(), 4); 7421 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7422 } 7423 7424 assert(VTList.NumVTs == 2); 7425 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7426 7427 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7428 WidenedMemVT, MMO); 7429 if (WidenedVT != VT) { 7430 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7431 DAG.getVectorIdxConstant(0, DL)); 7432 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7433 } 7434 return NewOp; 7435 } 7436 7437 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7438 bool ImageStore) const { 7439 EVT StoreVT = VData.getValueType(); 7440 7441 // No change for f16 and legal vector D16 types. 7442 if (!StoreVT.isVector()) 7443 return VData; 7444 7445 SDLoc DL(VData); 7446 unsigned NumElements = StoreVT.getVectorNumElements(); 7447 7448 if (Subtarget->hasUnpackedD16VMem()) { 7449 // We need to unpack the packed data to store. 7450 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7451 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7452 7453 EVT EquivStoreVT = 7454 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7455 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7456 return DAG.UnrollVectorOp(ZExt.getNode()); 7457 } 7458 7459 // The sq block of gfx8.1 does not estimate register use correctly for d16 7460 // image store instructions. The data operand is computed as if it were not a 7461 // d16 image instruction. 7462 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7463 // Bitcast to i16 7464 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7465 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7466 7467 // Decompose into scalars 7468 SmallVector<SDValue, 4> Elts; 7469 DAG.ExtractVectorElements(IntVData, Elts); 7470 7471 // Group pairs of i16 into v2i16 and bitcast to i32 7472 SmallVector<SDValue, 4> PackedElts; 7473 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7474 SDValue Pair = 7475 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7476 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7477 PackedElts.push_back(IntPair); 7478 } 7479 if ((NumElements % 2) == 1) { 7480 // Handle v3i16 7481 unsigned I = Elts.size() / 2; 7482 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7483 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7484 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7485 PackedElts.push_back(IntPair); 7486 } 7487 7488 // Pad using UNDEF 7489 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7490 7491 // Build final vector 7492 EVT VecVT = 7493 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7494 return DAG.getBuildVector(VecVT, DL, PackedElts); 7495 } 7496 7497 if (NumElements == 3) { 7498 EVT IntStoreVT = 7499 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7500 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7501 7502 EVT WidenedStoreVT = EVT::getVectorVT( 7503 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7504 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7505 WidenedStoreVT.getStoreSizeInBits()); 7506 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7507 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7508 } 7509 7510 assert(isTypeLegal(StoreVT)); 7511 return VData; 7512 } 7513 7514 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7515 SelectionDAG &DAG) const { 7516 SDLoc DL(Op); 7517 SDValue Chain = Op.getOperand(0); 7518 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7519 MachineFunction &MF = DAG.getMachineFunction(); 7520 7521 switch (IntrinsicID) { 7522 case Intrinsic::amdgcn_exp_compr: { 7523 SDValue Src0 = Op.getOperand(4); 7524 SDValue Src1 = Op.getOperand(5); 7525 // Hack around illegal type on SI by directly selecting it. 7526 if (isTypeLegal(Src0.getValueType())) 7527 return SDValue(); 7528 7529 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7530 SDValue Undef = DAG.getUNDEF(MVT::f32); 7531 const SDValue Ops[] = { 7532 Op.getOperand(2), // tgt 7533 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7534 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7535 Undef, // src2 7536 Undef, // src3 7537 Op.getOperand(7), // vm 7538 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7539 Op.getOperand(3), // en 7540 Op.getOperand(0) // Chain 7541 }; 7542 7543 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7544 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7545 } 7546 case Intrinsic::amdgcn_s_barrier: { 7547 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7548 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7549 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7550 if (WGSize <= ST.getWavefrontSize()) 7551 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7552 Op.getOperand(0)), 0); 7553 } 7554 return SDValue(); 7555 }; 7556 case Intrinsic::amdgcn_tbuffer_store: { 7557 SDValue VData = Op.getOperand(2); 7558 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7559 if (IsD16) 7560 VData = handleD16VData(VData, DAG); 7561 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7562 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7563 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7564 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7565 unsigned IdxEn = 1; 7566 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7567 IdxEn = Idx->getZExtValue() != 0; 7568 SDValue Ops[] = { 7569 Chain, 7570 VData, // vdata 7571 Op.getOperand(3), // rsrc 7572 Op.getOperand(4), // vindex 7573 Op.getOperand(5), // voffset 7574 Op.getOperand(6), // soffset 7575 Op.getOperand(7), // offset 7576 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7577 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7578 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7579 }; 7580 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7581 AMDGPUISD::TBUFFER_STORE_FORMAT; 7582 MemSDNode *M = cast<MemSDNode>(Op); 7583 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7584 M->getMemoryVT(), M->getMemOperand()); 7585 } 7586 7587 case Intrinsic::amdgcn_struct_tbuffer_store: { 7588 SDValue VData = Op.getOperand(2); 7589 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7590 if (IsD16) 7591 VData = handleD16VData(VData, DAG); 7592 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7593 SDValue Ops[] = { 7594 Chain, 7595 VData, // vdata 7596 Op.getOperand(3), // rsrc 7597 Op.getOperand(4), // vindex 7598 Offsets.first, // voffset 7599 Op.getOperand(6), // soffset 7600 Offsets.second, // offset 7601 Op.getOperand(7), // format 7602 Op.getOperand(8), // cachepolicy, swizzled buffer 7603 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7604 }; 7605 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7606 AMDGPUISD::TBUFFER_STORE_FORMAT; 7607 MemSDNode *M = cast<MemSDNode>(Op); 7608 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7609 M->getMemoryVT(), M->getMemOperand()); 7610 } 7611 7612 case Intrinsic::amdgcn_raw_tbuffer_store: { 7613 SDValue VData = Op.getOperand(2); 7614 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7615 if (IsD16) 7616 VData = handleD16VData(VData, DAG); 7617 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7618 SDValue Ops[] = { 7619 Chain, 7620 VData, // vdata 7621 Op.getOperand(3), // rsrc 7622 DAG.getConstant(0, DL, MVT::i32), // vindex 7623 Offsets.first, // voffset 7624 Op.getOperand(5), // soffset 7625 Offsets.second, // offset 7626 Op.getOperand(6), // format 7627 Op.getOperand(7), // cachepolicy, swizzled buffer 7628 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7629 }; 7630 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7631 AMDGPUISD::TBUFFER_STORE_FORMAT; 7632 MemSDNode *M = cast<MemSDNode>(Op); 7633 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7634 M->getMemoryVT(), M->getMemOperand()); 7635 } 7636 7637 case Intrinsic::amdgcn_buffer_store: 7638 case Intrinsic::amdgcn_buffer_store_format: { 7639 SDValue VData = Op.getOperand(2); 7640 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7641 if (IsD16) 7642 VData = handleD16VData(VData, DAG); 7643 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7644 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7645 unsigned IdxEn = 1; 7646 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7647 IdxEn = Idx->getZExtValue() != 0; 7648 SDValue Ops[] = { 7649 Chain, 7650 VData, 7651 Op.getOperand(3), // rsrc 7652 Op.getOperand(4), // vindex 7653 SDValue(), // voffset -- will be set by setBufferOffsets 7654 SDValue(), // soffset -- will be set by setBufferOffsets 7655 SDValue(), // offset -- will be set by setBufferOffsets 7656 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7657 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7658 }; 7659 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7660 // We don't know the offset if vindex is non-zero, so clear it. 7661 if (IdxEn) 7662 Offset = 0; 7663 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7664 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7665 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7666 MemSDNode *M = cast<MemSDNode>(Op); 7667 M->getMemOperand()->setOffset(Offset); 7668 7669 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7670 EVT VDataType = VData.getValueType().getScalarType(); 7671 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7672 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7673 7674 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7675 M->getMemoryVT(), M->getMemOperand()); 7676 } 7677 7678 case Intrinsic::amdgcn_raw_buffer_store: 7679 case Intrinsic::amdgcn_raw_buffer_store_format: { 7680 const bool IsFormat = 7681 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7682 7683 SDValue VData = Op.getOperand(2); 7684 EVT VDataVT = VData.getValueType(); 7685 EVT EltType = VDataVT.getScalarType(); 7686 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7687 if (IsD16) { 7688 VData = handleD16VData(VData, DAG); 7689 VDataVT = VData.getValueType(); 7690 } 7691 7692 if (!isTypeLegal(VDataVT)) { 7693 VData = 7694 DAG.getNode(ISD::BITCAST, DL, 7695 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7696 } 7697 7698 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7699 SDValue Ops[] = { 7700 Chain, 7701 VData, 7702 Op.getOperand(3), // rsrc 7703 DAG.getConstant(0, DL, MVT::i32), // vindex 7704 Offsets.first, // voffset 7705 Op.getOperand(5), // soffset 7706 Offsets.second, // offset 7707 Op.getOperand(6), // cachepolicy, swizzled buffer 7708 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7709 }; 7710 unsigned Opc = 7711 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7712 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7713 MemSDNode *M = cast<MemSDNode>(Op); 7714 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7715 7716 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7717 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7718 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7719 7720 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7721 M->getMemoryVT(), M->getMemOperand()); 7722 } 7723 7724 case Intrinsic::amdgcn_struct_buffer_store: 7725 case Intrinsic::amdgcn_struct_buffer_store_format: { 7726 const bool IsFormat = 7727 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7728 7729 SDValue VData = Op.getOperand(2); 7730 EVT VDataVT = VData.getValueType(); 7731 EVT EltType = VDataVT.getScalarType(); 7732 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7733 7734 if (IsD16) { 7735 VData = handleD16VData(VData, DAG); 7736 VDataVT = VData.getValueType(); 7737 } 7738 7739 if (!isTypeLegal(VDataVT)) { 7740 VData = 7741 DAG.getNode(ISD::BITCAST, DL, 7742 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7743 } 7744 7745 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7746 SDValue Ops[] = { 7747 Chain, 7748 VData, 7749 Op.getOperand(3), // rsrc 7750 Op.getOperand(4), // vindex 7751 Offsets.first, // voffset 7752 Op.getOperand(6), // soffset 7753 Offsets.second, // offset 7754 Op.getOperand(7), // cachepolicy, swizzled buffer 7755 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7756 }; 7757 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7758 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7759 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7760 MemSDNode *M = cast<MemSDNode>(Op); 7761 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7762 Ops[3])); 7763 7764 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7765 EVT VDataType = VData.getValueType().getScalarType(); 7766 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7767 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7768 7769 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7770 M->getMemoryVT(), M->getMemOperand()); 7771 } 7772 case Intrinsic::amdgcn_end_cf: 7773 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7774 Op->getOperand(2), Chain), 0); 7775 7776 default: { 7777 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7778 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7779 return lowerImage(Op, ImageDimIntr, DAG, true); 7780 7781 return Op; 7782 } 7783 } 7784 } 7785 7786 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7787 // offset (the offset that is included in bounds checking and swizzling, to be 7788 // split between the instruction's voffset and immoffset fields) and soffset 7789 // (the offset that is excluded from bounds checking and swizzling, to go in 7790 // the instruction's soffset field). This function takes the first kind of 7791 // offset and figures out how to split it between voffset and immoffset. 7792 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7793 SDValue Offset, SelectionDAG &DAG) const { 7794 SDLoc DL(Offset); 7795 const unsigned MaxImm = 4095; 7796 SDValue N0 = Offset; 7797 ConstantSDNode *C1 = nullptr; 7798 7799 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7800 N0 = SDValue(); 7801 else if (DAG.isBaseWithConstantOffset(N0)) { 7802 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7803 N0 = N0.getOperand(0); 7804 } 7805 7806 if (C1) { 7807 unsigned ImmOffset = C1->getZExtValue(); 7808 // If the immediate value is too big for the immoffset field, put the value 7809 // and -4096 into the immoffset field so that the value that is copied/added 7810 // for the voffset field is a multiple of 4096, and it stands more chance 7811 // of being CSEd with the copy/add for another similar load/store. 7812 // However, do not do that rounding down to a multiple of 4096 if that is a 7813 // negative number, as it appears to be illegal to have a negative offset 7814 // in the vgpr, even if adding the immediate offset makes it positive. 7815 unsigned Overflow = ImmOffset & ~MaxImm; 7816 ImmOffset -= Overflow; 7817 if ((int32_t)Overflow < 0) { 7818 Overflow += ImmOffset; 7819 ImmOffset = 0; 7820 } 7821 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7822 if (Overflow) { 7823 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7824 if (!N0) 7825 N0 = OverflowVal; 7826 else { 7827 SDValue Ops[] = { N0, OverflowVal }; 7828 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7829 } 7830 } 7831 } 7832 if (!N0) 7833 N0 = DAG.getConstant(0, DL, MVT::i32); 7834 if (!C1) 7835 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7836 return {N0, SDValue(C1, 0)}; 7837 } 7838 7839 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7840 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7841 // pointed to by Offsets. 7842 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7843 SelectionDAG &DAG, SDValue *Offsets, 7844 Align Alignment) const { 7845 SDLoc DL(CombinedOffset); 7846 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7847 uint32_t Imm = C->getZExtValue(); 7848 uint32_t SOffset, ImmOffset; 7849 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7850 Alignment)) { 7851 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7852 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7853 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7854 return SOffset + ImmOffset; 7855 } 7856 } 7857 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7858 SDValue N0 = CombinedOffset.getOperand(0); 7859 SDValue N1 = CombinedOffset.getOperand(1); 7860 uint32_t SOffset, ImmOffset; 7861 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7862 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7863 Subtarget, Alignment)) { 7864 Offsets[0] = N0; 7865 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7866 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7867 return 0; 7868 } 7869 } 7870 Offsets[0] = CombinedOffset; 7871 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7872 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7873 return 0; 7874 } 7875 7876 // Handle 8 bit and 16 bit buffer loads 7877 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7878 EVT LoadVT, SDLoc DL, 7879 ArrayRef<SDValue> Ops, 7880 MemSDNode *M) const { 7881 EVT IntVT = LoadVT.changeTypeToInteger(); 7882 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7883 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7884 7885 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7886 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7887 Ops, IntVT, 7888 M->getMemOperand()); 7889 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7890 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7891 7892 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7893 } 7894 7895 // Handle 8 bit and 16 bit buffer stores 7896 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7897 EVT VDataType, SDLoc DL, 7898 SDValue Ops[], 7899 MemSDNode *M) const { 7900 if (VDataType == MVT::f16) 7901 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7902 7903 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7904 Ops[1] = BufferStoreExt; 7905 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7906 AMDGPUISD::BUFFER_STORE_SHORT; 7907 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7908 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7909 M->getMemOperand()); 7910 } 7911 7912 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7913 ISD::LoadExtType ExtType, SDValue Op, 7914 const SDLoc &SL, EVT VT) { 7915 if (VT.bitsLT(Op.getValueType())) 7916 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7917 7918 switch (ExtType) { 7919 case ISD::SEXTLOAD: 7920 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7921 case ISD::ZEXTLOAD: 7922 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7923 case ISD::EXTLOAD: 7924 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7925 case ISD::NON_EXTLOAD: 7926 return Op; 7927 } 7928 7929 llvm_unreachable("invalid ext type"); 7930 } 7931 7932 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7933 SelectionDAG &DAG = DCI.DAG; 7934 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7935 return SDValue(); 7936 7937 // FIXME: Constant loads should all be marked invariant. 7938 unsigned AS = Ld->getAddressSpace(); 7939 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7940 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7941 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7942 return SDValue(); 7943 7944 // Don't do this early, since it may interfere with adjacent load merging for 7945 // illegal types. We can avoid losing alignment information for exotic types 7946 // pre-legalize. 7947 EVT MemVT = Ld->getMemoryVT(); 7948 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7949 MemVT.getSizeInBits() >= 32) 7950 return SDValue(); 7951 7952 SDLoc SL(Ld); 7953 7954 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7955 "unexpected vector extload"); 7956 7957 // TODO: Drop only high part of range. 7958 SDValue Ptr = Ld->getBasePtr(); 7959 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7960 MVT::i32, SL, Ld->getChain(), Ptr, 7961 Ld->getOffset(), 7962 Ld->getPointerInfo(), MVT::i32, 7963 Ld->getAlignment(), 7964 Ld->getMemOperand()->getFlags(), 7965 Ld->getAAInfo(), 7966 nullptr); // Drop ranges 7967 7968 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7969 if (MemVT.isFloatingPoint()) { 7970 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7971 "unexpected fp extload"); 7972 TruncVT = MemVT.changeTypeToInteger(); 7973 } 7974 7975 SDValue Cvt = NewLoad; 7976 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7977 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7978 DAG.getValueType(TruncVT)); 7979 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7980 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7981 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7982 } else { 7983 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7984 } 7985 7986 EVT VT = Ld->getValueType(0); 7987 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7988 7989 DCI.AddToWorklist(Cvt.getNode()); 7990 7991 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7992 // the appropriate extension from the 32-bit load. 7993 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7994 DCI.AddToWorklist(Cvt.getNode()); 7995 7996 // Handle conversion back to floating point if necessary. 7997 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7998 7999 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8000 } 8001 8002 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8003 SDLoc DL(Op); 8004 LoadSDNode *Load = cast<LoadSDNode>(Op); 8005 ISD::LoadExtType ExtType = Load->getExtensionType(); 8006 EVT MemVT = Load->getMemoryVT(); 8007 8008 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8009 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8010 return SDValue(); 8011 8012 // FIXME: Copied from PPC 8013 // First, load into 32 bits, then truncate to 1 bit. 8014 8015 SDValue Chain = Load->getChain(); 8016 SDValue BasePtr = Load->getBasePtr(); 8017 MachineMemOperand *MMO = Load->getMemOperand(); 8018 8019 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8020 8021 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8022 BasePtr, RealMemVT, MMO); 8023 8024 if (!MemVT.isVector()) { 8025 SDValue Ops[] = { 8026 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8027 NewLD.getValue(1) 8028 }; 8029 8030 return DAG.getMergeValues(Ops, DL); 8031 } 8032 8033 SmallVector<SDValue, 3> Elts; 8034 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8035 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8036 DAG.getConstant(I, DL, MVT::i32)); 8037 8038 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8039 } 8040 8041 SDValue Ops[] = { 8042 DAG.getBuildVector(MemVT, DL, Elts), 8043 NewLD.getValue(1) 8044 }; 8045 8046 return DAG.getMergeValues(Ops, DL); 8047 } 8048 8049 if (!MemVT.isVector()) 8050 return SDValue(); 8051 8052 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8053 "Custom lowering for non-i32 vectors hasn't been implemented."); 8054 8055 unsigned Alignment = Load->getAlignment(); 8056 unsigned AS = Load->getAddressSpace(); 8057 if (Subtarget->hasLDSMisalignedBug() && 8058 AS == AMDGPUAS::FLAT_ADDRESS && 8059 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8060 return SplitVectorLoad(Op, DAG); 8061 } 8062 8063 MachineFunction &MF = DAG.getMachineFunction(); 8064 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8065 // If there is a possibilty that flat instruction access scratch memory 8066 // then we need to use the same legalization rules we use for private. 8067 if (AS == AMDGPUAS::FLAT_ADDRESS && 8068 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8069 AS = MFI->hasFlatScratchInit() ? 8070 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8071 8072 unsigned NumElements = MemVT.getVectorNumElements(); 8073 8074 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8075 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8076 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8077 if (MemVT.isPow2VectorType()) 8078 return SDValue(); 8079 return WidenOrSplitVectorLoad(Op, DAG); 8080 } 8081 // Non-uniform loads will be selected to MUBUF instructions, so they 8082 // have the same legalization requirements as global and private 8083 // loads. 8084 // 8085 } 8086 8087 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8088 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8089 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8090 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8091 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8092 Alignment >= 4 && NumElements < 32) { 8093 if (MemVT.isPow2VectorType()) 8094 return SDValue(); 8095 return WidenOrSplitVectorLoad(Op, DAG); 8096 } 8097 // Non-uniform loads will be selected to MUBUF instructions, so they 8098 // have the same legalization requirements as global and private 8099 // loads. 8100 // 8101 } 8102 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8103 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8104 AS == AMDGPUAS::GLOBAL_ADDRESS || 8105 AS == AMDGPUAS::FLAT_ADDRESS) { 8106 if (NumElements > 4) 8107 return SplitVectorLoad(Op, DAG); 8108 // v3 loads not supported on SI. 8109 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8110 return WidenOrSplitVectorLoad(Op, DAG); 8111 8112 // v3 and v4 loads are supported for private and global memory. 8113 return SDValue(); 8114 } 8115 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8116 // Depending on the setting of the private_element_size field in the 8117 // resource descriptor, we can only make private accesses up to a certain 8118 // size. 8119 switch (Subtarget->getMaxPrivateElementSize()) { 8120 case 4: { 8121 SDValue Ops[2]; 8122 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8123 return DAG.getMergeValues(Ops, DL); 8124 } 8125 case 8: 8126 if (NumElements > 2) 8127 return SplitVectorLoad(Op, DAG); 8128 return SDValue(); 8129 case 16: 8130 // Same as global/flat 8131 if (NumElements > 4) 8132 return SplitVectorLoad(Op, DAG); 8133 // v3 loads not supported on SI. 8134 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8135 return WidenOrSplitVectorLoad(Op, DAG); 8136 8137 return SDValue(); 8138 default: 8139 llvm_unreachable("unsupported private_element_size"); 8140 } 8141 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8142 // Use ds_read_b128 or ds_read_b96 when possible. 8143 if (Subtarget->hasDS96AndDS128() && 8144 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8145 MemVT.getStoreSize() == 12) && 8146 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8147 Load->getAlign())) 8148 return SDValue(); 8149 8150 if (NumElements > 2) 8151 return SplitVectorLoad(Op, DAG); 8152 8153 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8154 // address is negative, then the instruction is incorrectly treated as 8155 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8156 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8157 // load later in the SILoadStoreOptimizer. 8158 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8159 NumElements == 2 && MemVT.getStoreSize() == 8 && 8160 Load->getAlignment() < 8) { 8161 return SplitVectorLoad(Op, DAG); 8162 } 8163 } 8164 8165 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8166 MemVT, *Load->getMemOperand())) { 8167 SDValue Ops[2]; 8168 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8169 return DAG.getMergeValues(Ops, DL); 8170 } 8171 8172 return SDValue(); 8173 } 8174 8175 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8176 EVT VT = Op.getValueType(); 8177 assert(VT.getSizeInBits() == 64); 8178 8179 SDLoc DL(Op); 8180 SDValue Cond = Op.getOperand(0); 8181 8182 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8183 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8184 8185 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8186 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8187 8188 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8189 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8190 8191 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8192 8193 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8194 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8195 8196 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8197 8198 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8199 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8200 } 8201 8202 // Catch division cases where we can use shortcuts with rcp and rsq 8203 // instructions. 8204 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8205 SelectionDAG &DAG) const { 8206 SDLoc SL(Op); 8207 SDValue LHS = Op.getOperand(0); 8208 SDValue RHS = Op.getOperand(1); 8209 EVT VT = Op.getValueType(); 8210 const SDNodeFlags Flags = Op->getFlags(); 8211 8212 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 8213 Flags.hasApproximateFuncs(); 8214 8215 // Without !fpmath accuracy information, we can't do more because we don't 8216 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8217 if (!AllowInaccurateRcp) 8218 return SDValue(); 8219 8220 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8221 if (CLHS->isExactlyValue(1.0)) { 8222 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8223 // the CI documentation has a worst case error of 1 ulp. 8224 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8225 // use it as long as we aren't trying to use denormals. 8226 // 8227 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8228 8229 // 1.0 / sqrt(x) -> rsq(x) 8230 8231 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8232 // error seems really high at 2^29 ULP. 8233 if (RHS.getOpcode() == ISD::FSQRT) 8234 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8235 8236 // 1.0 / x -> rcp(x) 8237 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8238 } 8239 8240 // Same as for 1.0, but expand the sign out of the constant. 8241 if (CLHS->isExactlyValue(-1.0)) { 8242 // -1.0 / x -> rcp (fneg x) 8243 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8244 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8245 } 8246 } 8247 8248 // Turn into multiply by the reciprocal. 8249 // x / y -> x * (1.0 / y) 8250 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8251 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8252 } 8253 8254 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8255 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8256 SDNodeFlags Flags) { 8257 if (GlueChain->getNumValues() <= 1) { 8258 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8259 } 8260 8261 assert(GlueChain->getNumValues() == 3); 8262 8263 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8264 switch (Opcode) { 8265 default: llvm_unreachable("no chain equivalent for opcode"); 8266 case ISD::FMUL: 8267 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8268 break; 8269 } 8270 8271 return DAG.getNode(Opcode, SL, VTList, 8272 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8273 Flags); 8274 } 8275 8276 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8277 EVT VT, SDValue A, SDValue B, SDValue C, 8278 SDValue GlueChain, SDNodeFlags Flags) { 8279 if (GlueChain->getNumValues() <= 1) { 8280 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8281 } 8282 8283 assert(GlueChain->getNumValues() == 3); 8284 8285 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8286 switch (Opcode) { 8287 default: llvm_unreachable("no chain equivalent for opcode"); 8288 case ISD::FMA: 8289 Opcode = AMDGPUISD::FMA_W_CHAIN; 8290 break; 8291 } 8292 8293 return DAG.getNode(Opcode, SL, VTList, 8294 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8295 Flags); 8296 } 8297 8298 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8299 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8300 return FastLowered; 8301 8302 SDLoc SL(Op); 8303 SDValue Src0 = Op.getOperand(0); 8304 SDValue Src1 = Op.getOperand(1); 8305 8306 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8307 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8308 8309 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8310 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8311 8312 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8313 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8314 8315 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8316 } 8317 8318 // Faster 2.5 ULP division that does not support denormals. 8319 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8320 SDLoc SL(Op); 8321 SDValue LHS = Op.getOperand(1); 8322 SDValue RHS = Op.getOperand(2); 8323 8324 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8325 8326 const APFloat K0Val(BitsToFloat(0x6f800000)); 8327 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8328 8329 const APFloat K1Val(BitsToFloat(0x2f800000)); 8330 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8331 8332 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8333 8334 EVT SetCCVT = 8335 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8336 8337 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8338 8339 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8340 8341 // TODO: Should this propagate fast-math-flags? 8342 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8343 8344 // rcp does not support denormals. 8345 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8346 8347 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8348 8349 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8350 } 8351 8352 // Returns immediate value for setting the F32 denorm mode when using the 8353 // S_DENORM_MODE instruction. 8354 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8355 const SDLoc &SL, const GCNSubtarget *ST) { 8356 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8357 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8358 ? FP_DENORM_FLUSH_NONE 8359 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8360 8361 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8362 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8363 } 8364 8365 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8366 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8367 return FastLowered; 8368 8369 // The selection matcher assumes anything with a chain selecting to a 8370 // mayRaiseFPException machine instruction. Since we're introducing a chain 8371 // here, we need to explicitly report nofpexcept for the regular fdiv 8372 // lowering. 8373 SDNodeFlags Flags = Op->getFlags(); 8374 Flags.setNoFPExcept(true); 8375 8376 SDLoc SL(Op); 8377 SDValue LHS = Op.getOperand(0); 8378 SDValue RHS = Op.getOperand(1); 8379 8380 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8381 8382 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8383 8384 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8385 {RHS, RHS, LHS}, Flags); 8386 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8387 {LHS, RHS, LHS}, Flags); 8388 8389 // Denominator is scaled to not be denormal, so using rcp is ok. 8390 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8391 DenominatorScaled, Flags); 8392 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8393 DenominatorScaled, Flags); 8394 8395 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8396 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8397 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8398 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8399 8400 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8401 8402 if (!HasFP32Denormals) { 8403 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8404 // lowering. The chain dependence is insufficient, and we need glue. We do 8405 // not need the glue variants in a strictfp function. 8406 8407 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8408 8409 SDNode *EnableDenorm; 8410 if (Subtarget->hasDenormModeInst()) { 8411 const SDValue EnableDenormValue = 8412 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8413 8414 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8415 DAG.getEntryNode(), EnableDenormValue).getNode(); 8416 } else { 8417 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8418 SL, MVT::i32); 8419 EnableDenorm = 8420 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8421 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8422 } 8423 8424 SDValue Ops[3] = { 8425 NegDivScale0, 8426 SDValue(EnableDenorm, 0), 8427 SDValue(EnableDenorm, 1) 8428 }; 8429 8430 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8431 } 8432 8433 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8434 ApproxRcp, One, NegDivScale0, Flags); 8435 8436 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8437 ApproxRcp, Fma0, Flags); 8438 8439 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8440 Fma1, Fma1, Flags); 8441 8442 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8443 NumeratorScaled, Mul, Flags); 8444 8445 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8446 Fma2, Fma1, Mul, Fma2, Flags); 8447 8448 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8449 NumeratorScaled, Fma3, Flags); 8450 8451 if (!HasFP32Denormals) { 8452 SDNode *DisableDenorm; 8453 if (Subtarget->hasDenormModeInst()) { 8454 const SDValue DisableDenormValue = 8455 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8456 8457 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8458 Fma4.getValue(1), DisableDenormValue, 8459 Fma4.getValue(2)).getNode(); 8460 } else { 8461 const SDValue DisableDenormValue = 8462 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8463 8464 DisableDenorm = DAG.getMachineNode( 8465 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8466 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8467 } 8468 8469 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8470 SDValue(DisableDenorm, 0), DAG.getRoot()); 8471 DAG.setRoot(OutputChain); 8472 } 8473 8474 SDValue Scale = NumeratorScaled.getValue(1); 8475 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8476 {Fma4, Fma1, Fma3, Scale}, Flags); 8477 8478 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8479 } 8480 8481 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8482 if (DAG.getTarget().Options.UnsafeFPMath) 8483 return lowerFastUnsafeFDIV(Op, DAG); 8484 8485 SDLoc SL(Op); 8486 SDValue X = Op.getOperand(0); 8487 SDValue Y = Op.getOperand(1); 8488 8489 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8490 8491 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8492 8493 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8494 8495 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8496 8497 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8498 8499 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8500 8501 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8502 8503 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8504 8505 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8506 8507 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8508 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8509 8510 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8511 NegDivScale0, Mul, DivScale1); 8512 8513 SDValue Scale; 8514 8515 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8516 // Workaround a hardware bug on SI where the condition output from div_scale 8517 // is not usable. 8518 8519 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8520 8521 // Figure out if the scale to use for div_fmas. 8522 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8523 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8524 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8525 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8526 8527 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8528 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8529 8530 SDValue Scale0Hi 8531 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8532 SDValue Scale1Hi 8533 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8534 8535 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8536 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8537 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8538 } else { 8539 Scale = DivScale1.getValue(1); 8540 } 8541 8542 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8543 Fma4, Fma3, Mul, Scale); 8544 8545 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8546 } 8547 8548 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8549 EVT VT = Op.getValueType(); 8550 8551 if (VT == MVT::f32) 8552 return LowerFDIV32(Op, DAG); 8553 8554 if (VT == MVT::f64) 8555 return LowerFDIV64(Op, DAG); 8556 8557 if (VT == MVT::f16) 8558 return LowerFDIV16(Op, DAG); 8559 8560 llvm_unreachable("Unexpected type for fdiv"); 8561 } 8562 8563 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8564 SDLoc DL(Op); 8565 StoreSDNode *Store = cast<StoreSDNode>(Op); 8566 EVT VT = Store->getMemoryVT(); 8567 8568 if (VT == MVT::i1) { 8569 return DAG.getTruncStore(Store->getChain(), DL, 8570 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8571 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8572 } 8573 8574 assert(VT.isVector() && 8575 Store->getValue().getValueType().getScalarType() == MVT::i32); 8576 8577 unsigned AS = Store->getAddressSpace(); 8578 if (Subtarget->hasLDSMisalignedBug() && 8579 AS == AMDGPUAS::FLAT_ADDRESS && 8580 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8581 return SplitVectorStore(Op, DAG); 8582 } 8583 8584 MachineFunction &MF = DAG.getMachineFunction(); 8585 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8586 // If there is a possibilty that flat instruction access scratch memory 8587 // then we need to use the same legalization rules we use for private. 8588 if (AS == AMDGPUAS::FLAT_ADDRESS && 8589 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8590 AS = MFI->hasFlatScratchInit() ? 8591 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8592 8593 unsigned NumElements = VT.getVectorNumElements(); 8594 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8595 AS == AMDGPUAS::FLAT_ADDRESS) { 8596 if (NumElements > 4) 8597 return SplitVectorStore(Op, DAG); 8598 // v3 stores not supported on SI. 8599 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8600 return SplitVectorStore(Op, DAG); 8601 8602 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8603 VT, *Store->getMemOperand())) 8604 return expandUnalignedStore(Store, DAG); 8605 8606 return SDValue(); 8607 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8608 switch (Subtarget->getMaxPrivateElementSize()) { 8609 case 4: 8610 return scalarizeVectorStore(Store, DAG); 8611 case 8: 8612 if (NumElements > 2) 8613 return SplitVectorStore(Op, DAG); 8614 return SDValue(); 8615 case 16: 8616 if (NumElements > 4 || 8617 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8618 return SplitVectorStore(Op, DAG); 8619 return SDValue(); 8620 default: 8621 llvm_unreachable("unsupported private_element_size"); 8622 } 8623 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8624 // Use ds_write_b128 or ds_write_b96 when possible. 8625 if (Subtarget->hasDS96AndDS128() && 8626 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8627 (VT.getStoreSize() == 12)) && 8628 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8629 Store->getAlign())) 8630 return SDValue(); 8631 8632 if (NumElements > 2) 8633 return SplitVectorStore(Op, DAG); 8634 8635 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8636 // address is negative, then the instruction is incorrectly treated as 8637 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8638 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8639 // store later in the SILoadStoreOptimizer. 8640 if (!Subtarget->hasUsableDSOffset() && 8641 NumElements == 2 && VT.getStoreSize() == 8 && 8642 Store->getAlignment() < 8) { 8643 return SplitVectorStore(Op, DAG); 8644 } 8645 8646 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8647 VT, *Store->getMemOperand())) { 8648 if (VT.isVector()) 8649 return SplitVectorStore(Op, DAG); 8650 return expandUnalignedStore(Store, DAG); 8651 } 8652 8653 return SDValue(); 8654 } else { 8655 llvm_unreachable("unhandled address space"); 8656 } 8657 } 8658 8659 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8660 SDLoc DL(Op); 8661 EVT VT = Op.getValueType(); 8662 SDValue Arg = Op.getOperand(0); 8663 SDValue TrigVal; 8664 8665 // Propagate fast-math flags so that the multiply we introduce can be folded 8666 // if Arg is already the result of a multiply by constant. 8667 auto Flags = Op->getFlags(); 8668 8669 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8670 8671 if (Subtarget->hasTrigReducedRange()) { 8672 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8673 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8674 } else { 8675 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8676 } 8677 8678 switch (Op.getOpcode()) { 8679 case ISD::FCOS: 8680 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8681 case ISD::FSIN: 8682 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8683 default: 8684 llvm_unreachable("Wrong trig opcode"); 8685 } 8686 } 8687 8688 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8689 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8690 assert(AtomicNode->isCompareAndSwap()); 8691 unsigned AS = AtomicNode->getAddressSpace(); 8692 8693 // No custom lowering required for local address space 8694 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8695 return Op; 8696 8697 // Non-local address space requires custom lowering for atomic compare 8698 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8699 SDLoc DL(Op); 8700 SDValue ChainIn = Op.getOperand(0); 8701 SDValue Addr = Op.getOperand(1); 8702 SDValue Old = Op.getOperand(2); 8703 SDValue New = Op.getOperand(3); 8704 EVT VT = Op.getValueType(); 8705 MVT SimpleVT = VT.getSimpleVT(); 8706 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8707 8708 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8709 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8710 8711 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8712 Ops, VT, AtomicNode->getMemOperand()); 8713 } 8714 8715 //===----------------------------------------------------------------------===// 8716 // Custom DAG optimizations 8717 //===----------------------------------------------------------------------===// 8718 8719 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8720 DAGCombinerInfo &DCI) const { 8721 EVT VT = N->getValueType(0); 8722 EVT ScalarVT = VT.getScalarType(); 8723 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8724 return SDValue(); 8725 8726 SelectionDAG &DAG = DCI.DAG; 8727 SDLoc DL(N); 8728 8729 SDValue Src = N->getOperand(0); 8730 EVT SrcVT = Src.getValueType(); 8731 8732 // TODO: We could try to match extracting the higher bytes, which would be 8733 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8734 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8735 // about in practice. 8736 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8737 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8738 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8739 DCI.AddToWorklist(Cvt.getNode()); 8740 8741 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8742 if (ScalarVT != MVT::f32) { 8743 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8744 DAG.getTargetConstant(0, DL, MVT::i32)); 8745 } 8746 return Cvt; 8747 } 8748 } 8749 8750 return SDValue(); 8751 } 8752 8753 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8754 8755 // This is a variant of 8756 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8757 // 8758 // The normal DAG combiner will do this, but only if the add has one use since 8759 // that would increase the number of instructions. 8760 // 8761 // This prevents us from seeing a constant offset that can be folded into a 8762 // memory instruction's addressing mode. If we know the resulting add offset of 8763 // a pointer can be folded into an addressing offset, we can replace the pointer 8764 // operand with the add of new constant offset. This eliminates one of the uses, 8765 // and may allow the remaining use to also be simplified. 8766 // 8767 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8768 unsigned AddrSpace, 8769 EVT MemVT, 8770 DAGCombinerInfo &DCI) const { 8771 SDValue N0 = N->getOperand(0); 8772 SDValue N1 = N->getOperand(1); 8773 8774 // We only do this to handle cases where it's profitable when there are 8775 // multiple uses of the add, so defer to the standard combine. 8776 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8777 N0->hasOneUse()) 8778 return SDValue(); 8779 8780 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8781 if (!CN1) 8782 return SDValue(); 8783 8784 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8785 if (!CAdd) 8786 return SDValue(); 8787 8788 // If the resulting offset is too large, we can't fold it into the addressing 8789 // mode offset. 8790 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8791 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8792 8793 AddrMode AM; 8794 AM.HasBaseReg = true; 8795 AM.BaseOffs = Offset.getSExtValue(); 8796 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8797 return SDValue(); 8798 8799 SelectionDAG &DAG = DCI.DAG; 8800 SDLoc SL(N); 8801 EVT VT = N->getValueType(0); 8802 8803 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8804 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8805 8806 SDNodeFlags Flags; 8807 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8808 (N0.getOpcode() == ISD::OR || 8809 N0->getFlags().hasNoUnsignedWrap())); 8810 8811 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8812 } 8813 8814 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8815 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8816 /// specific intrinsic, but they all place the pointer operand first. 8817 static unsigned getBasePtrIndex(const MemSDNode *N) { 8818 switch (N->getOpcode()) { 8819 case ISD::STORE: 8820 case ISD::INTRINSIC_W_CHAIN: 8821 case ISD::INTRINSIC_VOID: 8822 return 2; 8823 default: 8824 return 1; 8825 } 8826 } 8827 8828 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8829 DAGCombinerInfo &DCI) const { 8830 SelectionDAG &DAG = DCI.DAG; 8831 SDLoc SL(N); 8832 8833 unsigned PtrIdx = getBasePtrIndex(N); 8834 SDValue Ptr = N->getOperand(PtrIdx); 8835 8836 // TODO: We could also do this for multiplies. 8837 if (Ptr.getOpcode() == ISD::SHL) { 8838 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8839 N->getMemoryVT(), DCI); 8840 if (NewPtr) { 8841 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8842 8843 NewOps[PtrIdx] = NewPtr; 8844 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8845 } 8846 } 8847 8848 return SDValue(); 8849 } 8850 8851 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8852 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8853 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8854 (Opc == ISD::XOR && Val == 0); 8855 } 8856 8857 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8858 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8859 // integer combine opportunities since most 64-bit operations are decomposed 8860 // this way. TODO: We won't want this for SALU especially if it is an inline 8861 // immediate. 8862 SDValue SITargetLowering::splitBinaryBitConstantOp( 8863 DAGCombinerInfo &DCI, 8864 const SDLoc &SL, 8865 unsigned Opc, SDValue LHS, 8866 const ConstantSDNode *CRHS) const { 8867 uint64_t Val = CRHS->getZExtValue(); 8868 uint32_t ValLo = Lo_32(Val); 8869 uint32_t ValHi = Hi_32(Val); 8870 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8871 8872 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8873 bitOpWithConstantIsReducible(Opc, ValHi)) || 8874 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8875 // If we need to materialize a 64-bit immediate, it will be split up later 8876 // anyway. Avoid creating the harder to understand 64-bit immediate 8877 // materialization. 8878 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8879 } 8880 8881 return SDValue(); 8882 } 8883 8884 // Returns true if argument is a boolean value which is not serialized into 8885 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8886 static bool isBoolSGPR(SDValue V) { 8887 if (V.getValueType() != MVT::i1) 8888 return false; 8889 switch (V.getOpcode()) { 8890 default: break; 8891 case ISD::SETCC: 8892 case ISD::AND: 8893 case ISD::OR: 8894 case ISD::XOR: 8895 case AMDGPUISD::FP_CLASS: 8896 return true; 8897 } 8898 return false; 8899 } 8900 8901 // If a constant has all zeroes or all ones within each byte return it. 8902 // Otherwise return 0. 8903 static uint32_t getConstantPermuteMask(uint32_t C) { 8904 // 0xff for any zero byte in the mask 8905 uint32_t ZeroByteMask = 0; 8906 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8907 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8908 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8909 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8910 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8911 if ((NonZeroByteMask & C) != NonZeroByteMask) 8912 return 0; // Partial bytes selected. 8913 return C; 8914 } 8915 8916 // Check if a node selects whole bytes from its operand 0 starting at a byte 8917 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8918 // or -1 if not succeeded. 8919 // Note byte select encoding: 8920 // value 0-3 selects corresponding source byte; 8921 // value 0xc selects zero; 8922 // value 0xff selects 0xff. 8923 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8924 assert(V.getValueSizeInBits() == 32); 8925 8926 if (V.getNumOperands() != 2) 8927 return ~0; 8928 8929 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8930 if (!N1) 8931 return ~0; 8932 8933 uint32_t C = N1->getZExtValue(); 8934 8935 switch (V.getOpcode()) { 8936 default: 8937 break; 8938 case ISD::AND: 8939 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8940 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8941 } 8942 break; 8943 8944 case ISD::OR: 8945 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8946 return (0x03020100 & ~ConstMask) | ConstMask; 8947 } 8948 break; 8949 8950 case ISD::SHL: 8951 if (C % 8) 8952 return ~0; 8953 8954 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8955 8956 case ISD::SRL: 8957 if (C % 8) 8958 return ~0; 8959 8960 return uint32_t(0x0c0c0c0c03020100ull >> C); 8961 } 8962 8963 return ~0; 8964 } 8965 8966 SDValue SITargetLowering::performAndCombine(SDNode *N, 8967 DAGCombinerInfo &DCI) const { 8968 if (DCI.isBeforeLegalize()) 8969 return SDValue(); 8970 8971 SelectionDAG &DAG = DCI.DAG; 8972 EVT VT = N->getValueType(0); 8973 SDValue LHS = N->getOperand(0); 8974 SDValue RHS = N->getOperand(1); 8975 8976 8977 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8978 if (VT == MVT::i64 && CRHS) { 8979 if (SDValue Split 8980 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8981 return Split; 8982 } 8983 8984 if (CRHS && VT == MVT::i32) { 8985 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8986 // nb = number of trailing zeroes in mask 8987 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8988 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8989 uint64_t Mask = CRHS->getZExtValue(); 8990 unsigned Bits = countPopulation(Mask); 8991 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8992 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8993 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8994 unsigned Shift = CShift->getZExtValue(); 8995 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8996 unsigned Offset = NB + Shift; 8997 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8998 SDLoc SL(N); 8999 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9000 LHS->getOperand(0), 9001 DAG.getConstant(Offset, SL, MVT::i32), 9002 DAG.getConstant(Bits, SL, MVT::i32)); 9003 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9004 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9005 DAG.getValueType(NarrowVT)); 9006 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9007 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9008 return Shl; 9009 } 9010 } 9011 } 9012 9013 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9014 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9015 isa<ConstantSDNode>(LHS.getOperand(2))) { 9016 uint32_t Sel = getConstantPermuteMask(Mask); 9017 if (!Sel) 9018 return SDValue(); 9019 9020 // Select 0xc for all zero bytes 9021 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9022 SDLoc DL(N); 9023 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9024 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9025 } 9026 } 9027 9028 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9029 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9030 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9031 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9032 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9033 9034 SDValue X = LHS.getOperand(0); 9035 SDValue Y = RHS.getOperand(0); 9036 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9037 return SDValue(); 9038 9039 if (LCC == ISD::SETO) { 9040 if (X != LHS.getOperand(1)) 9041 return SDValue(); 9042 9043 if (RCC == ISD::SETUNE) { 9044 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9045 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9046 return SDValue(); 9047 9048 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9049 SIInstrFlags::N_SUBNORMAL | 9050 SIInstrFlags::N_ZERO | 9051 SIInstrFlags::P_ZERO | 9052 SIInstrFlags::P_SUBNORMAL | 9053 SIInstrFlags::P_NORMAL; 9054 9055 static_assert(((~(SIInstrFlags::S_NAN | 9056 SIInstrFlags::Q_NAN | 9057 SIInstrFlags::N_INFINITY | 9058 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9059 "mask not equal"); 9060 9061 SDLoc DL(N); 9062 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9063 X, DAG.getConstant(Mask, DL, MVT::i32)); 9064 } 9065 } 9066 } 9067 9068 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9069 std::swap(LHS, RHS); 9070 9071 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9072 RHS.hasOneUse()) { 9073 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9074 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9075 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9076 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9077 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9078 (RHS.getOperand(0) == LHS.getOperand(0) && 9079 LHS.getOperand(0) == LHS.getOperand(1))) { 9080 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9081 unsigned NewMask = LCC == ISD::SETO ? 9082 Mask->getZExtValue() & ~OrdMask : 9083 Mask->getZExtValue() & OrdMask; 9084 9085 SDLoc DL(N); 9086 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9087 DAG.getConstant(NewMask, DL, MVT::i32)); 9088 } 9089 } 9090 9091 if (VT == MVT::i32 && 9092 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9093 // and x, (sext cc from i1) => select cc, x, 0 9094 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9095 std::swap(LHS, RHS); 9096 if (isBoolSGPR(RHS.getOperand(0))) 9097 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9098 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9099 } 9100 9101 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9102 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9103 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9104 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9105 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9106 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9107 if (LHSMask != ~0u && RHSMask != ~0u) { 9108 // Canonicalize the expression in an attempt to have fewer unique masks 9109 // and therefore fewer registers used to hold the masks. 9110 if (LHSMask > RHSMask) { 9111 std::swap(LHSMask, RHSMask); 9112 std::swap(LHS, RHS); 9113 } 9114 9115 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9116 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9117 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9118 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9119 9120 // Check of we need to combine values from two sources within a byte. 9121 if (!(LHSUsedLanes & RHSUsedLanes) && 9122 // If we select high and lower word keep it for SDWA. 9123 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9124 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9125 // Each byte in each mask is either selector mask 0-3, or has higher 9126 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9127 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9128 // mask which is not 0xff wins. By anding both masks we have a correct 9129 // result except that 0x0c shall be corrected to give 0x0c only. 9130 uint32_t Mask = LHSMask & RHSMask; 9131 for (unsigned I = 0; I < 32; I += 8) { 9132 uint32_t ByteSel = 0xff << I; 9133 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9134 Mask &= (0x0c << I) & 0xffffffff; 9135 } 9136 9137 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9138 // or 0x0c. 9139 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9140 SDLoc DL(N); 9141 9142 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9143 LHS.getOperand(0), RHS.getOperand(0), 9144 DAG.getConstant(Sel, DL, MVT::i32)); 9145 } 9146 } 9147 } 9148 9149 return SDValue(); 9150 } 9151 9152 SDValue SITargetLowering::performOrCombine(SDNode *N, 9153 DAGCombinerInfo &DCI) const { 9154 SelectionDAG &DAG = DCI.DAG; 9155 SDValue LHS = N->getOperand(0); 9156 SDValue RHS = N->getOperand(1); 9157 9158 EVT VT = N->getValueType(0); 9159 if (VT == MVT::i1) { 9160 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9161 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9162 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9163 SDValue Src = LHS.getOperand(0); 9164 if (Src != RHS.getOperand(0)) 9165 return SDValue(); 9166 9167 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9168 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9169 if (!CLHS || !CRHS) 9170 return SDValue(); 9171 9172 // Only 10 bits are used. 9173 static const uint32_t MaxMask = 0x3ff; 9174 9175 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9176 SDLoc DL(N); 9177 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9178 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9179 } 9180 9181 return SDValue(); 9182 } 9183 9184 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9185 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9186 LHS.getOpcode() == AMDGPUISD::PERM && 9187 isa<ConstantSDNode>(LHS.getOperand(2))) { 9188 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9189 if (!Sel) 9190 return SDValue(); 9191 9192 Sel |= LHS.getConstantOperandVal(2); 9193 SDLoc DL(N); 9194 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9195 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9196 } 9197 9198 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9199 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9200 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9201 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 9202 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9203 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9204 if (LHSMask != ~0u && RHSMask != ~0u) { 9205 // Canonicalize the expression in an attempt to have fewer unique masks 9206 // and therefore fewer registers used to hold the masks. 9207 if (LHSMask > RHSMask) { 9208 std::swap(LHSMask, RHSMask); 9209 std::swap(LHS, RHS); 9210 } 9211 9212 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9213 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9214 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9215 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9216 9217 // Check of we need to combine values from two sources within a byte. 9218 if (!(LHSUsedLanes & RHSUsedLanes) && 9219 // If we select high and lower word keep it for SDWA. 9220 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9221 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9222 // Kill zero bytes selected by other mask. Zero value is 0xc. 9223 LHSMask &= ~RHSUsedLanes; 9224 RHSMask &= ~LHSUsedLanes; 9225 // Add 4 to each active LHS lane 9226 LHSMask |= LHSUsedLanes & 0x04040404; 9227 // Combine masks 9228 uint32_t Sel = LHSMask | RHSMask; 9229 SDLoc DL(N); 9230 9231 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9232 LHS.getOperand(0), RHS.getOperand(0), 9233 DAG.getConstant(Sel, DL, MVT::i32)); 9234 } 9235 } 9236 } 9237 9238 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9239 return SDValue(); 9240 9241 // TODO: This could be a generic combine with a predicate for extracting the 9242 // high half of an integer being free. 9243 9244 // (or i64:x, (zero_extend i32:y)) -> 9245 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9246 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9247 RHS.getOpcode() != ISD::ZERO_EXTEND) 9248 std::swap(LHS, RHS); 9249 9250 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9251 SDValue ExtSrc = RHS.getOperand(0); 9252 EVT SrcVT = ExtSrc.getValueType(); 9253 if (SrcVT == MVT::i32) { 9254 SDLoc SL(N); 9255 SDValue LowLHS, HiBits; 9256 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9257 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9258 9259 DCI.AddToWorklist(LowOr.getNode()); 9260 DCI.AddToWorklist(HiBits.getNode()); 9261 9262 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9263 LowOr, HiBits); 9264 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9265 } 9266 } 9267 9268 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9269 if (CRHS) { 9270 if (SDValue Split 9271 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9272 return Split; 9273 } 9274 9275 return SDValue(); 9276 } 9277 9278 SDValue SITargetLowering::performXorCombine(SDNode *N, 9279 DAGCombinerInfo &DCI) const { 9280 EVT VT = N->getValueType(0); 9281 if (VT != MVT::i64) 9282 return SDValue(); 9283 9284 SDValue LHS = N->getOperand(0); 9285 SDValue RHS = N->getOperand(1); 9286 9287 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9288 if (CRHS) { 9289 if (SDValue Split 9290 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9291 return Split; 9292 } 9293 9294 return SDValue(); 9295 } 9296 9297 // Instructions that will be lowered with a final instruction that zeros the 9298 // high result bits. 9299 // XXX - probably only need to list legal operations. 9300 static bool fp16SrcZerosHighBits(unsigned Opc) { 9301 switch (Opc) { 9302 case ISD::FADD: 9303 case ISD::FSUB: 9304 case ISD::FMUL: 9305 case ISD::FDIV: 9306 case ISD::FREM: 9307 case ISD::FMA: 9308 case ISD::FMAD: 9309 case ISD::FCANONICALIZE: 9310 case ISD::FP_ROUND: 9311 case ISD::UINT_TO_FP: 9312 case ISD::SINT_TO_FP: 9313 case ISD::FABS: 9314 // Fabs is lowered to a bit operation, but it's an and which will clear the 9315 // high bits anyway. 9316 case ISD::FSQRT: 9317 case ISD::FSIN: 9318 case ISD::FCOS: 9319 case ISD::FPOWI: 9320 case ISD::FPOW: 9321 case ISD::FLOG: 9322 case ISD::FLOG2: 9323 case ISD::FLOG10: 9324 case ISD::FEXP: 9325 case ISD::FEXP2: 9326 case ISD::FCEIL: 9327 case ISD::FTRUNC: 9328 case ISD::FRINT: 9329 case ISD::FNEARBYINT: 9330 case ISD::FROUND: 9331 case ISD::FFLOOR: 9332 case ISD::FMINNUM: 9333 case ISD::FMAXNUM: 9334 case AMDGPUISD::FRACT: 9335 case AMDGPUISD::CLAMP: 9336 case AMDGPUISD::COS_HW: 9337 case AMDGPUISD::SIN_HW: 9338 case AMDGPUISD::FMIN3: 9339 case AMDGPUISD::FMAX3: 9340 case AMDGPUISD::FMED3: 9341 case AMDGPUISD::FMAD_FTZ: 9342 case AMDGPUISD::RCP: 9343 case AMDGPUISD::RSQ: 9344 case AMDGPUISD::RCP_IFLAG: 9345 case AMDGPUISD::LDEXP: 9346 return true; 9347 default: 9348 // fcopysign, select and others may be lowered to 32-bit bit operations 9349 // which don't zero the high bits. 9350 return false; 9351 } 9352 } 9353 9354 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9355 DAGCombinerInfo &DCI) const { 9356 if (!Subtarget->has16BitInsts() || 9357 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9358 return SDValue(); 9359 9360 EVT VT = N->getValueType(0); 9361 if (VT != MVT::i32) 9362 return SDValue(); 9363 9364 SDValue Src = N->getOperand(0); 9365 if (Src.getValueType() != MVT::i16) 9366 return SDValue(); 9367 9368 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9369 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9370 if (Src.getOpcode() == ISD::BITCAST) { 9371 SDValue BCSrc = Src.getOperand(0); 9372 if (BCSrc.getValueType() == MVT::f16 && 9373 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9374 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9375 } 9376 9377 return SDValue(); 9378 } 9379 9380 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9381 DAGCombinerInfo &DCI) 9382 const { 9383 SDValue Src = N->getOperand(0); 9384 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9385 9386 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9387 VTSign->getVT() == MVT::i8) || 9388 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9389 VTSign->getVT() == MVT::i16)) && 9390 Src.hasOneUse()) { 9391 auto *M = cast<MemSDNode>(Src); 9392 SDValue Ops[] = { 9393 Src.getOperand(0), // Chain 9394 Src.getOperand(1), // rsrc 9395 Src.getOperand(2), // vindex 9396 Src.getOperand(3), // voffset 9397 Src.getOperand(4), // soffset 9398 Src.getOperand(5), // offset 9399 Src.getOperand(6), 9400 Src.getOperand(7) 9401 }; 9402 // replace with BUFFER_LOAD_BYTE/SHORT 9403 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9404 Src.getOperand(0).getValueType()); 9405 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9406 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9407 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9408 ResList, 9409 Ops, M->getMemoryVT(), 9410 M->getMemOperand()); 9411 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9412 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9413 } 9414 return SDValue(); 9415 } 9416 9417 SDValue SITargetLowering::performClassCombine(SDNode *N, 9418 DAGCombinerInfo &DCI) const { 9419 SelectionDAG &DAG = DCI.DAG; 9420 SDValue Mask = N->getOperand(1); 9421 9422 // fp_class x, 0 -> false 9423 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9424 if (CMask->isNullValue()) 9425 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9426 } 9427 9428 if (N->getOperand(0).isUndef()) 9429 return DAG.getUNDEF(MVT::i1); 9430 9431 return SDValue(); 9432 } 9433 9434 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9435 DAGCombinerInfo &DCI) const { 9436 EVT VT = N->getValueType(0); 9437 SDValue N0 = N->getOperand(0); 9438 9439 if (N0.isUndef()) 9440 return N0; 9441 9442 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9443 N0.getOpcode() == ISD::SINT_TO_FP)) { 9444 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9445 N->getFlags()); 9446 } 9447 9448 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9449 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9450 N0.getOperand(0), N->getFlags()); 9451 } 9452 9453 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9454 } 9455 9456 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9457 unsigned MaxDepth) const { 9458 unsigned Opcode = Op.getOpcode(); 9459 if (Opcode == ISD::FCANONICALIZE) 9460 return true; 9461 9462 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9463 auto F = CFP->getValueAPF(); 9464 if (F.isNaN() && F.isSignaling()) 9465 return false; 9466 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9467 } 9468 9469 // If source is a result of another standard FP operation it is already in 9470 // canonical form. 9471 if (MaxDepth == 0) 9472 return false; 9473 9474 switch (Opcode) { 9475 // These will flush denorms if required. 9476 case ISD::FADD: 9477 case ISD::FSUB: 9478 case ISD::FMUL: 9479 case ISD::FCEIL: 9480 case ISD::FFLOOR: 9481 case ISD::FMA: 9482 case ISD::FMAD: 9483 case ISD::FSQRT: 9484 case ISD::FDIV: 9485 case ISD::FREM: 9486 case ISD::FP_ROUND: 9487 case ISD::FP_EXTEND: 9488 case AMDGPUISD::FMUL_LEGACY: 9489 case AMDGPUISD::FMAD_FTZ: 9490 case AMDGPUISD::RCP: 9491 case AMDGPUISD::RSQ: 9492 case AMDGPUISD::RSQ_CLAMP: 9493 case AMDGPUISD::RCP_LEGACY: 9494 case AMDGPUISD::RCP_IFLAG: 9495 case AMDGPUISD::DIV_SCALE: 9496 case AMDGPUISD::DIV_FMAS: 9497 case AMDGPUISD::DIV_FIXUP: 9498 case AMDGPUISD::FRACT: 9499 case AMDGPUISD::LDEXP: 9500 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9501 case AMDGPUISD::CVT_F32_UBYTE0: 9502 case AMDGPUISD::CVT_F32_UBYTE1: 9503 case AMDGPUISD::CVT_F32_UBYTE2: 9504 case AMDGPUISD::CVT_F32_UBYTE3: 9505 return true; 9506 9507 // It can/will be lowered or combined as a bit operation. 9508 // Need to check their input recursively to handle. 9509 case ISD::FNEG: 9510 case ISD::FABS: 9511 case ISD::FCOPYSIGN: 9512 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9513 9514 case ISD::FSIN: 9515 case ISD::FCOS: 9516 case ISD::FSINCOS: 9517 return Op.getValueType().getScalarType() != MVT::f16; 9518 9519 case ISD::FMINNUM: 9520 case ISD::FMAXNUM: 9521 case ISD::FMINNUM_IEEE: 9522 case ISD::FMAXNUM_IEEE: 9523 case AMDGPUISD::CLAMP: 9524 case AMDGPUISD::FMED3: 9525 case AMDGPUISD::FMAX3: 9526 case AMDGPUISD::FMIN3: { 9527 // FIXME: Shouldn't treat the generic operations different based these. 9528 // However, we aren't really required to flush the result from 9529 // minnum/maxnum.. 9530 9531 // snans will be quieted, so we only need to worry about denormals. 9532 if (Subtarget->supportsMinMaxDenormModes() || 9533 denormalsEnabledForType(DAG, Op.getValueType())) 9534 return true; 9535 9536 // Flushing may be required. 9537 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9538 // targets need to check their input recursively. 9539 9540 // FIXME: Does this apply with clamp? It's implemented with max. 9541 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9542 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9543 return false; 9544 } 9545 9546 return true; 9547 } 9548 case ISD::SELECT: { 9549 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9550 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9551 } 9552 case ISD::BUILD_VECTOR: { 9553 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9554 SDValue SrcOp = Op.getOperand(i); 9555 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9556 return false; 9557 } 9558 9559 return true; 9560 } 9561 case ISD::EXTRACT_VECTOR_ELT: 9562 case ISD::EXTRACT_SUBVECTOR: { 9563 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9564 } 9565 case ISD::INSERT_VECTOR_ELT: { 9566 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9567 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9568 } 9569 case ISD::UNDEF: 9570 // Could be anything. 9571 return false; 9572 9573 case ISD::BITCAST: { 9574 // Hack round the mess we make when legalizing extract_vector_elt 9575 SDValue Src = Op.getOperand(0); 9576 if (Src.getValueType() == MVT::i16 && 9577 Src.getOpcode() == ISD::TRUNCATE) { 9578 SDValue TruncSrc = Src.getOperand(0); 9579 if (TruncSrc.getValueType() == MVT::i32 && 9580 TruncSrc.getOpcode() == ISD::BITCAST && 9581 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9582 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9583 } 9584 } 9585 9586 return false; 9587 } 9588 case ISD::INTRINSIC_WO_CHAIN: { 9589 unsigned IntrinsicID 9590 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9591 // TODO: Handle more intrinsics 9592 switch (IntrinsicID) { 9593 case Intrinsic::amdgcn_cvt_pkrtz: 9594 case Intrinsic::amdgcn_cubeid: 9595 case Intrinsic::amdgcn_frexp_mant: 9596 case Intrinsic::amdgcn_fdot2: 9597 case Intrinsic::amdgcn_rcp: 9598 case Intrinsic::amdgcn_rsq: 9599 case Intrinsic::amdgcn_rsq_clamp: 9600 case Intrinsic::amdgcn_rcp_legacy: 9601 case Intrinsic::amdgcn_rsq_legacy: 9602 case Intrinsic::amdgcn_trig_preop: 9603 return true; 9604 default: 9605 break; 9606 } 9607 9608 LLVM_FALLTHROUGH; 9609 } 9610 default: 9611 return denormalsEnabledForType(DAG, Op.getValueType()) && 9612 DAG.isKnownNeverSNaN(Op); 9613 } 9614 9615 llvm_unreachable("invalid operation"); 9616 } 9617 9618 // Constant fold canonicalize. 9619 SDValue SITargetLowering::getCanonicalConstantFP( 9620 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9621 // Flush denormals to 0 if not enabled. 9622 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9623 return DAG.getConstantFP(0.0, SL, VT); 9624 9625 if (C.isNaN()) { 9626 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9627 if (C.isSignaling()) { 9628 // Quiet a signaling NaN. 9629 // FIXME: Is this supposed to preserve payload bits? 9630 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9631 } 9632 9633 // Make sure it is the canonical NaN bitpattern. 9634 // 9635 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9636 // immediate? 9637 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9638 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9639 } 9640 9641 // Already canonical. 9642 return DAG.getConstantFP(C, SL, VT); 9643 } 9644 9645 static bool vectorEltWillFoldAway(SDValue Op) { 9646 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9647 } 9648 9649 SDValue SITargetLowering::performFCanonicalizeCombine( 9650 SDNode *N, 9651 DAGCombinerInfo &DCI) const { 9652 SelectionDAG &DAG = DCI.DAG; 9653 SDValue N0 = N->getOperand(0); 9654 EVT VT = N->getValueType(0); 9655 9656 // fcanonicalize undef -> qnan 9657 if (N0.isUndef()) { 9658 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9659 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9660 } 9661 9662 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9663 EVT VT = N->getValueType(0); 9664 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9665 } 9666 9667 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9668 // (fcanonicalize k) 9669 // 9670 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9671 9672 // TODO: This could be better with wider vectors that will be split to v2f16, 9673 // and to consider uses since there aren't that many packed operations. 9674 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9675 isTypeLegal(MVT::v2f16)) { 9676 SDLoc SL(N); 9677 SDValue NewElts[2]; 9678 SDValue Lo = N0.getOperand(0); 9679 SDValue Hi = N0.getOperand(1); 9680 EVT EltVT = Lo.getValueType(); 9681 9682 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9683 for (unsigned I = 0; I != 2; ++I) { 9684 SDValue Op = N0.getOperand(I); 9685 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9686 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9687 CFP->getValueAPF()); 9688 } else if (Op.isUndef()) { 9689 // Handled below based on what the other operand is. 9690 NewElts[I] = Op; 9691 } else { 9692 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9693 } 9694 } 9695 9696 // If one half is undef, and one is constant, perfer a splat vector rather 9697 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9698 // cheaper to use and may be free with a packed operation. 9699 if (NewElts[0].isUndef()) { 9700 if (isa<ConstantFPSDNode>(NewElts[1])) 9701 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9702 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9703 } 9704 9705 if (NewElts[1].isUndef()) { 9706 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9707 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9708 } 9709 9710 return DAG.getBuildVector(VT, SL, NewElts); 9711 } 9712 } 9713 9714 unsigned SrcOpc = N0.getOpcode(); 9715 9716 // If it's free to do so, push canonicalizes further up the source, which may 9717 // find a canonical source. 9718 // 9719 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9720 // sNaNs. 9721 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9722 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9723 if (CRHS && N0.hasOneUse()) { 9724 SDLoc SL(N); 9725 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9726 N0.getOperand(0)); 9727 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9728 DCI.AddToWorklist(Canon0.getNode()); 9729 9730 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9731 } 9732 } 9733 9734 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9735 } 9736 9737 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9738 switch (Opc) { 9739 case ISD::FMAXNUM: 9740 case ISD::FMAXNUM_IEEE: 9741 return AMDGPUISD::FMAX3; 9742 case ISD::SMAX: 9743 return AMDGPUISD::SMAX3; 9744 case ISD::UMAX: 9745 return AMDGPUISD::UMAX3; 9746 case ISD::FMINNUM: 9747 case ISD::FMINNUM_IEEE: 9748 return AMDGPUISD::FMIN3; 9749 case ISD::SMIN: 9750 return AMDGPUISD::SMIN3; 9751 case ISD::UMIN: 9752 return AMDGPUISD::UMIN3; 9753 default: 9754 llvm_unreachable("Not a min/max opcode"); 9755 } 9756 } 9757 9758 SDValue SITargetLowering::performIntMed3ImmCombine( 9759 SelectionDAG &DAG, const SDLoc &SL, 9760 SDValue Op0, SDValue Op1, bool Signed) const { 9761 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9762 if (!K1) 9763 return SDValue(); 9764 9765 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9766 if (!K0) 9767 return SDValue(); 9768 9769 if (Signed) { 9770 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9771 return SDValue(); 9772 } else { 9773 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9774 return SDValue(); 9775 } 9776 9777 EVT VT = K0->getValueType(0); 9778 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9779 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9780 return DAG.getNode(Med3Opc, SL, VT, 9781 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9782 } 9783 9784 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9785 MVT NVT = MVT::i32; 9786 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9787 9788 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9789 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9790 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9791 9792 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9793 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9794 } 9795 9796 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9797 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9798 return C; 9799 9800 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9801 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9802 return C; 9803 } 9804 9805 return nullptr; 9806 } 9807 9808 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9809 const SDLoc &SL, 9810 SDValue Op0, 9811 SDValue Op1) const { 9812 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9813 if (!K1) 9814 return SDValue(); 9815 9816 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9817 if (!K0) 9818 return SDValue(); 9819 9820 // Ordered >= (although NaN inputs should have folded away by now). 9821 if (K0->getValueAPF() > K1->getValueAPF()) 9822 return SDValue(); 9823 9824 const MachineFunction &MF = DAG.getMachineFunction(); 9825 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9826 9827 // TODO: Check IEEE bit enabled? 9828 EVT VT = Op0.getValueType(); 9829 if (Info->getMode().DX10Clamp) { 9830 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9831 // hardware fmed3 behavior converting to a min. 9832 // FIXME: Should this be allowing -0.0? 9833 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9834 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9835 } 9836 9837 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9838 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9839 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9840 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9841 // then give the other result, which is different from med3 with a NaN 9842 // input. 9843 SDValue Var = Op0.getOperand(0); 9844 if (!DAG.isKnownNeverSNaN(Var)) 9845 return SDValue(); 9846 9847 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9848 9849 if ((!K0->hasOneUse() || 9850 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9851 (!K1->hasOneUse() || 9852 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9853 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9854 Var, SDValue(K0, 0), SDValue(K1, 0)); 9855 } 9856 } 9857 9858 return SDValue(); 9859 } 9860 9861 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9862 DAGCombinerInfo &DCI) const { 9863 SelectionDAG &DAG = DCI.DAG; 9864 9865 EVT VT = N->getValueType(0); 9866 unsigned Opc = N->getOpcode(); 9867 SDValue Op0 = N->getOperand(0); 9868 SDValue Op1 = N->getOperand(1); 9869 9870 // Only do this if the inner op has one use since this will just increases 9871 // register pressure for no benefit. 9872 9873 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9874 !VT.isVector() && 9875 (VT == MVT::i32 || VT == MVT::f32 || 9876 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9877 // max(max(a, b), c) -> max3(a, b, c) 9878 // min(min(a, b), c) -> min3(a, b, c) 9879 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9880 SDLoc DL(N); 9881 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9882 DL, 9883 N->getValueType(0), 9884 Op0.getOperand(0), 9885 Op0.getOperand(1), 9886 Op1); 9887 } 9888 9889 // Try commuted. 9890 // max(a, max(b, c)) -> max3(a, b, c) 9891 // min(a, min(b, c)) -> min3(a, b, c) 9892 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9893 SDLoc DL(N); 9894 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9895 DL, 9896 N->getValueType(0), 9897 Op0, 9898 Op1.getOperand(0), 9899 Op1.getOperand(1)); 9900 } 9901 } 9902 9903 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9904 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9905 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9906 return Med3; 9907 } 9908 9909 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9910 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9911 return Med3; 9912 } 9913 9914 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9915 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9916 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9917 (Opc == AMDGPUISD::FMIN_LEGACY && 9918 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9919 (VT == MVT::f32 || VT == MVT::f64 || 9920 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9921 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9922 Op0.hasOneUse()) { 9923 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9924 return Res; 9925 } 9926 9927 return SDValue(); 9928 } 9929 9930 static bool isClampZeroToOne(SDValue A, SDValue B) { 9931 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9932 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9933 // FIXME: Should this be allowing -0.0? 9934 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9935 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9936 } 9937 } 9938 9939 return false; 9940 } 9941 9942 // FIXME: Should only worry about snans for version with chain. 9943 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9944 DAGCombinerInfo &DCI) const { 9945 EVT VT = N->getValueType(0); 9946 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9947 // NaNs. With a NaN input, the order of the operands may change the result. 9948 9949 SelectionDAG &DAG = DCI.DAG; 9950 SDLoc SL(N); 9951 9952 SDValue Src0 = N->getOperand(0); 9953 SDValue Src1 = N->getOperand(1); 9954 SDValue Src2 = N->getOperand(2); 9955 9956 if (isClampZeroToOne(Src0, Src1)) { 9957 // const_a, const_b, x -> clamp is safe in all cases including signaling 9958 // nans. 9959 // FIXME: Should this be allowing -0.0? 9960 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9961 } 9962 9963 const MachineFunction &MF = DAG.getMachineFunction(); 9964 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9965 9966 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9967 // handling no dx10-clamp? 9968 if (Info->getMode().DX10Clamp) { 9969 // If NaNs is clamped to 0, we are free to reorder the inputs. 9970 9971 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9972 std::swap(Src0, Src1); 9973 9974 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9975 std::swap(Src1, Src2); 9976 9977 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9978 std::swap(Src0, Src1); 9979 9980 if (isClampZeroToOne(Src1, Src2)) 9981 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9982 } 9983 9984 return SDValue(); 9985 } 9986 9987 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9988 DAGCombinerInfo &DCI) const { 9989 SDValue Src0 = N->getOperand(0); 9990 SDValue Src1 = N->getOperand(1); 9991 if (Src0.isUndef() && Src1.isUndef()) 9992 return DCI.DAG.getUNDEF(N->getValueType(0)); 9993 return SDValue(); 9994 } 9995 9996 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9997 // expanded into a set of cmp/select instructions. 9998 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9999 unsigned NumElem, 10000 bool IsDivergentIdx) { 10001 if (UseDivergentRegisterIndexing) 10002 return false; 10003 10004 unsigned VecSize = EltSize * NumElem; 10005 10006 // Sub-dword vectors of size 2 dword or less have better implementation. 10007 if (VecSize <= 64 && EltSize < 32) 10008 return false; 10009 10010 // Always expand the rest of sub-dword instructions, otherwise it will be 10011 // lowered via memory. 10012 if (EltSize < 32) 10013 return true; 10014 10015 // Always do this if var-idx is divergent, otherwise it will become a loop. 10016 if (IsDivergentIdx) 10017 return true; 10018 10019 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10020 unsigned NumInsts = NumElem /* Number of compares */ + 10021 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10022 return NumInsts <= 16; 10023 } 10024 10025 static bool shouldExpandVectorDynExt(SDNode *N) { 10026 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10027 if (isa<ConstantSDNode>(Idx)) 10028 return false; 10029 10030 SDValue Vec = N->getOperand(0); 10031 EVT VecVT = Vec.getValueType(); 10032 EVT EltVT = VecVT.getVectorElementType(); 10033 unsigned EltSize = EltVT.getSizeInBits(); 10034 unsigned NumElem = VecVT.getVectorNumElements(); 10035 10036 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10037 Idx->isDivergent()); 10038 } 10039 10040 SDValue SITargetLowering::performExtractVectorEltCombine( 10041 SDNode *N, DAGCombinerInfo &DCI) const { 10042 SDValue Vec = N->getOperand(0); 10043 SelectionDAG &DAG = DCI.DAG; 10044 10045 EVT VecVT = Vec.getValueType(); 10046 EVT EltVT = VecVT.getVectorElementType(); 10047 10048 if ((Vec.getOpcode() == ISD::FNEG || 10049 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10050 SDLoc SL(N); 10051 EVT EltVT = N->getValueType(0); 10052 SDValue Idx = N->getOperand(1); 10053 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10054 Vec.getOperand(0), Idx); 10055 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10056 } 10057 10058 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10059 // => 10060 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10061 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10062 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10063 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10064 SDLoc SL(N); 10065 EVT EltVT = N->getValueType(0); 10066 SDValue Idx = N->getOperand(1); 10067 unsigned Opc = Vec.getOpcode(); 10068 10069 switch(Opc) { 10070 default: 10071 break; 10072 // TODO: Support other binary operations. 10073 case ISD::FADD: 10074 case ISD::FSUB: 10075 case ISD::FMUL: 10076 case ISD::ADD: 10077 case ISD::UMIN: 10078 case ISD::UMAX: 10079 case ISD::SMIN: 10080 case ISD::SMAX: 10081 case ISD::FMAXNUM: 10082 case ISD::FMINNUM: 10083 case ISD::FMAXNUM_IEEE: 10084 case ISD::FMINNUM_IEEE: { 10085 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10086 Vec.getOperand(0), Idx); 10087 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10088 Vec.getOperand(1), Idx); 10089 10090 DCI.AddToWorklist(Elt0.getNode()); 10091 DCI.AddToWorklist(Elt1.getNode()); 10092 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10093 } 10094 } 10095 } 10096 10097 unsigned VecSize = VecVT.getSizeInBits(); 10098 unsigned EltSize = EltVT.getSizeInBits(); 10099 10100 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10101 if (::shouldExpandVectorDynExt(N)) { 10102 SDLoc SL(N); 10103 SDValue Idx = N->getOperand(1); 10104 SDValue V; 10105 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10106 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10107 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10108 if (I == 0) 10109 V = Elt; 10110 else 10111 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10112 } 10113 return V; 10114 } 10115 10116 if (!DCI.isBeforeLegalize()) 10117 return SDValue(); 10118 10119 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10120 // elements. This exposes more load reduction opportunities by replacing 10121 // multiple small extract_vector_elements with a single 32-bit extract. 10122 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10123 if (isa<MemSDNode>(Vec) && 10124 EltSize <= 16 && 10125 EltVT.isByteSized() && 10126 VecSize > 32 && 10127 VecSize % 32 == 0 && 10128 Idx) { 10129 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10130 10131 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10132 unsigned EltIdx = BitIndex / 32; 10133 unsigned LeftoverBitIdx = BitIndex % 32; 10134 SDLoc SL(N); 10135 10136 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10137 DCI.AddToWorklist(Cast.getNode()); 10138 10139 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10140 DAG.getConstant(EltIdx, SL, MVT::i32)); 10141 DCI.AddToWorklist(Elt.getNode()); 10142 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10143 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10144 DCI.AddToWorklist(Srl.getNode()); 10145 10146 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10147 DCI.AddToWorklist(Trunc.getNode()); 10148 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10149 } 10150 10151 return SDValue(); 10152 } 10153 10154 SDValue 10155 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10156 DAGCombinerInfo &DCI) const { 10157 SDValue Vec = N->getOperand(0); 10158 SDValue Idx = N->getOperand(2); 10159 EVT VecVT = Vec.getValueType(); 10160 EVT EltVT = VecVT.getVectorElementType(); 10161 10162 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10163 // => BUILD_VECTOR n x select (e, const-idx) 10164 if (!::shouldExpandVectorDynExt(N)) 10165 return SDValue(); 10166 10167 SelectionDAG &DAG = DCI.DAG; 10168 SDLoc SL(N); 10169 SDValue Ins = N->getOperand(1); 10170 EVT IdxVT = Idx.getValueType(); 10171 10172 SmallVector<SDValue, 16> Ops; 10173 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10174 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10175 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10176 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10177 Ops.push_back(V); 10178 } 10179 10180 return DAG.getBuildVector(VecVT, SL, Ops); 10181 } 10182 10183 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10184 const SDNode *N0, 10185 const SDNode *N1) const { 10186 EVT VT = N0->getValueType(0); 10187 10188 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10189 // support denormals ever. 10190 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10191 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10192 getSubtarget()->hasMadF16())) && 10193 isOperationLegal(ISD::FMAD, VT)) 10194 return ISD::FMAD; 10195 10196 const TargetOptions &Options = DAG.getTarget().Options; 10197 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10198 (N0->getFlags().hasAllowContract() && 10199 N1->getFlags().hasAllowContract())) && 10200 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10201 return ISD::FMA; 10202 } 10203 10204 return 0; 10205 } 10206 10207 // For a reassociatable opcode perform: 10208 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10209 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10210 SelectionDAG &DAG) const { 10211 EVT VT = N->getValueType(0); 10212 if (VT != MVT::i32 && VT != MVT::i64) 10213 return SDValue(); 10214 10215 unsigned Opc = N->getOpcode(); 10216 SDValue Op0 = N->getOperand(0); 10217 SDValue Op1 = N->getOperand(1); 10218 10219 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10220 return SDValue(); 10221 10222 if (Op0->isDivergent()) 10223 std::swap(Op0, Op1); 10224 10225 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10226 return SDValue(); 10227 10228 SDValue Op2 = Op1.getOperand(1); 10229 Op1 = Op1.getOperand(0); 10230 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10231 return SDValue(); 10232 10233 if (Op1->isDivergent()) 10234 std::swap(Op1, Op2); 10235 10236 // If either operand is constant this will conflict with 10237 // DAGCombiner::ReassociateOps(). 10238 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10239 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10240 return SDValue(); 10241 10242 SDLoc SL(N); 10243 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10244 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10245 } 10246 10247 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10248 EVT VT, 10249 SDValue N0, SDValue N1, SDValue N2, 10250 bool Signed) { 10251 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10252 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10253 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10254 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10255 } 10256 10257 SDValue SITargetLowering::performAddCombine(SDNode *N, 10258 DAGCombinerInfo &DCI) const { 10259 SelectionDAG &DAG = DCI.DAG; 10260 EVT VT = N->getValueType(0); 10261 SDLoc SL(N); 10262 SDValue LHS = N->getOperand(0); 10263 SDValue RHS = N->getOperand(1); 10264 10265 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10266 && Subtarget->hasMad64_32() && 10267 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10268 VT.getScalarSizeInBits() <= 64) { 10269 if (LHS.getOpcode() != ISD::MUL) 10270 std::swap(LHS, RHS); 10271 10272 SDValue MulLHS = LHS.getOperand(0); 10273 SDValue MulRHS = LHS.getOperand(1); 10274 SDValue AddRHS = RHS; 10275 10276 // TODO: Maybe restrict if SGPR inputs. 10277 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10278 numBitsUnsigned(MulRHS, DAG) <= 32) { 10279 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10280 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10281 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10282 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10283 } 10284 10285 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10286 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10287 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10288 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10289 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10290 } 10291 10292 return SDValue(); 10293 } 10294 10295 if (SDValue V = reassociateScalarOps(N, DAG)) { 10296 return V; 10297 } 10298 10299 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10300 return SDValue(); 10301 10302 // add x, zext (setcc) => addcarry x, 0, setcc 10303 // add x, sext (setcc) => subcarry x, 0, setcc 10304 unsigned Opc = LHS.getOpcode(); 10305 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10306 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10307 std::swap(RHS, LHS); 10308 10309 Opc = RHS.getOpcode(); 10310 switch (Opc) { 10311 default: break; 10312 case ISD::ZERO_EXTEND: 10313 case ISD::SIGN_EXTEND: 10314 case ISD::ANY_EXTEND: { 10315 auto Cond = RHS.getOperand(0); 10316 // If this won't be a real VOPC output, we would still need to insert an 10317 // extra instruction anyway. 10318 if (!isBoolSGPR(Cond)) 10319 break; 10320 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10321 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10322 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10323 return DAG.getNode(Opc, SL, VTList, Args); 10324 } 10325 case ISD::ADDCARRY: { 10326 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10327 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10328 if (!C || C->getZExtValue() != 0) break; 10329 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10330 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10331 } 10332 } 10333 return SDValue(); 10334 } 10335 10336 SDValue SITargetLowering::performSubCombine(SDNode *N, 10337 DAGCombinerInfo &DCI) const { 10338 SelectionDAG &DAG = DCI.DAG; 10339 EVT VT = N->getValueType(0); 10340 10341 if (VT != MVT::i32) 10342 return SDValue(); 10343 10344 SDLoc SL(N); 10345 SDValue LHS = N->getOperand(0); 10346 SDValue RHS = N->getOperand(1); 10347 10348 // sub x, zext (setcc) => subcarry x, 0, setcc 10349 // sub x, sext (setcc) => addcarry x, 0, setcc 10350 unsigned Opc = RHS.getOpcode(); 10351 switch (Opc) { 10352 default: break; 10353 case ISD::ZERO_EXTEND: 10354 case ISD::SIGN_EXTEND: 10355 case ISD::ANY_EXTEND: { 10356 auto Cond = RHS.getOperand(0); 10357 // If this won't be a real VOPC output, we would still need to insert an 10358 // extra instruction anyway. 10359 if (!isBoolSGPR(Cond)) 10360 break; 10361 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10362 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10363 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10364 return DAG.getNode(Opc, SL, VTList, Args); 10365 } 10366 } 10367 10368 if (LHS.getOpcode() == ISD::SUBCARRY) { 10369 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10370 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10371 if (!C || !C->isNullValue()) 10372 return SDValue(); 10373 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10374 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10375 } 10376 return SDValue(); 10377 } 10378 10379 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10380 DAGCombinerInfo &DCI) const { 10381 10382 if (N->getValueType(0) != MVT::i32) 10383 return SDValue(); 10384 10385 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10386 if (!C || C->getZExtValue() != 0) 10387 return SDValue(); 10388 10389 SelectionDAG &DAG = DCI.DAG; 10390 SDValue LHS = N->getOperand(0); 10391 10392 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10393 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10394 unsigned LHSOpc = LHS.getOpcode(); 10395 unsigned Opc = N->getOpcode(); 10396 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10397 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10398 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10399 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10400 } 10401 return SDValue(); 10402 } 10403 10404 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10405 DAGCombinerInfo &DCI) const { 10406 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10407 return SDValue(); 10408 10409 SelectionDAG &DAG = DCI.DAG; 10410 EVT VT = N->getValueType(0); 10411 10412 SDLoc SL(N); 10413 SDValue LHS = N->getOperand(0); 10414 SDValue RHS = N->getOperand(1); 10415 10416 // These should really be instruction patterns, but writing patterns with 10417 // source modiifiers is a pain. 10418 10419 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10420 if (LHS.getOpcode() == ISD::FADD) { 10421 SDValue A = LHS.getOperand(0); 10422 if (A == LHS.getOperand(1)) { 10423 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10424 if (FusedOp != 0) { 10425 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10426 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10427 } 10428 } 10429 } 10430 10431 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10432 if (RHS.getOpcode() == ISD::FADD) { 10433 SDValue A = RHS.getOperand(0); 10434 if (A == RHS.getOperand(1)) { 10435 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10436 if (FusedOp != 0) { 10437 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10438 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10439 } 10440 } 10441 } 10442 10443 return SDValue(); 10444 } 10445 10446 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10447 DAGCombinerInfo &DCI) const { 10448 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10449 return SDValue(); 10450 10451 SelectionDAG &DAG = DCI.DAG; 10452 SDLoc SL(N); 10453 EVT VT = N->getValueType(0); 10454 assert(!VT.isVector()); 10455 10456 // Try to get the fneg to fold into the source modifier. This undoes generic 10457 // DAG combines and folds them into the mad. 10458 // 10459 // Only do this if we are not trying to support denormals. v_mad_f32 does 10460 // not support denormals ever. 10461 SDValue LHS = N->getOperand(0); 10462 SDValue RHS = N->getOperand(1); 10463 if (LHS.getOpcode() == ISD::FADD) { 10464 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10465 SDValue A = LHS.getOperand(0); 10466 if (A == LHS.getOperand(1)) { 10467 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10468 if (FusedOp != 0){ 10469 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10470 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10471 10472 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10473 } 10474 } 10475 } 10476 10477 if (RHS.getOpcode() == ISD::FADD) { 10478 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10479 10480 SDValue A = RHS.getOperand(0); 10481 if (A == RHS.getOperand(1)) { 10482 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10483 if (FusedOp != 0){ 10484 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10485 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10486 } 10487 } 10488 } 10489 10490 return SDValue(); 10491 } 10492 10493 SDValue SITargetLowering::performFMACombine(SDNode *N, 10494 DAGCombinerInfo &DCI) const { 10495 SelectionDAG &DAG = DCI.DAG; 10496 EVT VT = N->getValueType(0); 10497 SDLoc SL(N); 10498 10499 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 10500 return SDValue(); 10501 10502 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10503 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10504 SDValue Op1 = N->getOperand(0); 10505 SDValue Op2 = N->getOperand(1); 10506 SDValue FMA = N->getOperand(2); 10507 10508 if (FMA.getOpcode() != ISD::FMA || 10509 Op1.getOpcode() != ISD::FP_EXTEND || 10510 Op2.getOpcode() != ISD::FP_EXTEND) 10511 return SDValue(); 10512 10513 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10514 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10515 // is sufficient to allow generaing fdot2. 10516 const TargetOptions &Options = DAG.getTarget().Options; 10517 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10518 (N->getFlags().hasAllowContract() && 10519 FMA->getFlags().hasAllowContract())) { 10520 Op1 = Op1.getOperand(0); 10521 Op2 = Op2.getOperand(0); 10522 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10523 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10524 return SDValue(); 10525 10526 SDValue Vec1 = Op1.getOperand(0); 10527 SDValue Idx1 = Op1.getOperand(1); 10528 SDValue Vec2 = Op2.getOperand(0); 10529 10530 SDValue FMAOp1 = FMA.getOperand(0); 10531 SDValue FMAOp2 = FMA.getOperand(1); 10532 SDValue FMAAcc = FMA.getOperand(2); 10533 10534 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10535 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10536 return SDValue(); 10537 10538 FMAOp1 = FMAOp1.getOperand(0); 10539 FMAOp2 = FMAOp2.getOperand(0); 10540 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10541 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10542 return SDValue(); 10543 10544 SDValue Vec3 = FMAOp1.getOperand(0); 10545 SDValue Vec4 = FMAOp2.getOperand(0); 10546 SDValue Idx2 = FMAOp1.getOperand(1); 10547 10548 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10549 // Idx1 and Idx2 cannot be the same. 10550 Idx1 == Idx2) 10551 return SDValue(); 10552 10553 if (Vec1 == Vec2 || Vec3 == Vec4) 10554 return SDValue(); 10555 10556 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10557 return SDValue(); 10558 10559 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10560 (Vec1 == Vec4 && Vec2 == Vec3)) { 10561 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10562 DAG.getTargetConstant(0, SL, MVT::i1)); 10563 } 10564 } 10565 return SDValue(); 10566 } 10567 10568 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10569 DAGCombinerInfo &DCI) const { 10570 SelectionDAG &DAG = DCI.DAG; 10571 SDLoc SL(N); 10572 10573 SDValue LHS = N->getOperand(0); 10574 SDValue RHS = N->getOperand(1); 10575 EVT VT = LHS.getValueType(); 10576 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10577 10578 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10579 if (!CRHS) { 10580 CRHS = dyn_cast<ConstantSDNode>(LHS); 10581 if (CRHS) { 10582 std::swap(LHS, RHS); 10583 CC = getSetCCSwappedOperands(CC); 10584 } 10585 } 10586 10587 if (CRHS) { 10588 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10589 isBoolSGPR(LHS.getOperand(0))) { 10590 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10591 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10592 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10593 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10594 if ((CRHS->isAllOnesValue() && 10595 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10596 (CRHS->isNullValue() && 10597 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10598 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10599 DAG.getConstant(-1, SL, MVT::i1)); 10600 if ((CRHS->isAllOnesValue() && 10601 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10602 (CRHS->isNullValue() && 10603 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10604 return LHS.getOperand(0); 10605 } 10606 10607 uint64_t CRHSVal = CRHS->getZExtValue(); 10608 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10609 LHS.getOpcode() == ISD::SELECT && 10610 isa<ConstantSDNode>(LHS.getOperand(1)) && 10611 isa<ConstantSDNode>(LHS.getOperand(2)) && 10612 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10613 isBoolSGPR(LHS.getOperand(0))) { 10614 // Given CT != FT: 10615 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10616 // setcc (select cc, CT, CF), CF, ne => cc 10617 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10618 // setcc (select cc, CT, CF), CT, eq => cc 10619 uint64_t CT = LHS.getConstantOperandVal(1); 10620 uint64_t CF = LHS.getConstantOperandVal(2); 10621 10622 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10623 (CT == CRHSVal && CC == ISD::SETNE)) 10624 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10625 DAG.getConstant(-1, SL, MVT::i1)); 10626 if ((CF == CRHSVal && CC == ISD::SETNE) || 10627 (CT == CRHSVal && CC == ISD::SETEQ)) 10628 return LHS.getOperand(0); 10629 } 10630 } 10631 10632 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10633 VT != MVT::f16)) 10634 return SDValue(); 10635 10636 // Match isinf/isfinite pattern 10637 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10638 // (fcmp one (fabs x), inf) -> (fp_class x, 10639 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10640 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10641 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10642 if (!CRHS) 10643 return SDValue(); 10644 10645 const APFloat &APF = CRHS->getValueAPF(); 10646 if (APF.isInfinity() && !APF.isNegative()) { 10647 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10648 SIInstrFlags::N_INFINITY; 10649 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10650 SIInstrFlags::P_ZERO | 10651 SIInstrFlags::N_NORMAL | 10652 SIInstrFlags::P_NORMAL | 10653 SIInstrFlags::N_SUBNORMAL | 10654 SIInstrFlags::P_SUBNORMAL; 10655 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10656 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10657 DAG.getConstant(Mask, SL, MVT::i32)); 10658 } 10659 } 10660 10661 return SDValue(); 10662 } 10663 10664 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10665 DAGCombinerInfo &DCI) const { 10666 SelectionDAG &DAG = DCI.DAG; 10667 SDLoc SL(N); 10668 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10669 10670 SDValue Src = N->getOperand(0); 10671 SDValue Shift = N->getOperand(0); 10672 10673 // TODO: Extend type shouldn't matter (assuming legal types). 10674 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10675 Shift = Shift.getOperand(0); 10676 10677 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10678 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10679 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10680 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10681 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10682 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10683 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10684 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10685 SDLoc(Shift.getOperand(0)), MVT::i32); 10686 10687 unsigned ShiftOffset = 8 * Offset; 10688 if (Shift.getOpcode() == ISD::SHL) 10689 ShiftOffset -= C->getZExtValue(); 10690 else 10691 ShiftOffset += C->getZExtValue(); 10692 10693 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10694 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10695 MVT::f32, Shift); 10696 } 10697 } 10698 } 10699 10700 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10701 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10702 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10703 // We simplified Src. If this node is not dead, visit it again so it is 10704 // folded properly. 10705 if (N->getOpcode() != ISD::DELETED_NODE) 10706 DCI.AddToWorklist(N); 10707 return SDValue(N, 0); 10708 } 10709 10710 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10711 if (SDValue DemandedSrc = 10712 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10713 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10714 10715 return SDValue(); 10716 } 10717 10718 SDValue SITargetLowering::performClampCombine(SDNode *N, 10719 DAGCombinerInfo &DCI) const { 10720 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10721 if (!CSrc) 10722 return SDValue(); 10723 10724 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10725 const APFloat &F = CSrc->getValueAPF(); 10726 APFloat Zero = APFloat::getZero(F.getSemantics()); 10727 if (F < Zero || 10728 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10729 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10730 } 10731 10732 APFloat One(F.getSemantics(), "1.0"); 10733 if (F > One) 10734 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10735 10736 return SDValue(CSrc, 0); 10737 } 10738 10739 10740 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10741 DAGCombinerInfo &DCI) const { 10742 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10743 return SDValue(); 10744 switch (N->getOpcode()) { 10745 case ISD::ADD: 10746 return performAddCombine(N, DCI); 10747 case ISD::SUB: 10748 return performSubCombine(N, DCI); 10749 case ISD::ADDCARRY: 10750 case ISD::SUBCARRY: 10751 return performAddCarrySubCarryCombine(N, DCI); 10752 case ISD::FADD: 10753 return performFAddCombine(N, DCI); 10754 case ISD::FSUB: 10755 return performFSubCombine(N, DCI); 10756 case ISD::SETCC: 10757 return performSetCCCombine(N, DCI); 10758 case ISD::FMAXNUM: 10759 case ISD::FMINNUM: 10760 case ISD::FMAXNUM_IEEE: 10761 case ISD::FMINNUM_IEEE: 10762 case ISD::SMAX: 10763 case ISD::SMIN: 10764 case ISD::UMAX: 10765 case ISD::UMIN: 10766 case AMDGPUISD::FMIN_LEGACY: 10767 case AMDGPUISD::FMAX_LEGACY: 10768 return performMinMaxCombine(N, DCI); 10769 case ISD::FMA: 10770 return performFMACombine(N, DCI); 10771 case ISD::AND: 10772 return performAndCombine(N, DCI); 10773 case ISD::OR: 10774 return performOrCombine(N, DCI); 10775 case ISD::XOR: 10776 return performXorCombine(N, DCI); 10777 case ISD::ZERO_EXTEND: 10778 return performZeroExtendCombine(N, DCI); 10779 case ISD::SIGN_EXTEND_INREG: 10780 return performSignExtendInRegCombine(N , DCI); 10781 case AMDGPUISD::FP_CLASS: 10782 return performClassCombine(N, DCI); 10783 case ISD::FCANONICALIZE: 10784 return performFCanonicalizeCombine(N, DCI); 10785 case AMDGPUISD::RCP: 10786 return performRcpCombine(N, DCI); 10787 case AMDGPUISD::FRACT: 10788 case AMDGPUISD::RSQ: 10789 case AMDGPUISD::RCP_LEGACY: 10790 case AMDGPUISD::RCP_IFLAG: 10791 case AMDGPUISD::RSQ_CLAMP: 10792 case AMDGPUISD::LDEXP: { 10793 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10794 SDValue Src = N->getOperand(0); 10795 if (Src.isUndef()) 10796 return Src; 10797 break; 10798 } 10799 case ISD::SINT_TO_FP: 10800 case ISD::UINT_TO_FP: 10801 return performUCharToFloatCombine(N, DCI); 10802 case AMDGPUISD::CVT_F32_UBYTE0: 10803 case AMDGPUISD::CVT_F32_UBYTE1: 10804 case AMDGPUISD::CVT_F32_UBYTE2: 10805 case AMDGPUISD::CVT_F32_UBYTE3: 10806 return performCvtF32UByteNCombine(N, DCI); 10807 case AMDGPUISD::FMED3: 10808 return performFMed3Combine(N, DCI); 10809 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10810 return performCvtPkRTZCombine(N, DCI); 10811 case AMDGPUISD::CLAMP: 10812 return performClampCombine(N, DCI); 10813 case ISD::SCALAR_TO_VECTOR: { 10814 SelectionDAG &DAG = DCI.DAG; 10815 EVT VT = N->getValueType(0); 10816 10817 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10818 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10819 SDLoc SL(N); 10820 SDValue Src = N->getOperand(0); 10821 EVT EltVT = Src.getValueType(); 10822 if (EltVT == MVT::f16) 10823 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10824 10825 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10826 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10827 } 10828 10829 break; 10830 } 10831 case ISD::EXTRACT_VECTOR_ELT: 10832 return performExtractVectorEltCombine(N, DCI); 10833 case ISD::INSERT_VECTOR_ELT: 10834 return performInsertVectorEltCombine(N, DCI); 10835 case ISD::LOAD: { 10836 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10837 return Widended; 10838 LLVM_FALLTHROUGH; 10839 } 10840 default: { 10841 if (!DCI.isBeforeLegalize()) { 10842 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10843 return performMemSDNodeCombine(MemNode, DCI); 10844 } 10845 10846 break; 10847 } 10848 } 10849 10850 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10851 } 10852 10853 /// Helper function for adjustWritemask 10854 static unsigned SubIdx2Lane(unsigned Idx) { 10855 switch (Idx) { 10856 default: return 0; 10857 case AMDGPU::sub0: return 0; 10858 case AMDGPU::sub1: return 1; 10859 case AMDGPU::sub2: return 2; 10860 case AMDGPU::sub3: return 3; 10861 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10862 } 10863 } 10864 10865 /// Adjust the writemask of MIMG instructions 10866 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10867 SelectionDAG &DAG) const { 10868 unsigned Opcode = Node->getMachineOpcode(); 10869 10870 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10871 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10872 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10873 return Node; // not implemented for D16 10874 10875 SDNode *Users[5] = { nullptr }; 10876 unsigned Lane = 0; 10877 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10878 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10879 unsigned NewDmask = 0; 10880 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10881 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10882 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10883 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10884 unsigned TFCLane = 0; 10885 bool HasChain = Node->getNumValues() > 1; 10886 10887 if (OldDmask == 0) { 10888 // These are folded out, but on the chance it happens don't assert. 10889 return Node; 10890 } 10891 10892 unsigned OldBitsSet = countPopulation(OldDmask); 10893 // Work out which is the TFE/LWE lane if that is enabled. 10894 if (UsesTFC) { 10895 TFCLane = OldBitsSet; 10896 } 10897 10898 // Try to figure out the used register components 10899 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10900 I != E; ++I) { 10901 10902 // Don't look at users of the chain. 10903 if (I.getUse().getResNo() != 0) 10904 continue; 10905 10906 // Abort if we can't understand the usage 10907 if (!I->isMachineOpcode() || 10908 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10909 return Node; 10910 10911 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10912 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10913 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10914 // set, etc. 10915 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10916 10917 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10918 if (UsesTFC && Lane == TFCLane) { 10919 Users[Lane] = *I; 10920 } else { 10921 // Set which texture component corresponds to the lane. 10922 unsigned Comp; 10923 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10924 Comp = countTrailingZeros(Dmask); 10925 Dmask &= ~(1 << Comp); 10926 } 10927 10928 // Abort if we have more than one user per component. 10929 if (Users[Lane]) 10930 return Node; 10931 10932 Users[Lane] = *I; 10933 NewDmask |= 1 << Comp; 10934 } 10935 } 10936 10937 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10938 bool NoChannels = !NewDmask; 10939 if (NoChannels) { 10940 if (!UsesTFC) { 10941 // No uses of the result and not using TFC. Then do nothing. 10942 return Node; 10943 } 10944 // If the original dmask has one channel - then nothing to do 10945 if (OldBitsSet == 1) 10946 return Node; 10947 // Use an arbitrary dmask - required for the instruction to work 10948 NewDmask = 1; 10949 } 10950 // Abort if there's no change 10951 if (NewDmask == OldDmask) 10952 return Node; 10953 10954 unsigned BitsSet = countPopulation(NewDmask); 10955 10956 // Check for TFE or LWE - increase the number of channels by one to account 10957 // for the extra return value 10958 // This will need adjustment for D16 if this is also included in 10959 // adjustWriteMask (this function) but at present D16 are excluded. 10960 unsigned NewChannels = BitsSet + UsesTFC; 10961 10962 int NewOpcode = 10963 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10964 assert(NewOpcode != -1 && 10965 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10966 "failed to find equivalent MIMG op"); 10967 10968 // Adjust the writemask in the node 10969 SmallVector<SDValue, 12> Ops; 10970 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10971 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10972 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10973 10974 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10975 10976 MVT ResultVT = NewChannels == 1 ? 10977 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10978 NewChannels == 5 ? 8 : NewChannels); 10979 SDVTList NewVTList = HasChain ? 10980 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10981 10982 10983 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10984 NewVTList, Ops); 10985 10986 if (HasChain) { 10987 // Update chain. 10988 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10989 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10990 } 10991 10992 if (NewChannels == 1) { 10993 assert(Node->hasNUsesOfValue(1, 0)); 10994 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10995 SDLoc(Node), Users[Lane]->getValueType(0), 10996 SDValue(NewNode, 0)); 10997 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10998 return nullptr; 10999 } 11000 11001 // Update the users of the node with the new indices 11002 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11003 SDNode *User = Users[i]; 11004 if (!User) { 11005 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11006 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11007 if (i || !NoChannels) 11008 continue; 11009 } else { 11010 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11011 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11012 } 11013 11014 switch (Idx) { 11015 default: break; 11016 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11017 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11018 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11019 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11020 } 11021 } 11022 11023 DAG.RemoveDeadNode(Node); 11024 return nullptr; 11025 } 11026 11027 static bool isFrameIndexOp(SDValue Op) { 11028 if (Op.getOpcode() == ISD::AssertZext) 11029 Op = Op.getOperand(0); 11030 11031 return isa<FrameIndexSDNode>(Op); 11032 } 11033 11034 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11035 /// with frame index operands. 11036 /// LLVM assumes that inputs are to these instructions are registers. 11037 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11038 SelectionDAG &DAG) const { 11039 if (Node->getOpcode() == ISD::CopyToReg) { 11040 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11041 SDValue SrcVal = Node->getOperand(2); 11042 11043 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11044 // to try understanding copies to physical registers. 11045 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11046 SDLoc SL(Node); 11047 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11048 SDValue VReg = DAG.getRegister( 11049 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11050 11051 SDNode *Glued = Node->getGluedNode(); 11052 SDValue ToVReg 11053 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11054 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11055 SDValue ToResultReg 11056 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11057 VReg, ToVReg.getValue(1)); 11058 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11059 DAG.RemoveDeadNode(Node); 11060 return ToResultReg.getNode(); 11061 } 11062 } 11063 11064 SmallVector<SDValue, 8> Ops; 11065 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11066 if (!isFrameIndexOp(Node->getOperand(i))) { 11067 Ops.push_back(Node->getOperand(i)); 11068 continue; 11069 } 11070 11071 SDLoc DL(Node); 11072 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11073 Node->getOperand(i).getValueType(), 11074 Node->getOperand(i)), 0)); 11075 } 11076 11077 return DAG.UpdateNodeOperands(Node, Ops); 11078 } 11079 11080 /// Fold the instructions after selecting them. 11081 /// Returns null if users were already updated. 11082 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11083 SelectionDAG &DAG) const { 11084 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11085 unsigned Opcode = Node->getMachineOpcode(); 11086 11087 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11088 !TII->isGather4(Opcode) && 11089 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11090 return adjustWritemask(Node, DAG); 11091 } 11092 11093 if (Opcode == AMDGPU::INSERT_SUBREG || 11094 Opcode == AMDGPU::REG_SEQUENCE) { 11095 legalizeTargetIndependentNode(Node, DAG); 11096 return Node; 11097 } 11098 11099 switch (Opcode) { 11100 case AMDGPU::V_DIV_SCALE_F32: 11101 case AMDGPU::V_DIV_SCALE_F64: { 11102 // Satisfy the operand register constraint when one of the inputs is 11103 // undefined. Ordinarily each undef value will have its own implicit_def of 11104 // a vreg, so force these to use a single register. 11105 SDValue Src0 = Node->getOperand(1); 11106 SDValue Src1 = Node->getOperand(3); 11107 SDValue Src2 = Node->getOperand(5); 11108 11109 if ((Src0.isMachineOpcode() && 11110 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11111 (Src0 == Src1 || Src0 == Src2)) 11112 break; 11113 11114 MVT VT = Src0.getValueType().getSimpleVT(); 11115 const TargetRegisterClass *RC = 11116 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11117 11118 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11119 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11120 11121 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11122 UndefReg, Src0, SDValue()); 11123 11124 // src0 must be the same register as src1 or src2, even if the value is 11125 // undefined, so make sure we don't violate this constraint. 11126 if (Src0.isMachineOpcode() && 11127 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11128 if (Src1.isMachineOpcode() && 11129 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11130 Src0 = Src1; 11131 else if (Src2.isMachineOpcode() && 11132 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11133 Src0 = Src2; 11134 else { 11135 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11136 Src0 = UndefReg; 11137 Src1 = UndefReg; 11138 } 11139 } else 11140 break; 11141 11142 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11143 Ops[1] = Src0; 11144 Ops[3] = Src1; 11145 Ops[5] = Src2; 11146 Ops.push_back(ImpDef.getValue(1)); 11147 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11148 } 11149 default: 11150 break; 11151 } 11152 11153 return Node; 11154 } 11155 11156 /// Assign the register class depending on the number of 11157 /// bits set in the writemask 11158 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11159 SDNode *Node) const { 11160 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11161 11162 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11163 11164 if (TII->isVOP3(MI.getOpcode())) { 11165 // Make sure constant bus requirements are respected. 11166 TII->legalizeOperandsVOP3(MRI, MI); 11167 11168 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11169 // This saves a chain-copy of registers and better ballance register 11170 // use between vgpr and agpr as agpr tuples tend to be big. 11171 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11172 unsigned Opc = MI.getOpcode(); 11173 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11174 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11175 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11176 if (I == -1) 11177 break; 11178 MachineOperand &Op = MI.getOperand(I); 11179 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11180 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11181 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11182 continue; 11183 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11184 if (!Src || !Src->isCopy() || 11185 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11186 continue; 11187 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11188 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11189 // All uses of agpr64 and agpr32 can also accept vgpr except for 11190 // v_accvgpr_read, but we do not produce agpr reads during selection, 11191 // so no use checks are needed. 11192 MRI.setRegClass(Op.getReg(), NewRC); 11193 } 11194 } 11195 11196 return; 11197 } 11198 11199 // Replace unused atomics with the no return version. 11200 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11201 if (NoRetAtomicOp != -1) { 11202 if (!Node->hasAnyUseOfValue(0)) { 11203 int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11204 AMDGPU::OpName::glc1); 11205 if (Glc1Idx != -1) 11206 MI.RemoveOperand(Glc1Idx); 11207 MI.RemoveOperand(0); 11208 MI.setDesc(TII->get(NoRetAtomicOp)); 11209 return; 11210 } 11211 11212 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11213 // instruction, because the return type of these instructions is a vec2 of 11214 // the memory type, so it can be tied to the input operand. 11215 // This means these instructions always have a use, so we need to add a 11216 // special case to check if the atomic has only one extract_subreg use, 11217 // which itself has no uses. 11218 if ((Node->hasNUsesOfValue(1, 0) && 11219 Node->use_begin()->isMachineOpcode() && 11220 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11221 !Node->use_begin()->hasAnyUseOfValue(0))) { 11222 Register Def = MI.getOperand(0).getReg(); 11223 11224 // Change this into a noret atomic. 11225 MI.setDesc(TII->get(NoRetAtomicOp)); 11226 MI.RemoveOperand(0); 11227 11228 // If we only remove the def operand from the atomic instruction, the 11229 // extract_subreg will be left with a use of a vreg without a def. 11230 // So we need to insert an implicit_def to avoid machine verifier 11231 // errors. 11232 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11233 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11234 } 11235 return; 11236 } 11237 } 11238 11239 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11240 uint64_t Val) { 11241 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11242 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11243 } 11244 11245 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11246 const SDLoc &DL, 11247 SDValue Ptr) const { 11248 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11249 11250 // Build the half of the subregister with the constants before building the 11251 // full 128-bit register. If we are building multiple resource descriptors, 11252 // this will allow CSEing of the 2-component register. 11253 const SDValue Ops0[] = { 11254 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11255 buildSMovImm32(DAG, DL, 0), 11256 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11257 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11258 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11259 }; 11260 11261 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11262 MVT::v2i32, Ops0), 0); 11263 11264 // Combine the constants and the pointer. 11265 const SDValue Ops1[] = { 11266 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11267 Ptr, 11268 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11269 SubRegHi, 11270 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11271 }; 11272 11273 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11274 } 11275 11276 /// Return a resource descriptor with the 'Add TID' bit enabled 11277 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11278 /// of the resource descriptor) to create an offset, which is added to 11279 /// the resource pointer. 11280 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11281 SDValue Ptr, uint32_t RsrcDword1, 11282 uint64_t RsrcDword2And3) const { 11283 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11284 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11285 if (RsrcDword1) { 11286 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11287 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11288 0); 11289 } 11290 11291 SDValue DataLo = buildSMovImm32(DAG, DL, 11292 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11293 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11294 11295 const SDValue Ops[] = { 11296 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11297 PtrLo, 11298 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11299 PtrHi, 11300 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11301 DataLo, 11302 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11303 DataHi, 11304 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11305 }; 11306 11307 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11308 } 11309 11310 //===----------------------------------------------------------------------===// 11311 // SI Inline Assembly Support 11312 //===----------------------------------------------------------------------===// 11313 11314 std::pair<unsigned, const TargetRegisterClass *> 11315 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11316 StringRef Constraint, 11317 MVT VT) const { 11318 const TargetRegisterClass *RC = nullptr; 11319 if (Constraint.size() == 1) { 11320 const unsigned BitWidth = VT.getSizeInBits(); 11321 switch (Constraint[0]) { 11322 default: 11323 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11324 case 's': 11325 case 'r': 11326 switch (BitWidth) { 11327 case 16: 11328 RC = &AMDGPU::SReg_32RegClass; 11329 break; 11330 case 64: 11331 RC = &AMDGPU::SGPR_64RegClass; 11332 break; 11333 default: 11334 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11335 if (!RC) 11336 return std::make_pair(0U, nullptr); 11337 break; 11338 } 11339 break; 11340 case 'v': 11341 switch (BitWidth) { 11342 case 16: 11343 RC = &AMDGPU::VGPR_32RegClass; 11344 break; 11345 default: 11346 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 11347 if (!RC) 11348 return std::make_pair(0U, nullptr); 11349 break; 11350 } 11351 break; 11352 case 'a': 11353 if (!Subtarget->hasMAIInsts()) 11354 break; 11355 switch (BitWidth) { 11356 case 16: 11357 RC = &AMDGPU::AGPR_32RegClass; 11358 break; 11359 default: 11360 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 11361 if (!RC) 11362 return std::make_pair(0U, nullptr); 11363 break; 11364 } 11365 break; 11366 } 11367 // We actually support i128, i16 and f16 as inline parameters 11368 // even if they are not reported as legal 11369 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11370 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11371 return std::make_pair(0U, RC); 11372 } 11373 11374 if (Constraint.size() > 1) { 11375 if (Constraint[1] == 'v') { 11376 RC = &AMDGPU::VGPR_32RegClass; 11377 } else if (Constraint[1] == 's') { 11378 RC = &AMDGPU::SGPR_32RegClass; 11379 } else if (Constraint[1] == 'a') { 11380 RC = &AMDGPU::AGPR_32RegClass; 11381 } 11382 11383 if (RC) { 11384 uint32_t Idx; 11385 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11386 if (!Failed && Idx < RC->getNumRegs()) 11387 return std::make_pair(RC->getRegister(Idx), RC); 11388 } 11389 } 11390 11391 // FIXME: Returns VS_32 for physical SGPR constraints 11392 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11393 } 11394 11395 static bool isImmConstraint(StringRef Constraint) { 11396 if (Constraint.size() == 1) { 11397 switch (Constraint[0]) { 11398 default: break; 11399 case 'I': 11400 case 'J': 11401 case 'A': 11402 case 'B': 11403 case 'C': 11404 return true; 11405 } 11406 } else if (Constraint == "DA" || 11407 Constraint == "DB") { 11408 return true; 11409 } 11410 return false; 11411 } 11412 11413 SITargetLowering::ConstraintType 11414 SITargetLowering::getConstraintType(StringRef Constraint) const { 11415 if (Constraint.size() == 1) { 11416 switch (Constraint[0]) { 11417 default: break; 11418 case 's': 11419 case 'v': 11420 case 'a': 11421 return C_RegisterClass; 11422 } 11423 } 11424 if (isImmConstraint(Constraint)) { 11425 return C_Other; 11426 } 11427 return TargetLowering::getConstraintType(Constraint); 11428 } 11429 11430 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11431 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11432 Val = Val & maskTrailingOnes<uint64_t>(Size); 11433 } 11434 return Val; 11435 } 11436 11437 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11438 std::string &Constraint, 11439 std::vector<SDValue> &Ops, 11440 SelectionDAG &DAG) const { 11441 if (isImmConstraint(Constraint)) { 11442 uint64_t Val; 11443 if (getAsmOperandConstVal(Op, Val) && 11444 checkAsmConstraintVal(Op, Constraint, Val)) { 11445 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11446 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11447 } 11448 } else { 11449 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11450 } 11451 } 11452 11453 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11454 unsigned Size = Op.getScalarValueSizeInBits(); 11455 if (Size > 64) 11456 return false; 11457 11458 if (Size == 16 && !Subtarget->has16BitInsts()) 11459 return false; 11460 11461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11462 Val = C->getSExtValue(); 11463 return true; 11464 } 11465 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11466 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11467 return true; 11468 } 11469 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11470 if (Size != 16 || Op.getNumOperands() != 2) 11471 return false; 11472 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11473 return false; 11474 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11475 Val = C->getSExtValue(); 11476 return true; 11477 } 11478 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11479 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11480 return true; 11481 } 11482 } 11483 11484 return false; 11485 } 11486 11487 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11488 const std::string &Constraint, 11489 uint64_t Val) const { 11490 if (Constraint.size() == 1) { 11491 switch (Constraint[0]) { 11492 case 'I': 11493 return AMDGPU::isInlinableIntLiteral(Val); 11494 case 'J': 11495 return isInt<16>(Val); 11496 case 'A': 11497 return checkAsmConstraintValA(Op, Val); 11498 case 'B': 11499 return isInt<32>(Val); 11500 case 'C': 11501 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11502 AMDGPU::isInlinableIntLiteral(Val); 11503 default: 11504 break; 11505 } 11506 } else if (Constraint.size() == 2) { 11507 if (Constraint == "DA") { 11508 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11509 int64_t LoBits = static_cast<int32_t>(Val); 11510 return checkAsmConstraintValA(Op, HiBits, 32) && 11511 checkAsmConstraintValA(Op, LoBits, 32); 11512 } 11513 if (Constraint == "DB") { 11514 return true; 11515 } 11516 } 11517 llvm_unreachable("Invalid asm constraint"); 11518 } 11519 11520 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11521 uint64_t Val, 11522 unsigned MaxSize) const { 11523 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11524 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11525 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11526 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11527 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11528 return true; 11529 } 11530 return false; 11531 } 11532 11533 // Figure out which registers should be reserved for stack access. Only after 11534 // the function is legalized do we know all of the non-spill stack objects or if 11535 // calls are present. 11536 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11537 MachineRegisterInfo &MRI = MF.getRegInfo(); 11538 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11539 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11540 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11541 11542 if (Info->isEntryFunction()) { 11543 // Callable functions have fixed registers used for stack access. 11544 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11545 } 11546 11547 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11548 Info->getStackPtrOffsetReg())); 11549 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11550 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11551 11552 // We need to worry about replacing the default register with itself in case 11553 // of MIR testcases missing the MFI. 11554 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11555 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11556 11557 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11558 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11559 11560 Info->limitOccupancy(MF); 11561 11562 if (ST.isWave32() && !MF.empty()) { 11563 const SIInstrInfo *TII = ST.getInstrInfo(); 11564 for (auto &MBB : MF) { 11565 for (auto &MI : MBB) { 11566 TII->fixImplicitOperands(MI); 11567 } 11568 } 11569 } 11570 11571 TargetLoweringBase::finalizeLowering(MF); 11572 11573 // Allocate a VGPR for future SGPR Spill if 11574 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11575 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11576 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 11577 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 11578 Info->reserveVGPRforSGPRSpills(MF); 11579 } 11580 11581 void SITargetLowering::computeKnownBitsForFrameIndex( 11582 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11583 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11584 11585 // Set the high bits to zero based on the maximum allowed scratch size per 11586 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11587 // calculation won't overflow, so assume the sign bit is never set. 11588 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11589 } 11590 11591 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11592 KnownBits &Known, unsigned Dim) { 11593 unsigned MaxValue = 11594 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11595 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11596 } 11597 11598 void SITargetLowering::computeKnownBitsForTargetInstr( 11599 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11600 const MachineRegisterInfo &MRI, unsigned Depth) const { 11601 const MachineInstr *MI = MRI.getVRegDef(R); 11602 switch (MI->getOpcode()) { 11603 case AMDGPU::G_INTRINSIC: { 11604 switch (MI->getIntrinsicID()) { 11605 case Intrinsic::amdgcn_workitem_id_x: 11606 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11607 break; 11608 case Intrinsic::amdgcn_workitem_id_y: 11609 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11610 break; 11611 case Intrinsic::amdgcn_workitem_id_z: 11612 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11613 break; 11614 case Intrinsic::amdgcn_mbcnt_lo: 11615 case Intrinsic::amdgcn_mbcnt_hi: { 11616 // These return at most the wavefront size - 1. 11617 unsigned Size = MRI.getType(R).getSizeInBits(); 11618 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11619 break; 11620 } 11621 case Intrinsic::amdgcn_groupstaticsize: { 11622 // We can report everything over the maximum size as 0. We can't report 11623 // based on the actual size because we don't know if it's accurate or not 11624 // at any given point. 11625 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11626 break; 11627 } 11628 } 11629 break; 11630 } 11631 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11632 Known.Zero.setHighBits(24); 11633 break; 11634 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11635 Known.Zero.setHighBits(16); 11636 break; 11637 } 11638 } 11639 11640 Align SITargetLowering::computeKnownAlignForTargetInstr( 11641 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11642 unsigned Depth) const { 11643 const MachineInstr *MI = MRI.getVRegDef(R); 11644 switch (MI->getOpcode()) { 11645 case AMDGPU::G_INTRINSIC: 11646 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11647 // FIXME: Can this move to generic code? What about the case where the call 11648 // site specifies a lower alignment? 11649 Intrinsic::ID IID = MI->getIntrinsicID(); 11650 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11651 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11652 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11653 return *RetAlign; 11654 return Align(1); 11655 } 11656 default: 11657 return Align(1); 11658 } 11659 } 11660 11661 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11662 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11663 const Align CacheLineAlign = Align(64); 11664 11665 // Pre-GFX10 target did not benefit from loop alignment 11666 if (!ML || DisableLoopAlignment || 11667 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11668 getSubtarget()->hasInstFwdPrefetchBug()) 11669 return PrefAlign; 11670 11671 // On GFX10 I$ is 4 x 64 bytes cache lines. 11672 // By default prefetcher keeps one cache line behind and reads two ahead. 11673 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11674 // behind and one ahead. 11675 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11676 // If loop fits 64 bytes it always spans no more than two cache lines and 11677 // does not need an alignment. 11678 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11679 // Else if loop is less or equal 192 bytes we need two lines behind. 11680 11681 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11682 const MachineBasicBlock *Header = ML->getHeader(); 11683 if (Header->getAlignment() != PrefAlign) 11684 return Header->getAlignment(); // Already processed. 11685 11686 unsigned LoopSize = 0; 11687 for (const MachineBasicBlock *MBB : ML->blocks()) { 11688 // If inner loop block is aligned assume in average half of the alignment 11689 // size to be added as nops. 11690 if (MBB != Header) 11691 LoopSize += MBB->getAlignment().value() / 2; 11692 11693 for (const MachineInstr &MI : *MBB) { 11694 LoopSize += TII->getInstSizeInBytes(MI); 11695 if (LoopSize > 192) 11696 return PrefAlign; 11697 } 11698 } 11699 11700 if (LoopSize <= 64) 11701 return PrefAlign; 11702 11703 if (LoopSize <= 128) 11704 return CacheLineAlign; 11705 11706 // If any of parent loops is surrounded by prefetch instructions do not 11707 // insert new for inner loop, which would reset parent's settings. 11708 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11709 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11710 auto I = Exit->getFirstNonDebugInstr(); 11711 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11712 return CacheLineAlign; 11713 } 11714 } 11715 11716 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11717 MachineBasicBlock *Exit = ML->getExitBlock(); 11718 11719 if (Pre && Exit) { 11720 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11721 TII->get(AMDGPU::S_INST_PREFETCH)) 11722 .addImm(1); // prefetch 2 lines behind PC 11723 11724 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11725 TII->get(AMDGPU::S_INST_PREFETCH)) 11726 .addImm(2); // prefetch 1 line behind PC 11727 } 11728 11729 return CacheLineAlign; 11730 } 11731 11732 LLVM_ATTRIBUTE_UNUSED 11733 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11734 assert(N->getOpcode() == ISD::CopyFromReg); 11735 do { 11736 // Follow the chain until we find an INLINEASM node. 11737 N = N->getOperand(0).getNode(); 11738 if (N->getOpcode() == ISD::INLINEASM || 11739 N->getOpcode() == ISD::INLINEASM_BR) 11740 return true; 11741 } while (N->getOpcode() == ISD::CopyFromReg); 11742 return false; 11743 } 11744 11745 bool SITargetLowering::isSDNodeSourceOfDivergence( 11746 const SDNode *N, FunctionLoweringInfo *FLI, 11747 LegacyDivergenceAnalysis *KDA) const { 11748 switch (N->getOpcode()) { 11749 case ISD::CopyFromReg: { 11750 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11751 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11752 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11753 Register Reg = R->getReg(); 11754 11755 // FIXME: Why does this need to consider isLiveIn? 11756 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11757 return !TRI->isSGPRReg(MRI, Reg); 11758 11759 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11760 return KDA->isDivergent(V); 11761 11762 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11763 return !TRI->isSGPRReg(MRI, Reg); 11764 } 11765 case ISD::LOAD: { 11766 const LoadSDNode *L = cast<LoadSDNode>(N); 11767 unsigned AS = L->getAddressSpace(); 11768 // A flat load may access private memory. 11769 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11770 } 11771 case ISD::CALLSEQ_END: 11772 return true; 11773 case ISD::INTRINSIC_WO_CHAIN: 11774 return AMDGPU::isIntrinsicSourceOfDivergence( 11775 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11776 case ISD::INTRINSIC_W_CHAIN: 11777 return AMDGPU::isIntrinsicSourceOfDivergence( 11778 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11779 } 11780 return false; 11781 } 11782 11783 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11784 EVT VT) const { 11785 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11786 case MVT::f32: 11787 return hasFP32Denormals(DAG.getMachineFunction()); 11788 case MVT::f64: 11789 case MVT::f16: 11790 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11791 default: 11792 return false; 11793 } 11794 } 11795 11796 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11797 const SelectionDAG &DAG, 11798 bool SNaN, 11799 unsigned Depth) const { 11800 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11801 const MachineFunction &MF = DAG.getMachineFunction(); 11802 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11803 11804 if (Info->getMode().DX10Clamp) 11805 return true; // Clamped to 0. 11806 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11807 } 11808 11809 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11810 SNaN, Depth); 11811 } 11812 11813 // Global FP atomic instructions have a hardcoded FP mode and do not support 11814 // FP32 denormals, and only support v2f16 denormals. 11815 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11816 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11817 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11818 if (&Flt == &APFloat::IEEEsingle()) 11819 return DenormMode == DenormalMode::getPreserveSign(); 11820 return DenormMode == DenormalMode::getIEEE(); 11821 } 11822 11823 TargetLowering::AtomicExpansionKind 11824 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11825 switch (RMW->getOperation()) { 11826 case AtomicRMWInst::FAdd: { 11827 Type *Ty = RMW->getType(); 11828 11829 // We don't have a way to support 16-bit atomics now, so just leave them 11830 // as-is. 11831 if (Ty->isHalfTy()) 11832 return AtomicExpansionKind::None; 11833 11834 if (!Ty->isFloatTy()) 11835 return AtomicExpansionKind::CmpXChg; 11836 11837 // TODO: Do have these for flat. Older targets also had them for buffers. 11838 unsigned AS = RMW->getPointerAddressSpace(); 11839 11840 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11841 if (!fpModeMatchesGlobalFPAtomicMode(RMW)) 11842 return AtomicExpansionKind::CmpXChg; 11843 11844 return RMW->use_empty() ? AtomicExpansionKind::None : 11845 AtomicExpansionKind::CmpXChg; 11846 } 11847 11848 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11849 // to round-to-nearest-even. 11850 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11851 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11852 } 11853 default: 11854 break; 11855 } 11856 11857 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11858 } 11859 11860 const TargetRegisterClass * 11861 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11862 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11863 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11864 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11865 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11866 : &AMDGPU::SReg_32RegClass; 11867 if (!TRI->isSGPRClass(RC) && !isDivergent) 11868 return TRI->getEquivalentSGPRClass(RC); 11869 else if (TRI->isSGPRClass(RC) && isDivergent) 11870 return TRI->getEquivalentVGPRClass(RC); 11871 11872 return RC; 11873 } 11874 11875 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11876 // uniform values (as produced by the mask results of control flow intrinsics) 11877 // used outside of divergent blocks. The phi users need to also be treated as 11878 // always uniform. 11879 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11880 unsigned WaveSize) { 11881 // FIXME: We asssume we never cast the mask results of a control flow 11882 // intrinsic. 11883 // Early exit if the type won't be consistent as a compile time hack. 11884 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11885 if (!IT || IT->getBitWidth() != WaveSize) 11886 return false; 11887 11888 if (!isa<Instruction>(V)) 11889 return false; 11890 if (!Visited.insert(V).second) 11891 return false; 11892 bool Result = false; 11893 for (auto U : V->users()) { 11894 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11895 if (V == U->getOperand(1)) { 11896 switch (Intrinsic->getIntrinsicID()) { 11897 default: 11898 Result = false; 11899 break; 11900 case Intrinsic::amdgcn_if_break: 11901 case Intrinsic::amdgcn_if: 11902 case Intrinsic::amdgcn_else: 11903 Result = true; 11904 break; 11905 } 11906 } 11907 if (V == U->getOperand(0)) { 11908 switch (Intrinsic->getIntrinsicID()) { 11909 default: 11910 Result = false; 11911 break; 11912 case Intrinsic::amdgcn_end_cf: 11913 case Intrinsic::amdgcn_loop: 11914 Result = true; 11915 break; 11916 } 11917 } 11918 } else { 11919 Result = hasCFUser(U, Visited, WaveSize); 11920 } 11921 if (Result) 11922 break; 11923 } 11924 return Result; 11925 } 11926 11927 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11928 const Value *V) const { 11929 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11930 if (CI->isInlineAsm()) { 11931 // FIXME: This cannot give a correct answer. This should only trigger in 11932 // the case where inline asm returns mixed SGPR and VGPR results, used 11933 // outside the defining block. We don't have a specific result to 11934 // consider, so this assumes if any value is SGPR, the overall register 11935 // also needs to be SGPR. 11936 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11937 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11938 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11939 for (auto &TC : TargetConstraints) { 11940 if (TC.Type == InlineAsm::isOutput) { 11941 ComputeConstraintToUse(TC, SDValue()); 11942 unsigned AssignedReg; 11943 const TargetRegisterClass *RC; 11944 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11945 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11946 if (RC) { 11947 MachineRegisterInfo &MRI = MF.getRegInfo(); 11948 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11949 return true; 11950 else if (SIRI->isSGPRClass(RC)) 11951 return true; 11952 } 11953 } 11954 } 11955 } 11956 } 11957 SmallPtrSet<const Value *, 16> Visited; 11958 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11959 } 11960 11961 std::pair<int, MVT> 11962 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 11963 Type *Ty) const { 11964 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 11965 auto Size = DL.getTypeSizeInBits(Ty); 11966 // Maximum load or store can handle 8 dwords for scalar and 4 for 11967 // vector ALU. Let's assume anything above 8 dwords is expensive 11968 // even if legal. 11969 if (Size <= 256) 11970 return Cost; 11971 11972 Cost.first = (Size + 255) / 256; 11973 return Cost; 11974 } 11975