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 "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/IR/DiagnosticInfo.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/IntrinsicsAMDGPU.h" 32 #include "llvm/IR/IntrinsicsR600.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/KnownBits.h" 35 36 using namespace llvm; 37 38 #define DEBUG_TYPE "si-lower" 39 40 STATISTIC(NumTailCalls, "Number of tail calls"); 41 42 static cl::opt<bool> DisableLoopAlignment( 43 "amdgpu-disable-loop-alignment", 44 cl::desc("Do not align and prefetch loops"), 45 cl::init(false)); 46 47 static cl::opt<bool> VGPRReserveforSGPRSpill( 48 "amdgpu-reserve-vgpr-for-sgpr-spill", 49 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 50 51 static cl::opt<bool> UseDivergentRegisterIndexing( 52 "amdgpu-use-divergent-register-indexing", 53 cl::Hidden, 54 cl::desc("Use indirect register addressing for divergent indexes"), 55 cl::init(false)); 56 57 static bool hasFP32Denormals(const MachineFunction &MF) { 58 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 59 return Info->getMode().allFP32Denormals(); 60 } 61 62 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 63 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 64 return Info->getMode().allFP64FP16Denormals(); 65 } 66 67 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 68 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 69 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 70 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 71 return AMDGPU::SGPR0 + Reg; 72 } 73 } 74 llvm_unreachable("Cannot allocate sgpr"); 75 } 76 77 SITargetLowering::SITargetLowering(const TargetMachine &TM, 78 const GCNSubtarget &STI) 79 : AMDGPUTargetLowering(TM, STI), 80 Subtarget(&STI) { 81 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 82 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 83 84 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 85 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 86 87 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 88 89 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 90 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 91 92 addRegisterClass(MVT::f64, V64RegClass); 93 addRegisterClass(MVT::v2f32, V64RegClass); 94 95 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 96 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 97 98 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 100 101 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 102 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 103 104 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 105 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 106 107 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 108 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 109 110 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 111 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 112 113 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 114 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 115 116 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 117 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 118 119 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 120 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 121 122 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 123 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 124 125 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 126 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 127 128 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 129 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 130 131 if (Subtarget->has16BitInsts()) { 132 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 133 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 134 135 // Unless there are also VOP3P operations, not operations are really legal. 136 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 138 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 140 } 141 142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 144 145 computeRegisterProperties(Subtarget->getRegisterInfo()); 146 147 // The boolean content concept here is too inflexible. Compares only ever 148 // really produce a 1-bit result. Any copy/extend from these will turn into a 149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 150 // it's what most targets use. 151 setBooleanContents(ZeroOrOneBooleanContent); 152 setBooleanVectorContents(ZeroOrOneBooleanContent); 153 154 // We need to custom lower vector stores from local memory 155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 174 setOperationAction(ISD::STORE, MVT::i1, Custom); 175 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 176 177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 193 194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 201 202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 204 205 setOperationAction(ISD::SELECT, MVT::i1, Promote); 206 setOperationAction(ISD::SELECT, MVT::i64, Custom); 207 setOperationAction(ISD::SELECT, MVT::f64, Promote); 208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 209 210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 215 216 setOperationAction(ISD::SETCC, MVT::i1, Promote); 217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 220 221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 237 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 246 247 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 248 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 253 254 setOperationAction(ISD::UADDO, MVT::i32, Legal); 255 setOperationAction(ISD::USUBO, MVT::i32, Legal); 256 257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 259 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 263 264 #if 0 265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 267 #endif 268 269 // We only support LOAD/STORE and vector manipulation ops for vectors 270 // with > 4 elements. 271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 275 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 276 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 277 switch (Op) { 278 case ISD::LOAD: 279 case ISD::STORE: 280 case ISD::BUILD_VECTOR: 281 case ISD::BITCAST: 282 case ISD::EXTRACT_VECTOR_ELT: 283 case ISD::INSERT_VECTOR_ELT: 284 case ISD::EXTRACT_SUBVECTOR: 285 case ISD::SCALAR_TO_VECTOR: 286 break; 287 case ISD::INSERT_SUBVECTOR: 288 case ISD::CONCAT_VECTORS: 289 setOperationAction(Op, VT, Custom); 290 break; 291 default: 292 setOperationAction(Op, VT, Expand); 293 break; 294 } 295 } 296 } 297 298 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 299 300 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 301 // is expanded to avoid having two separate loops in case the index is a VGPR. 302 303 // Most operations are naturally 32-bit vector operations. We only support 304 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 305 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 306 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 307 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 311 312 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 313 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 314 315 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 316 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 317 } 318 319 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 320 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 321 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 322 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 325 326 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 327 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 328 329 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 330 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 331 } 332 333 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 334 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 335 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 341 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 342 343 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 344 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 345 } 346 347 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 348 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 349 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 355 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 356 357 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 358 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 359 } 360 361 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 362 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 363 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 369 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 370 371 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 372 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 373 } 374 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 379 380 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 382 383 // Avoid stack access for these. 384 // TODO: Generalize to more vector types. 385 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 389 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 396 397 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 399 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 401 402 // Deal with vec3 vector operations when widened to vec4. 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 407 408 // Deal with vec5/6/7 vector operations when widened to vec8. 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 417 418 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 419 // and output demarshalling 420 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 422 423 // We can't return success/failure, only the old value, 424 // let LLVM add the comparison 425 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 427 428 if (Subtarget->hasFlatAddressSpace()) { 429 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 430 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 431 } 432 433 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 434 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 435 436 // FIXME: This should be narrowed to i32, but that only happens if i64 is 437 // illegal. 438 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 439 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 440 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 441 442 // On SI this is s_memtime and s_memrealtime on VI. 443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 444 setOperationAction(ISD::TRAP, MVT::Other, Custom); 445 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 446 447 if (Subtarget->has16BitInsts()) { 448 setOperationAction(ISD::FPOW, MVT::f16, Promote); 449 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 450 setOperationAction(ISD::FLOG, MVT::f16, Custom); 451 setOperationAction(ISD::FEXP, MVT::f16, Custom); 452 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 453 } 454 455 if (Subtarget->hasMadMacF32Insts()) 456 setOperationAction(ISD::FMAD, MVT::f32, Legal); 457 458 if (!Subtarget->hasBFI()) { 459 // fcopysign can be done in a single instruction with BFI. 460 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 461 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 462 } 463 464 if (!Subtarget->hasBCNT(32)) 465 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 466 467 if (!Subtarget->hasBCNT(64)) 468 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 469 470 if (Subtarget->hasFFBH()) { 471 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 473 } 474 475 if (Subtarget->hasFFBL()) { 476 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 478 } 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, Custom); 581 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 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 if (Subtarget->hasPackedFP32Ops()) { 775 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 776 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 777 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 778 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 779 780 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 781 setOperationAction(ISD::FADD, VT, Custom); 782 setOperationAction(ISD::FMUL, VT, Custom); 783 setOperationAction(ISD::FMA, VT, Custom); 784 } 785 } 786 } 787 788 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 789 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 790 791 if (Subtarget->has16BitInsts()) { 792 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 793 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 794 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 795 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 796 } else { 797 // Legalization hack. 798 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 799 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 800 801 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 802 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 803 } 804 805 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 806 setOperationAction(ISD::SELECT, VT, Custom); 807 } 808 809 setOperationAction(ISD::SMULO, MVT::i64, Custom); 810 setOperationAction(ISD::UMULO, MVT::i64, Custom); 811 812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 813 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 819 820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 831 832 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 833 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 842 843 setTargetDAGCombine(ISD::ADD); 844 setTargetDAGCombine(ISD::ADDCARRY); 845 setTargetDAGCombine(ISD::SUB); 846 setTargetDAGCombine(ISD::SUBCARRY); 847 setTargetDAGCombine(ISD::FADD); 848 setTargetDAGCombine(ISD::FSUB); 849 setTargetDAGCombine(ISD::FMINNUM); 850 setTargetDAGCombine(ISD::FMAXNUM); 851 setTargetDAGCombine(ISD::FMINNUM_IEEE); 852 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 853 setTargetDAGCombine(ISD::FMA); 854 setTargetDAGCombine(ISD::SMIN); 855 setTargetDAGCombine(ISD::SMAX); 856 setTargetDAGCombine(ISD::UMIN); 857 setTargetDAGCombine(ISD::UMAX); 858 setTargetDAGCombine(ISD::SETCC); 859 setTargetDAGCombine(ISD::AND); 860 setTargetDAGCombine(ISD::OR); 861 setTargetDAGCombine(ISD::XOR); 862 setTargetDAGCombine(ISD::SINT_TO_FP); 863 setTargetDAGCombine(ISD::UINT_TO_FP); 864 setTargetDAGCombine(ISD::FCANONICALIZE); 865 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 866 setTargetDAGCombine(ISD::ZERO_EXTEND); 867 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 868 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 869 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 870 871 // All memory operations. Some folding on the pointer operand is done to help 872 // matching the constant offsets in the addressing modes. 873 setTargetDAGCombine(ISD::LOAD); 874 setTargetDAGCombine(ISD::STORE); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD); 876 setTargetDAGCombine(ISD::ATOMIC_STORE); 877 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 878 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 879 setTargetDAGCombine(ISD::ATOMIC_SWAP); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 891 setTargetDAGCombine(ISD::INTRINSIC_VOID); 892 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 893 894 // FIXME: In other contexts we pretend this is a per-function property. 895 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 896 897 setSchedulingPreference(Sched::RegPressure); 898 } 899 900 const GCNSubtarget *SITargetLowering::getSubtarget() const { 901 return Subtarget; 902 } 903 904 //===----------------------------------------------------------------------===// 905 // TargetLowering queries 906 //===----------------------------------------------------------------------===// 907 908 // v_mad_mix* support a conversion from f16 to f32. 909 // 910 // There is only one special case when denormals are enabled we don't currently, 911 // where this is OK to use. 912 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 913 EVT DestVT, EVT SrcVT) const { 914 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 915 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 916 DestVT.getScalarType() == MVT::f32 && 917 SrcVT.getScalarType() == MVT::f16 && 918 // TODO: This probably only requires no input flushing? 919 !hasFP32Denormals(DAG.getMachineFunction()); 920 } 921 922 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 923 // SI has some legal vector types, but no legal vector operations. Say no 924 // shuffles are legal in order to prefer scalarizing some vector operations. 925 return false; 926 } 927 928 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 929 CallingConv::ID CC, 930 EVT VT) const { 931 if (CC == CallingConv::AMDGPU_KERNEL) 932 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 933 934 if (VT.isVector()) { 935 EVT ScalarVT = VT.getScalarType(); 936 unsigned Size = ScalarVT.getSizeInBits(); 937 if (Size == 16) { 938 if (Subtarget->has16BitInsts()) 939 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 940 return VT.isInteger() ? MVT::i32 : MVT::f32; 941 } 942 943 if (Size < 16) 944 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 945 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 946 } 947 948 if (VT.getSizeInBits() > 32) 949 return MVT::i32; 950 951 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 952 } 953 954 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 955 CallingConv::ID CC, 956 EVT VT) const { 957 if (CC == CallingConv::AMDGPU_KERNEL) 958 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 959 960 if (VT.isVector()) { 961 unsigned NumElts = VT.getVectorNumElements(); 962 EVT ScalarVT = VT.getScalarType(); 963 unsigned Size = ScalarVT.getSizeInBits(); 964 965 // FIXME: Should probably promote 8-bit vectors to i16. 966 if (Size == 16 && Subtarget->has16BitInsts()) 967 return (NumElts + 1) / 2; 968 969 if (Size <= 32) 970 return NumElts; 971 972 if (Size > 32) 973 return NumElts * ((Size + 31) / 32); 974 } else if (VT.getSizeInBits() > 32) 975 return (VT.getSizeInBits() + 31) / 32; 976 977 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 978 } 979 980 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 981 LLVMContext &Context, CallingConv::ID CC, 982 EVT VT, EVT &IntermediateVT, 983 unsigned &NumIntermediates, MVT &RegisterVT) const { 984 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 985 unsigned NumElts = VT.getVectorNumElements(); 986 EVT ScalarVT = VT.getScalarType(); 987 unsigned Size = ScalarVT.getSizeInBits(); 988 // FIXME: We should fix the ABI to be the same on targets without 16-bit 989 // support, but unless we can properly handle 3-vectors, it will be still be 990 // inconsistent. 991 if (Size == 16 && Subtarget->has16BitInsts()) { 992 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 993 IntermediateVT = RegisterVT; 994 NumIntermediates = (NumElts + 1) / 2; 995 return NumIntermediates; 996 } 997 998 if (Size == 32) { 999 RegisterVT = ScalarVT.getSimpleVT(); 1000 IntermediateVT = RegisterVT; 1001 NumIntermediates = NumElts; 1002 return NumIntermediates; 1003 } 1004 1005 if (Size < 16 && Subtarget->has16BitInsts()) { 1006 // FIXME: Should probably form v2i16 pieces 1007 RegisterVT = MVT::i16; 1008 IntermediateVT = ScalarVT; 1009 NumIntermediates = NumElts; 1010 return NumIntermediates; 1011 } 1012 1013 1014 if (Size != 16 && Size <= 32) { 1015 RegisterVT = MVT::i32; 1016 IntermediateVT = ScalarVT; 1017 NumIntermediates = NumElts; 1018 return NumIntermediates; 1019 } 1020 1021 if (Size > 32) { 1022 RegisterVT = MVT::i32; 1023 IntermediateVT = RegisterVT; 1024 NumIntermediates = NumElts * ((Size + 31) / 32); 1025 return NumIntermediates; 1026 } 1027 } 1028 1029 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1030 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1031 } 1032 1033 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1034 assert(DMaskLanes != 0); 1035 1036 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1037 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1038 return EVT::getVectorVT(Ty->getContext(), 1039 EVT::getEVT(VT->getElementType()), 1040 NumElts); 1041 } 1042 1043 return EVT::getEVT(Ty); 1044 } 1045 1046 // Peek through TFE struct returns to only use the data size. 1047 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1048 auto *ST = dyn_cast<StructType>(Ty); 1049 if (!ST) 1050 return memVTFromImageData(Ty, DMaskLanes); 1051 1052 // Some intrinsics return an aggregate type - special case to work out the 1053 // correct memVT. 1054 // 1055 // Only limited forms of aggregate type currently expected. 1056 if (ST->getNumContainedTypes() != 2 || 1057 !ST->getContainedType(1)->isIntegerTy(32)) 1058 return EVT(); 1059 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1060 } 1061 1062 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1063 const CallInst &CI, 1064 MachineFunction &MF, 1065 unsigned IntrID) const { 1066 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1067 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1068 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1069 (Intrinsic::ID)IntrID); 1070 if (Attr.hasFnAttr(Attribute::ReadNone)) 1071 return false; 1072 1073 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1074 1075 if (RsrcIntr->IsImage) { 1076 Info.ptrVal = 1077 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1078 Info.align.reset(); 1079 } else { 1080 Info.ptrVal = 1081 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1082 } 1083 1084 Info.flags = MachineMemOperand::MODereferenceable; 1085 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1086 unsigned DMaskLanes = 4; 1087 1088 if (RsrcIntr->IsImage) { 1089 const AMDGPU::ImageDimIntrinsicInfo *Intr 1090 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1091 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1092 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1093 1094 if (!BaseOpcode->Gather4) { 1095 // If this isn't a gather, we may have excess loaded elements in the 1096 // IR type. Check the dmask for the real number of elements loaded. 1097 unsigned DMask 1098 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1099 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1100 } 1101 1102 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1103 } else 1104 Info.memVT = EVT::getEVT(CI.getType()); 1105 1106 // FIXME: What does alignment mean for an image? 1107 Info.opc = ISD::INTRINSIC_W_CHAIN; 1108 Info.flags |= MachineMemOperand::MOLoad; 1109 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1110 Info.opc = ISD::INTRINSIC_VOID; 1111 1112 Type *DataTy = CI.getArgOperand(0)->getType(); 1113 if (RsrcIntr->IsImage) { 1114 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1115 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1116 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1117 } else 1118 Info.memVT = EVT::getEVT(DataTy); 1119 1120 Info.flags |= MachineMemOperand::MOStore; 1121 } else { 1122 // Atomic 1123 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1124 ISD::INTRINSIC_W_CHAIN; 1125 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1126 Info.flags = MachineMemOperand::MOLoad | 1127 MachineMemOperand::MOStore | 1128 MachineMemOperand::MODereferenceable; 1129 1130 // XXX - Should this be volatile without known ordering? 1131 Info.flags |= MachineMemOperand::MOVolatile; 1132 } 1133 return true; 1134 } 1135 1136 switch (IntrID) { 1137 case Intrinsic::amdgcn_atomic_inc: 1138 case Intrinsic::amdgcn_atomic_dec: 1139 case Intrinsic::amdgcn_ds_ordered_add: 1140 case Intrinsic::amdgcn_ds_ordered_swap: 1141 case Intrinsic::amdgcn_ds_fadd: 1142 case Intrinsic::amdgcn_ds_fmin: 1143 case Intrinsic::amdgcn_ds_fmax: { 1144 Info.opc = ISD::INTRINSIC_W_CHAIN; 1145 Info.memVT = MVT::getVT(CI.getType()); 1146 Info.ptrVal = CI.getOperand(0); 1147 Info.align.reset(); 1148 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1149 1150 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1151 if (!Vol->isZero()) 1152 Info.flags |= MachineMemOperand::MOVolatile; 1153 1154 return true; 1155 } 1156 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1157 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1158 1159 Info.opc = ISD::INTRINSIC_W_CHAIN; 1160 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1161 Info.ptrVal = 1162 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1163 Info.align.reset(); 1164 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1165 1166 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1167 if (!Vol || !Vol->isZero()) 1168 Info.flags |= MachineMemOperand::MOVolatile; 1169 1170 return true; 1171 } 1172 case Intrinsic::amdgcn_ds_append: 1173 case Intrinsic::amdgcn_ds_consume: { 1174 Info.opc = ISD::INTRINSIC_W_CHAIN; 1175 Info.memVT = MVT::getVT(CI.getType()); 1176 Info.ptrVal = CI.getOperand(0); 1177 Info.align.reset(); 1178 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1179 1180 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1181 if (!Vol->isZero()) 1182 Info.flags |= MachineMemOperand::MOVolatile; 1183 1184 return true; 1185 } 1186 case Intrinsic::amdgcn_global_atomic_csub: { 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::MOVolatile; 1194 return true; 1195 } 1196 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1197 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1198 Info.opc = ISD::INTRINSIC_W_CHAIN; 1199 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1200 Info.ptrVal = 1201 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1202 Info.align.reset(); 1203 Info.flags = MachineMemOperand::MOLoad | 1204 MachineMemOperand::MODereferenceable; 1205 return true; 1206 } 1207 case Intrinsic::amdgcn_global_atomic_fadd: 1208 case Intrinsic::amdgcn_global_atomic_fmin: 1209 case Intrinsic::amdgcn_global_atomic_fmax: 1210 case Intrinsic::amdgcn_flat_atomic_fadd: 1211 case Intrinsic::amdgcn_flat_atomic_fmin: 1212 case Intrinsic::amdgcn_flat_atomic_fmax: { 1213 Info.opc = ISD::INTRINSIC_W_CHAIN; 1214 Info.memVT = MVT::getVT(CI.getType()); 1215 Info.ptrVal = CI.getOperand(0); 1216 Info.align.reset(); 1217 Info.flags = MachineMemOperand::MOLoad | 1218 MachineMemOperand::MOStore | 1219 MachineMemOperand::MODereferenceable | 1220 MachineMemOperand::MOVolatile; 1221 return true; 1222 } 1223 case Intrinsic::amdgcn_ds_gws_init: 1224 case Intrinsic::amdgcn_ds_gws_barrier: 1225 case Intrinsic::amdgcn_ds_gws_sema_v: 1226 case Intrinsic::amdgcn_ds_gws_sema_br: 1227 case Intrinsic::amdgcn_ds_gws_sema_p: 1228 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1229 Info.opc = ISD::INTRINSIC_VOID; 1230 1231 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1232 Info.ptrVal = 1233 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1234 1235 // This is an abstract access, but we need to specify a type and size. 1236 Info.memVT = MVT::i32; 1237 Info.size = 4; 1238 Info.align = Align(4); 1239 1240 Info.flags = MachineMemOperand::MOStore; 1241 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1242 Info.flags = MachineMemOperand::MOLoad; 1243 return true; 1244 } 1245 default: 1246 return false; 1247 } 1248 } 1249 1250 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1251 SmallVectorImpl<Value*> &Ops, 1252 Type *&AccessTy) const { 1253 switch (II->getIntrinsicID()) { 1254 case Intrinsic::amdgcn_atomic_inc: 1255 case Intrinsic::amdgcn_atomic_dec: 1256 case Intrinsic::amdgcn_ds_ordered_add: 1257 case Intrinsic::amdgcn_ds_ordered_swap: 1258 case Intrinsic::amdgcn_ds_append: 1259 case Intrinsic::amdgcn_ds_consume: 1260 case Intrinsic::amdgcn_ds_fadd: 1261 case Intrinsic::amdgcn_ds_fmin: 1262 case Intrinsic::amdgcn_ds_fmax: 1263 case Intrinsic::amdgcn_global_atomic_fadd: 1264 case Intrinsic::amdgcn_flat_atomic_fadd: 1265 case Intrinsic::amdgcn_flat_atomic_fmin: 1266 case Intrinsic::amdgcn_flat_atomic_fmax: 1267 case Intrinsic::amdgcn_global_atomic_csub: { 1268 Value *Ptr = II->getArgOperand(0); 1269 AccessTy = II->getType(); 1270 Ops.push_back(Ptr); 1271 return true; 1272 } 1273 default: 1274 return false; 1275 } 1276 } 1277 1278 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1279 if (!Subtarget->hasFlatInstOffsets()) { 1280 // Flat instructions do not have offsets, and only have the register 1281 // address. 1282 return AM.BaseOffs == 0 && AM.Scale == 0; 1283 } 1284 1285 return AM.Scale == 0 && 1286 (AM.BaseOffs == 0 || 1287 Subtarget->getInstrInfo()->isLegalFLATOffset( 1288 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1289 } 1290 1291 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1292 if (Subtarget->hasFlatGlobalInsts()) 1293 return AM.Scale == 0 && 1294 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1295 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1296 SIInstrFlags::FlatGlobal)); 1297 1298 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1299 // Assume the we will use FLAT for all global memory accesses 1300 // on VI. 1301 // FIXME: This assumption is currently wrong. On VI we still use 1302 // MUBUF instructions for the r + i addressing mode. As currently 1303 // implemented, the MUBUF instructions only work on buffer < 4GB. 1304 // It may be possible to support > 4GB buffers with MUBUF instructions, 1305 // by setting the stride value in the resource descriptor which would 1306 // increase the size limit to (stride * 4GB). However, this is risky, 1307 // because it has never been validated. 1308 return isLegalFlatAddressingMode(AM); 1309 } 1310 1311 return isLegalMUBUFAddressingMode(AM); 1312 } 1313 1314 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1315 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1316 // additionally can do r + r + i with addr64. 32-bit has more addressing 1317 // mode options. Depending on the resource constant, it can also do 1318 // (i64 r0) + (i32 r1) * (i14 i). 1319 // 1320 // Private arrays end up using a scratch buffer most of the time, so also 1321 // assume those use MUBUF instructions. Scratch loads / stores are currently 1322 // implemented as mubuf instructions with offen bit set, so slightly 1323 // different than the normal addr64. 1324 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1325 return false; 1326 1327 // FIXME: Since we can split immediate into soffset and immediate offset, 1328 // would it make sense to allow any immediate? 1329 1330 switch (AM.Scale) { 1331 case 0: // r + i or just i, depending on HasBaseReg. 1332 return true; 1333 case 1: 1334 return true; // We have r + r or r + i. 1335 case 2: 1336 if (AM.HasBaseReg) { 1337 // Reject 2 * r + r. 1338 return false; 1339 } 1340 1341 // Allow 2 * r as r + r 1342 // Or 2 * r + i is allowed as r + r + i. 1343 return true; 1344 default: // Don't allow n * r 1345 return false; 1346 } 1347 } 1348 1349 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1350 const AddrMode &AM, Type *Ty, 1351 unsigned AS, Instruction *I) const { 1352 // No global is ever allowed as a base. 1353 if (AM.BaseGV) 1354 return false; 1355 1356 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1357 return isLegalGlobalAddressingMode(AM); 1358 1359 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1360 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1361 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1362 // If the offset isn't a multiple of 4, it probably isn't going to be 1363 // correctly aligned. 1364 // FIXME: Can we get the real alignment here? 1365 if (AM.BaseOffs % 4 != 0) 1366 return isLegalMUBUFAddressingMode(AM); 1367 1368 // There are no SMRD extloads, so if we have to do a small type access we 1369 // will use a MUBUF load. 1370 // FIXME?: We also need to do this if unaligned, but we don't know the 1371 // alignment here. 1372 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1373 return isLegalGlobalAddressingMode(AM); 1374 1375 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1376 // SMRD instructions have an 8-bit, dword offset on SI. 1377 if (!isUInt<8>(AM.BaseOffs / 4)) 1378 return false; 1379 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1380 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1381 // in 8-bits, it can use a smaller encoding. 1382 if (!isUInt<32>(AM.BaseOffs / 4)) 1383 return false; 1384 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1385 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1386 if (!isUInt<20>(AM.BaseOffs)) 1387 return false; 1388 } else 1389 llvm_unreachable("unhandled generation"); 1390 1391 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1392 return true; 1393 1394 if (AM.Scale == 1 && AM.HasBaseReg) 1395 return true; 1396 1397 return false; 1398 1399 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1400 return isLegalMUBUFAddressingMode(AM); 1401 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1402 AS == AMDGPUAS::REGION_ADDRESS) { 1403 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1404 // field. 1405 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1406 // an 8-bit dword offset but we don't know the alignment here. 1407 if (!isUInt<16>(AM.BaseOffs)) 1408 return false; 1409 1410 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1411 return true; 1412 1413 if (AM.Scale == 1 && AM.HasBaseReg) 1414 return true; 1415 1416 return false; 1417 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1418 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1419 // For an unknown address space, this usually means that this is for some 1420 // reason being used for pure arithmetic, and not based on some addressing 1421 // computation. We don't have instructions that compute pointers with any 1422 // addressing modes, so treat them as having no offset like flat 1423 // instructions. 1424 return isLegalFlatAddressingMode(AM); 1425 } 1426 1427 // Assume a user alias of global for unknown address spaces. 1428 return isLegalGlobalAddressingMode(AM); 1429 } 1430 1431 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1432 const MachineFunction &MF) const { 1433 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1434 return (MemVT.getSizeInBits() <= 4 * 32); 1435 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1436 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1437 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1438 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1439 return (MemVT.getSizeInBits() <= 2 * 32); 1440 } 1441 return true; 1442 } 1443 1444 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1445 unsigned Size, unsigned AddrSpace, Align Alignment, 1446 MachineMemOperand::Flags Flags, bool *IsFast) const { 1447 if (IsFast) 1448 *IsFast = false; 1449 1450 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1451 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1452 // Check if alignment requirements for ds_read/write instructions are 1453 // disabled. 1454 if (Subtarget->hasUnalignedDSAccessEnabled() && 1455 !Subtarget->hasLDSMisalignedBug()) { 1456 if (IsFast) 1457 *IsFast = Alignment != Align(2); 1458 return true; 1459 } 1460 1461 // Either, the alignment requirements are "enabled", or there is an 1462 // unaligned LDS access related hardware bug though alignment requirements 1463 // are "disabled". In either case, we need to check for proper alignment 1464 // requirements. 1465 // 1466 if (Size == 64) { 1467 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1468 // can do a 4 byte aligned, 8 byte access in a single operation using 1469 // ds_read2/write2_b32 with adjacent offsets. 1470 bool AlignedBy4 = Alignment >= Align(4); 1471 if (IsFast) 1472 *IsFast = AlignedBy4; 1473 1474 return AlignedBy4; 1475 } 1476 if (Size == 96) { 1477 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1478 // gfx8 and older. 1479 bool AlignedBy16 = Alignment >= Align(16); 1480 if (IsFast) 1481 *IsFast = AlignedBy16; 1482 1483 return AlignedBy16; 1484 } 1485 if (Size == 128) { 1486 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1487 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1488 // single operation using ds_read2/write2_b64. 1489 bool AlignedBy8 = Alignment >= Align(8); 1490 if (IsFast) 1491 *IsFast = AlignedBy8; 1492 1493 return AlignedBy8; 1494 } 1495 } 1496 1497 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1498 bool AlignedBy4 = Alignment >= Align(4); 1499 if (IsFast) 1500 *IsFast = AlignedBy4; 1501 1502 return AlignedBy4 || 1503 Subtarget->enableFlatScratch() || 1504 Subtarget->hasUnalignedScratchAccess(); 1505 } 1506 1507 // FIXME: We have to be conservative here and assume that flat operations 1508 // will access scratch. If we had access to the IR function, then we 1509 // could determine if any private memory was used in the function. 1510 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1511 !Subtarget->hasUnalignedScratchAccess()) { 1512 bool AlignedBy4 = Alignment >= Align(4); 1513 if (IsFast) 1514 *IsFast = AlignedBy4; 1515 1516 return AlignedBy4; 1517 } 1518 1519 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1520 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1521 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1522 // If we have an uniform constant load, it still requires using a slow 1523 // buffer instruction if unaligned. 1524 if (IsFast) { 1525 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1526 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1527 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1528 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1529 Alignment >= Align(4) : Alignment != Align(2); 1530 } 1531 1532 return true; 1533 } 1534 1535 // Smaller than dword value must be aligned. 1536 if (Size < 32) 1537 return false; 1538 1539 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1540 // byte-address are ignored, thus forcing Dword alignment. 1541 // This applies to private, global, and constant memory. 1542 if (IsFast) 1543 *IsFast = true; 1544 1545 return Size >= 32 && Alignment >= Align(4); 1546 } 1547 1548 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1549 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1550 bool *IsFast) const { 1551 if (IsFast) 1552 *IsFast = false; 1553 1554 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1555 // which isn't a simple VT. 1556 // Until MVT is extended to handle this, simply check for the size and 1557 // rely on the condition below: allow accesses if the size is a multiple of 4. 1558 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1559 VT.getStoreSize() > 16)) { 1560 return false; 1561 } 1562 1563 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1564 Alignment, Flags, IsFast); 1565 } 1566 1567 EVT SITargetLowering::getOptimalMemOpType( 1568 const MemOp &Op, const AttributeList &FuncAttributes) const { 1569 // FIXME: Should account for address space here. 1570 1571 // The default fallback uses the private pointer size as a guess for a type to 1572 // use. Make sure we switch these to 64-bit accesses. 1573 1574 if (Op.size() >= 16 && 1575 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1576 return MVT::v4i32; 1577 1578 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1579 return MVT::v2i32; 1580 1581 // Use the default. 1582 return MVT::Other; 1583 } 1584 1585 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1586 const MemSDNode *MemNode = cast<MemSDNode>(N); 1587 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1588 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1589 return I && I->getMetadata("amdgpu.noclobber"); 1590 } 1591 1592 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1593 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1594 AS == AMDGPUAS::PRIVATE_ADDRESS; 1595 } 1596 1597 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1598 unsigned DestAS) const { 1599 // Flat -> private/local is a simple truncate. 1600 // Flat -> global is no-op 1601 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1602 return true; 1603 1604 const GCNTargetMachine &TM = 1605 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1606 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1607 } 1608 1609 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1610 const MemSDNode *MemNode = cast<MemSDNode>(N); 1611 1612 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1613 } 1614 1615 TargetLoweringBase::LegalizeTypeAction 1616 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1617 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1618 VT.getScalarType().bitsLE(MVT::i16)) 1619 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1620 return TargetLoweringBase::getPreferredVectorAction(VT); 1621 } 1622 1623 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1624 Type *Ty) const { 1625 // FIXME: Could be smarter if called for vector constants. 1626 return true; 1627 } 1628 1629 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1630 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1631 switch (Op) { 1632 case ISD::LOAD: 1633 case ISD::STORE: 1634 1635 // These operations are done with 32-bit instructions anyway. 1636 case ISD::AND: 1637 case ISD::OR: 1638 case ISD::XOR: 1639 case ISD::SELECT: 1640 // TODO: Extensions? 1641 return true; 1642 default: 1643 return false; 1644 } 1645 } 1646 1647 // SimplifySetCC uses this function to determine whether or not it should 1648 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1649 if (VT == MVT::i1 && Op == ISD::SETCC) 1650 return false; 1651 1652 return TargetLowering::isTypeDesirableForOp(Op, VT); 1653 } 1654 1655 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1656 const SDLoc &SL, 1657 SDValue Chain, 1658 uint64_t Offset) const { 1659 const DataLayout &DL = DAG.getDataLayout(); 1660 MachineFunction &MF = DAG.getMachineFunction(); 1661 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1662 1663 const ArgDescriptor *InputPtrReg; 1664 const TargetRegisterClass *RC; 1665 LLT ArgTy; 1666 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1667 1668 std::tie(InputPtrReg, RC, ArgTy) = 1669 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1670 1671 // We may not have the kernarg segment argument if we have no kernel 1672 // arguments. 1673 if (!InputPtrReg) 1674 return DAG.getConstant(0, SL, PtrVT); 1675 1676 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1677 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1678 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1679 1680 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1681 } 1682 1683 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1684 const SDLoc &SL) const { 1685 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1686 FIRST_IMPLICIT); 1687 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1688 } 1689 1690 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1691 const SDLoc &SL, SDValue Val, 1692 bool Signed, 1693 const ISD::InputArg *Arg) const { 1694 // First, if it is a widened vector, narrow it. 1695 if (VT.isVector() && 1696 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1697 EVT NarrowedVT = 1698 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1699 VT.getVectorNumElements()); 1700 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1701 DAG.getConstant(0, SL, MVT::i32)); 1702 } 1703 1704 // Then convert the vector elements or scalar value. 1705 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1706 VT.bitsLT(MemVT)) { 1707 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1708 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1709 } 1710 1711 if (MemVT.isFloatingPoint()) 1712 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1713 else if (Signed) 1714 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1715 else 1716 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1717 1718 return Val; 1719 } 1720 1721 SDValue SITargetLowering::lowerKernargMemParameter( 1722 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1723 uint64_t Offset, Align Alignment, bool Signed, 1724 const ISD::InputArg *Arg) const { 1725 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1726 1727 // Try to avoid using an extload by loading earlier than the argument address, 1728 // and extracting the relevant bits. The load should hopefully be merged with 1729 // the previous argument. 1730 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1731 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1732 int64_t AlignDownOffset = alignDown(Offset, 4); 1733 int64_t OffsetDiff = Offset - AlignDownOffset; 1734 1735 EVT IntVT = MemVT.changeTypeToInteger(); 1736 1737 // TODO: If we passed in the base kernel offset we could have a better 1738 // alignment than 4, but we don't really need it. 1739 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1740 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1741 MachineMemOperand::MODereferenceable | 1742 MachineMemOperand::MOInvariant); 1743 1744 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1745 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1746 1747 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1748 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1749 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1750 1751 1752 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1753 } 1754 1755 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1756 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1757 MachineMemOperand::MODereferenceable | 1758 MachineMemOperand::MOInvariant); 1759 1760 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1761 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1762 } 1763 1764 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1765 const SDLoc &SL, SDValue Chain, 1766 const ISD::InputArg &Arg) const { 1767 MachineFunction &MF = DAG.getMachineFunction(); 1768 MachineFrameInfo &MFI = MF.getFrameInfo(); 1769 1770 if (Arg.Flags.isByVal()) { 1771 unsigned Size = Arg.Flags.getByValSize(); 1772 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1773 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1774 } 1775 1776 unsigned ArgOffset = VA.getLocMemOffset(); 1777 unsigned ArgSize = VA.getValVT().getStoreSize(); 1778 1779 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1780 1781 // Create load nodes to retrieve arguments from the stack. 1782 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1783 SDValue ArgValue; 1784 1785 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1786 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1787 MVT MemVT = VA.getValVT(); 1788 1789 switch (VA.getLocInfo()) { 1790 default: 1791 break; 1792 case CCValAssign::BCvt: 1793 MemVT = VA.getLocVT(); 1794 break; 1795 case CCValAssign::SExt: 1796 ExtType = ISD::SEXTLOAD; 1797 break; 1798 case CCValAssign::ZExt: 1799 ExtType = ISD::ZEXTLOAD; 1800 break; 1801 case CCValAssign::AExt: 1802 ExtType = ISD::EXTLOAD; 1803 break; 1804 } 1805 1806 ArgValue = DAG.getExtLoad( 1807 ExtType, SL, VA.getLocVT(), Chain, FIN, 1808 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1809 MemVT); 1810 return ArgValue; 1811 } 1812 1813 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1814 const SIMachineFunctionInfo &MFI, 1815 EVT VT, 1816 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1817 const ArgDescriptor *Reg; 1818 const TargetRegisterClass *RC; 1819 LLT Ty; 1820 1821 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1822 if (!Reg) { 1823 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1824 // It's possible for a kernarg intrinsic call to appear in a kernel with 1825 // no allocated segment, in which case we do not add the user sgpr 1826 // argument, so just return null. 1827 return DAG.getConstant(0, SDLoc(), VT); 1828 } 1829 1830 // It's undefined behavior if a function marked with the amdgpu-no-* 1831 // attributes uses the corresponding intrinsic. 1832 return DAG.getUNDEF(VT); 1833 } 1834 1835 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1836 } 1837 1838 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1839 CallingConv::ID CallConv, 1840 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1841 FunctionType *FType, 1842 SIMachineFunctionInfo *Info) { 1843 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1844 const ISD::InputArg *Arg = &Ins[I]; 1845 1846 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1847 "vector type argument should have been split"); 1848 1849 // First check if it's a PS input addr. 1850 if (CallConv == CallingConv::AMDGPU_PS && 1851 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1852 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1853 1854 // Inconveniently only the first part of the split is marked as isSplit, 1855 // so skip to the end. We only want to increment PSInputNum once for the 1856 // entire split argument. 1857 if (Arg->Flags.isSplit()) { 1858 while (!Arg->Flags.isSplitEnd()) { 1859 assert((!Arg->VT.isVector() || 1860 Arg->VT.getScalarSizeInBits() == 16) && 1861 "unexpected vector split in ps argument type"); 1862 if (!SkipArg) 1863 Splits.push_back(*Arg); 1864 Arg = &Ins[++I]; 1865 } 1866 } 1867 1868 if (SkipArg) { 1869 // We can safely skip PS inputs. 1870 Skipped.set(Arg->getOrigArgIndex()); 1871 ++PSInputNum; 1872 continue; 1873 } 1874 1875 Info->markPSInputAllocated(PSInputNum); 1876 if (Arg->Used) 1877 Info->markPSInputEnabled(PSInputNum); 1878 1879 ++PSInputNum; 1880 } 1881 1882 Splits.push_back(*Arg); 1883 } 1884 } 1885 1886 // Allocate special inputs passed in VGPRs. 1887 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1888 MachineFunction &MF, 1889 const SIRegisterInfo &TRI, 1890 SIMachineFunctionInfo &Info) const { 1891 const LLT S32 = LLT::scalar(32); 1892 MachineRegisterInfo &MRI = MF.getRegInfo(); 1893 1894 if (Info.hasWorkItemIDX()) { 1895 Register Reg = AMDGPU::VGPR0; 1896 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1897 1898 CCInfo.AllocateReg(Reg); 1899 unsigned Mask = (Subtarget->hasPackedTID() && 1900 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1901 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1902 } 1903 1904 if (Info.hasWorkItemIDY()) { 1905 assert(Info.hasWorkItemIDX()); 1906 if (Subtarget->hasPackedTID()) { 1907 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1908 0x3ff << 10)); 1909 } else { 1910 unsigned Reg = AMDGPU::VGPR1; 1911 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1912 1913 CCInfo.AllocateReg(Reg); 1914 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1915 } 1916 } 1917 1918 if (Info.hasWorkItemIDZ()) { 1919 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1920 if (Subtarget->hasPackedTID()) { 1921 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1922 0x3ff << 20)); 1923 } else { 1924 unsigned Reg = AMDGPU::VGPR2; 1925 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1926 1927 CCInfo.AllocateReg(Reg); 1928 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1929 } 1930 } 1931 } 1932 1933 // Try to allocate a VGPR at the end of the argument list, or if no argument 1934 // VGPRs are left allocating a stack slot. 1935 // If \p Mask is is given it indicates bitfield position in the register. 1936 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1937 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1938 ArgDescriptor Arg = ArgDescriptor()) { 1939 if (Arg.isSet()) 1940 return ArgDescriptor::createArg(Arg, Mask); 1941 1942 ArrayRef<MCPhysReg> ArgVGPRs 1943 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1944 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1945 if (RegIdx == ArgVGPRs.size()) { 1946 // Spill to stack required. 1947 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1948 1949 return ArgDescriptor::createStack(Offset, Mask); 1950 } 1951 1952 unsigned Reg = ArgVGPRs[RegIdx]; 1953 Reg = CCInfo.AllocateReg(Reg); 1954 assert(Reg != AMDGPU::NoRegister); 1955 1956 MachineFunction &MF = CCInfo.getMachineFunction(); 1957 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1958 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1959 return ArgDescriptor::createRegister(Reg, Mask); 1960 } 1961 1962 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1963 const TargetRegisterClass *RC, 1964 unsigned NumArgRegs) { 1965 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1966 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1967 if (RegIdx == ArgSGPRs.size()) 1968 report_fatal_error("ran out of SGPRs for arguments"); 1969 1970 unsigned Reg = ArgSGPRs[RegIdx]; 1971 Reg = CCInfo.AllocateReg(Reg); 1972 assert(Reg != AMDGPU::NoRegister); 1973 1974 MachineFunction &MF = CCInfo.getMachineFunction(); 1975 MF.addLiveIn(Reg, RC); 1976 return ArgDescriptor::createRegister(Reg); 1977 } 1978 1979 // If this has a fixed position, we still should allocate the register in the 1980 // CCInfo state. Technically we could get away with this for values passed 1981 // outside of the normal argument range. 1982 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1983 const TargetRegisterClass *RC, 1984 MCRegister Reg) { 1985 Reg = CCInfo.AllocateReg(Reg); 1986 assert(Reg != AMDGPU::NoRegister); 1987 MachineFunction &MF = CCInfo.getMachineFunction(); 1988 MF.addLiveIn(Reg, RC); 1989 } 1990 1991 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1992 if (Arg) { 1993 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1994 Arg.getRegister()); 1995 } else 1996 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1997 } 1998 1999 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2000 if (Arg) { 2001 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2002 Arg.getRegister()); 2003 } else 2004 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2005 } 2006 2007 /// Allocate implicit function VGPR arguments at the end of allocated user 2008 /// arguments. 2009 void SITargetLowering::allocateSpecialInputVGPRs( 2010 CCState &CCInfo, MachineFunction &MF, 2011 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2012 const unsigned Mask = 0x3ff; 2013 ArgDescriptor Arg; 2014 2015 if (Info.hasWorkItemIDX()) { 2016 Arg = allocateVGPR32Input(CCInfo, Mask); 2017 Info.setWorkItemIDX(Arg); 2018 } 2019 2020 if (Info.hasWorkItemIDY()) { 2021 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2022 Info.setWorkItemIDY(Arg); 2023 } 2024 2025 if (Info.hasWorkItemIDZ()) 2026 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2027 } 2028 2029 /// Allocate implicit function VGPR arguments in fixed registers. 2030 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2031 CCState &CCInfo, MachineFunction &MF, 2032 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2033 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2034 if (!Reg) 2035 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2036 2037 const unsigned Mask = 0x3ff; 2038 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2039 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2040 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2041 } 2042 2043 void SITargetLowering::allocateSpecialInputSGPRs( 2044 CCState &CCInfo, 2045 MachineFunction &MF, 2046 const SIRegisterInfo &TRI, 2047 SIMachineFunctionInfo &Info) const { 2048 auto &ArgInfo = Info.getArgInfo(); 2049 2050 // We need to allocate these in place regardless of their use. 2051 const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI; 2052 2053 // TODO: Unify handling with private memory pointers. 2054 if (IsFixed || Info.hasDispatchPtr()) 2055 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2056 2057 if (IsFixed || Info.hasQueuePtr()) 2058 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2059 2060 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2061 // constant offset from the kernarg segment. 2062 if (IsFixed || Info.hasImplicitArgPtr()) 2063 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2064 2065 if (IsFixed || Info.hasDispatchID()) 2066 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2067 2068 // flat_scratch_init is not applicable for non-kernel functions. 2069 2070 if (IsFixed || Info.hasWorkGroupIDX()) 2071 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2072 2073 if (IsFixed || Info.hasWorkGroupIDY()) 2074 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2075 2076 if (IsFixed || Info.hasWorkGroupIDZ()) 2077 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2078 } 2079 2080 // Allocate special inputs passed in user SGPRs. 2081 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2082 MachineFunction &MF, 2083 const SIRegisterInfo &TRI, 2084 SIMachineFunctionInfo &Info) const { 2085 if (Info.hasImplicitBufferPtr()) { 2086 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2087 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2088 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2089 } 2090 2091 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2092 if (Info.hasPrivateSegmentBuffer()) { 2093 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2094 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2095 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2096 } 2097 2098 if (Info.hasDispatchPtr()) { 2099 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2100 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2101 CCInfo.AllocateReg(DispatchPtrReg); 2102 } 2103 2104 if (Info.hasQueuePtr()) { 2105 Register QueuePtrReg = Info.addQueuePtr(TRI); 2106 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2107 CCInfo.AllocateReg(QueuePtrReg); 2108 } 2109 2110 if (Info.hasKernargSegmentPtr()) { 2111 MachineRegisterInfo &MRI = MF.getRegInfo(); 2112 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2113 CCInfo.AllocateReg(InputPtrReg); 2114 2115 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2116 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2117 } 2118 2119 if (Info.hasDispatchID()) { 2120 Register DispatchIDReg = Info.addDispatchID(TRI); 2121 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2122 CCInfo.AllocateReg(DispatchIDReg); 2123 } 2124 2125 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2126 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2127 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2128 CCInfo.AllocateReg(FlatScratchInitReg); 2129 } 2130 2131 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2132 // these from the dispatch pointer. 2133 } 2134 2135 // Allocate special input registers that are initialized per-wave. 2136 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2137 MachineFunction &MF, 2138 SIMachineFunctionInfo &Info, 2139 CallingConv::ID CallConv, 2140 bool IsShader) const { 2141 if (Info.hasWorkGroupIDX()) { 2142 Register Reg = Info.addWorkGroupIDX(); 2143 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2144 CCInfo.AllocateReg(Reg); 2145 } 2146 2147 if (Info.hasWorkGroupIDY()) { 2148 Register Reg = Info.addWorkGroupIDY(); 2149 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2150 CCInfo.AllocateReg(Reg); 2151 } 2152 2153 if (Info.hasWorkGroupIDZ()) { 2154 Register Reg = Info.addWorkGroupIDZ(); 2155 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2156 CCInfo.AllocateReg(Reg); 2157 } 2158 2159 if (Info.hasWorkGroupInfo()) { 2160 Register Reg = Info.addWorkGroupInfo(); 2161 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2162 CCInfo.AllocateReg(Reg); 2163 } 2164 2165 if (Info.hasPrivateSegmentWaveByteOffset()) { 2166 // Scratch wave offset passed in system SGPR. 2167 unsigned PrivateSegmentWaveByteOffsetReg; 2168 2169 if (IsShader) { 2170 PrivateSegmentWaveByteOffsetReg = 2171 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2172 2173 // This is true if the scratch wave byte offset doesn't have a fixed 2174 // location. 2175 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2176 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2177 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2178 } 2179 } else 2180 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2181 2182 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2183 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2184 } 2185 } 2186 2187 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2188 MachineFunction &MF, 2189 const SIRegisterInfo &TRI, 2190 SIMachineFunctionInfo &Info) { 2191 // Now that we've figured out where the scratch register inputs are, see if 2192 // should reserve the arguments and use them directly. 2193 MachineFrameInfo &MFI = MF.getFrameInfo(); 2194 bool HasStackObjects = MFI.hasStackObjects(); 2195 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2196 2197 // Record that we know we have non-spill stack objects so we don't need to 2198 // check all stack objects later. 2199 if (HasStackObjects) 2200 Info.setHasNonSpillStackObjects(true); 2201 2202 // Everything live out of a block is spilled with fast regalloc, so it's 2203 // almost certain that spilling will be required. 2204 if (TM.getOptLevel() == CodeGenOpt::None) 2205 HasStackObjects = true; 2206 2207 // For now assume stack access is needed in any callee functions, so we need 2208 // the scratch registers to pass in. 2209 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2210 2211 if (!ST.enableFlatScratch()) { 2212 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2213 // If we have stack objects, we unquestionably need the private buffer 2214 // resource. For the Code Object V2 ABI, this will be the first 4 user 2215 // SGPR inputs. We can reserve those and use them directly. 2216 2217 Register PrivateSegmentBufferReg = 2218 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2219 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2220 } else { 2221 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2222 // We tentatively reserve the last registers (skipping the last registers 2223 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2224 // we'll replace these with the ones immediately after those which were 2225 // really allocated. In the prologue copies will be inserted from the 2226 // argument to these reserved registers. 2227 2228 // Without HSA, relocations are used for the scratch pointer and the 2229 // buffer resource setup is always inserted in the prologue. Scratch wave 2230 // offset is still in an input SGPR. 2231 Info.setScratchRSrcReg(ReservedBufferReg); 2232 } 2233 } 2234 2235 MachineRegisterInfo &MRI = MF.getRegInfo(); 2236 2237 // For entry functions we have to set up the stack pointer if we use it, 2238 // whereas non-entry functions get this "for free". This means there is no 2239 // intrinsic advantage to using S32 over S34 in cases where we do not have 2240 // calls but do need a frame pointer (i.e. if we are requested to have one 2241 // because frame pointer elimination is disabled). To keep things simple we 2242 // only ever use S32 as the call ABI stack pointer, and so using it does not 2243 // imply we need a separate frame pointer. 2244 // 2245 // Try to use s32 as the SP, but move it if it would interfere with input 2246 // arguments. This won't work with calls though. 2247 // 2248 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2249 // registers. 2250 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2251 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2252 } else { 2253 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2254 2255 if (MFI.hasCalls()) 2256 report_fatal_error("call in graphics shader with too many input SGPRs"); 2257 2258 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2259 if (!MRI.isLiveIn(Reg)) { 2260 Info.setStackPtrOffsetReg(Reg); 2261 break; 2262 } 2263 } 2264 2265 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2266 report_fatal_error("failed to find register for SP"); 2267 } 2268 2269 // hasFP should be accurate for entry functions even before the frame is 2270 // finalized, because it does not rely on the known stack size, only 2271 // properties like whether variable sized objects are present. 2272 if (ST.getFrameLowering()->hasFP(MF)) { 2273 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2274 } 2275 } 2276 2277 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2278 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2279 return !Info->isEntryFunction(); 2280 } 2281 2282 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2283 2284 } 2285 2286 void SITargetLowering::insertCopiesSplitCSR( 2287 MachineBasicBlock *Entry, 2288 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2289 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2290 2291 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2292 if (!IStart) 2293 return; 2294 2295 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2296 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2297 MachineBasicBlock::iterator MBBI = Entry->begin(); 2298 for (const MCPhysReg *I = IStart; *I; ++I) { 2299 const TargetRegisterClass *RC = nullptr; 2300 if (AMDGPU::SReg_64RegClass.contains(*I)) 2301 RC = &AMDGPU::SGPR_64RegClass; 2302 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2303 RC = &AMDGPU::SGPR_32RegClass; 2304 else 2305 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2306 2307 Register NewVR = MRI->createVirtualRegister(RC); 2308 // Create copy from CSR to a virtual register. 2309 Entry->addLiveIn(*I); 2310 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2311 .addReg(*I); 2312 2313 // Insert the copy-back instructions right before the terminator. 2314 for (auto *Exit : Exits) 2315 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2316 TII->get(TargetOpcode::COPY), *I) 2317 .addReg(NewVR); 2318 } 2319 } 2320 2321 SDValue SITargetLowering::LowerFormalArguments( 2322 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2323 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2324 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2325 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2326 2327 MachineFunction &MF = DAG.getMachineFunction(); 2328 const Function &Fn = MF.getFunction(); 2329 FunctionType *FType = MF.getFunction().getFunctionType(); 2330 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2331 2332 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2333 DiagnosticInfoUnsupported NoGraphicsHSA( 2334 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2335 DAG.getContext()->diagnose(NoGraphicsHSA); 2336 return DAG.getEntryNode(); 2337 } 2338 2339 Info->allocateModuleLDSGlobal(Fn.getParent()); 2340 2341 SmallVector<ISD::InputArg, 16> Splits; 2342 SmallVector<CCValAssign, 16> ArgLocs; 2343 BitVector Skipped(Ins.size()); 2344 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2345 *DAG.getContext()); 2346 2347 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2348 bool IsKernel = AMDGPU::isKernel(CallConv); 2349 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2350 2351 if (IsGraphics) { 2352 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2353 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2354 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2355 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2356 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2357 !Info->hasWorkItemIDZ()); 2358 } 2359 2360 if (CallConv == CallingConv::AMDGPU_PS) { 2361 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2362 2363 // At least one interpolation mode must be enabled or else the GPU will 2364 // hang. 2365 // 2366 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2367 // set PSInputAddr, the user wants to enable some bits after the compilation 2368 // based on run-time states. Since we can't know what the final PSInputEna 2369 // will look like, so we shouldn't do anything here and the user should take 2370 // responsibility for the correct programming. 2371 // 2372 // Otherwise, the following restrictions apply: 2373 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2374 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2375 // enabled too. 2376 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2377 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2378 CCInfo.AllocateReg(AMDGPU::VGPR0); 2379 CCInfo.AllocateReg(AMDGPU::VGPR1); 2380 Info->markPSInputAllocated(0); 2381 Info->markPSInputEnabled(0); 2382 } 2383 if (Subtarget->isAmdPalOS()) { 2384 // For isAmdPalOS, the user does not enable some bits after compilation 2385 // based on run-time states; the register values being generated here are 2386 // the final ones set in hardware. Therefore we need to apply the 2387 // workaround to PSInputAddr and PSInputEnable together. (The case where 2388 // a bit is set in PSInputAddr but not PSInputEnable is where the 2389 // frontend set up an input arg for a particular interpolation mode, but 2390 // nothing uses that input arg. Really we should have an earlier pass 2391 // that removes such an arg.) 2392 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2393 if ((PsInputBits & 0x7F) == 0 || 2394 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2395 Info->markPSInputEnabled( 2396 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2397 } 2398 } else if (IsKernel) { 2399 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2400 } else { 2401 Splits.append(Ins.begin(), Ins.end()); 2402 } 2403 2404 if (IsEntryFunc) { 2405 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2406 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2407 } else { 2408 // For the fixed ABI, pass workitem IDs in the last argument register. 2409 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2410 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2411 } 2412 2413 if (IsKernel) { 2414 analyzeFormalArgumentsCompute(CCInfo, Ins); 2415 } else { 2416 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2417 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2418 } 2419 2420 SmallVector<SDValue, 16> Chains; 2421 2422 // FIXME: This is the minimum kernel argument alignment. We should improve 2423 // this to the maximum alignment of the arguments. 2424 // 2425 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2426 // kern arg offset. 2427 const Align KernelArgBaseAlign = Align(16); 2428 2429 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2430 const ISD::InputArg &Arg = Ins[i]; 2431 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2432 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2433 continue; 2434 } 2435 2436 CCValAssign &VA = ArgLocs[ArgIdx++]; 2437 MVT VT = VA.getLocVT(); 2438 2439 if (IsEntryFunc && VA.isMemLoc()) { 2440 VT = Ins[i].VT; 2441 EVT MemVT = VA.getLocVT(); 2442 2443 const uint64_t Offset = VA.getLocMemOffset(); 2444 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2445 2446 if (Arg.Flags.isByRef()) { 2447 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2448 2449 const GCNTargetMachine &TM = 2450 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2451 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2452 Arg.Flags.getPointerAddrSpace())) { 2453 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2454 Arg.Flags.getPointerAddrSpace()); 2455 } 2456 2457 InVals.push_back(Ptr); 2458 continue; 2459 } 2460 2461 SDValue Arg = lowerKernargMemParameter( 2462 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2463 Chains.push_back(Arg.getValue(1)); 2464 2465 auto *ParamTy = 2466 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2467 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2468 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2469 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2470 // On SI local pointers are just offsets into LDS, so they are always 2471 // less than 16-bits. On CI and newer they could potentially be 2472 // real pointers, so we can't guarantee their size. 2473 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2474 DAG.getValueType(MVT::i16)); 2475 } 2476 2477 InVals.push_back(Arg); 2478 continue; 2479 } else if (!IsEntryFunc && VA.isMemLoc()) { 2480 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2481 InVals.push_back(Val); 2482 if (!Arg.Flags.isByVal()) 2483 Chains.push_back(Val.getValue(1)); 2484 continue; 2485 } 2486 2487 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2488 2489 Register Reg = VA.getLocReg(); 2490 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2491 EVT ValVT = VA.getValVT(); 2492 2493 Reg = MF.addLiveIn(Reg, RC); 2494 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2495 2496 if (Arg.Flags.isSRet()) { 2497 // The return object should be reasonably addressable. 2498 2499 // FIXME: This helps when the return is a real sret. If it is a 2500 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2501 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2502 unsigned NumBits 2503 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2504 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2505 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2506 } 2507 2508 // If this is an 8 or 16-bit value, it is really passed promoted 2509 // to 32 bits. Insert an assert[sz]ext to capture this, then 2510 // truncate to the right size. 2511 switch (VA.getLocInfo()) { 2512 case CCValAssign::Full: 2513 break; 2514 case CCValAssign::BCvt: 2515 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2516 break; 2517 case CCValAssign::SExt: 2518 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2519 DAG.getValueType(ValVT)); 2520 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2521 break; 2522 case CCValAssign::ZExt: 2523 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2524 DAG.getValueType(ValVT)); 2525 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2526 break; 2527 case CCValAssign::AExt: 2528 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2529 break; 2530 default: 2531 llvm_unreachable("Unknown loc info!"); 2532 } 2533 2534 InVals.push_back(Val); 2535 } 2536 2537 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2538 // Special inputs come after user arguments. 2539 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2540 } 2541 2542 // Start adding system SGPRs. 2543 if (IsEntryFunc) { 2544 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2545 } else { 2546 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2547 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2548 } 2549 2550 auto &ArgUsageInfo = 2551 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2552 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2553 2554 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2555 Info->setBytesInStackArgArea(StackArgSize); 2556 2557 return Chains.empty() ? Chain : 2558 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2559 } 2560 2561 // TODO: If return values can't fit in registers, we should return as many as 2562 // possible in registers before passing on stack. 2563 bool SITargetLowering::CanLowerReturn( 2564 CallingConv::ID CallConv, 2565 MachineFunction &MF, bool IsVarArg, 2566 const SmallVectorImpl<ISD::OutputArg> &Outs, 2567 LLVMContext &Context) const { 2568 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2569 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2570 // for shaders. Vector types should be explicitly handled by CC. 2571 if (AMDGPU::isEntryFunctionCC(CallConv)) 2572 return true; 2573 2574 SmallVector<CCValAssign, 16> RVLocs; 2575 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2576 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2577 } 2578 2579 SDValue 2580 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2581 bool isVarArg, 2582 const SmallVectorImpl<ISD::OutputArg> &Outs, 2583 const SmallVectorImpl<SDValue> &OutVals, 2584 const SDLoc &DL, SelectionDAG &DAG) const { 2585 MachineFunction &MF = DAG.getMachineFunction(); 2586 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2587 2588 if (AMDGPU::isKernel(CallConv)) { 2589 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2590 OutVals, DL, DAG); 2591 } 2592 2593 bool IsShader = AMDGPU::isShader(CallConv); 2594 2595 Info->setIfReturnsVoid(Outs.empty()); 2596 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2597 2598 // CCValAssign - represent the assignment of the return value to a location. 2599 SmallVector<CCValAssign, 48> RVLocs; 2600 SmallVector<ISD::OutputArg, 48> Splits; 2601 2602 // CCState - Info about the registers and stack slots. 2603 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2604 *DAG.getContext()); 2605 2606 // Analyze outgoing return values. 2607 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2608 2609 SDValue Flag; 2610 SmallVector<SDValue, 48> RetOps; 2611 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2612 2613 // Add return address for callable functions. 2614 if (!Info->isEntryFunction()) { 2615 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2616 SDValue ReturnAddrReg = CreateLiveInRegister( 2617 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2618 2619 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2620 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2621 MVT::i64); 2622 Chain = 2623 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2624 Flag = Chain.getValue(1); 2625 RetOps.push_back(ReturnAddrVirtualReg); 2626 } 2627 2628 // Copy the result values into the output registers. 2629 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2630 ++I, ++RealRVLocIdx) { 2631 CCValAssign &VA = RVLocs[I]; 2632 assert(VA.isRegLoc() && "Can only return in registers!"); 2633 // TODO: Partially return in registers if return values don't fit. 2634 SDValue Arg = OutVals[RealRVLocIdx]; 2635 2636 // Copied from other backends. 2637 switch (VA.getLocInfo()) { 2638 case CCValAssign::Full: 2639 break; 2640 case CCValAssign::BCvt: 2641 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2642 break; 2643 case CCValAssign::SExt: 2644 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2645 break; 2646 case CCValAssign::ZExt: 2647 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2648 break; 2649 case CCValAssign::AExt: 2650 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2651 break; 2652 default: 2653 llvm_unreachable("Unknown loc info!"); 2654 } 2655 2656 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2657 Flag = Chain.getValue(1); 2658 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2659 } 2660 2661 // FIXME: Does sret work properly? 2662 if (!Info->isEntryFunction()) { 2663 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2664 const MCPhysReg *I = 2665 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2666 if (I) { 2667 for (; *I; ++I) { 2668 if (AMDGPU::SReg_64RegClass.contains(*I)) 2669 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2670 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2671 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2672 else 2673 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2674 } 2675 } 2676 } 2677 2678 // Update chain and glue. 2679 RetOps[0] = Chain; 2680 if (Flag.getNode()) 2681 RetOps.push_back(Flag); 2682 2683 unsigned Opc = AMDGPUISD::ENDPGM; 2684 if (!IsWaveEnd) 2685 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2686 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2687 } 2688 2689 SDValue SITargetLowering::LowerCallResult( 2690 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2691 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2692 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2693 SDValue ThisVal) const { 2694 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2695 2696 // Assign locations to each value returned by this call. 2697 SmallVector<CCValAssign, 16> RVLocs; 2698 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2699 *DAG.getContext()); 2700 CCInfo.AnalyzeCallResult(Ins, RetCC); 2701 2702 // Copy all of the result registers out of their specified physreg. 2703 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2704 CCValAssign VA = RVLocs[i]; 2705 SDValue Val; 2706 2707 if (VA.isRegLoc()) { 2708 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2709 Chain = Val.getValue(1); 2710 InFlag = Val.getValue(2); 2711 } else if (VA.isMemLoc()) { 2712 report_fatal_error("TODO: return values in memory"); 2713 } else 2714 llvm_unreachable("unknown argument location type"); 2715 2716 switch (VA.getLocInfo()) { 2717 case CCValAssign::Full: 2718 break; 2719 case CCValAssign::BCvt: 2720 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2721 break; 2722 case CCValAssign::ZExt: 2723 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2724 DAG.getValueType(VA.getValVT())); 2725 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2726 break; 2727 case CCValAssign::SExt: 2728 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2729 DAG.getValueType(VA.getValVT())); 2730 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2731 break; 2732 case CCValAssign::AExt: 2733 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2734 break; 2735 default: 2736 llvm_unreachable("Unknown loc info!"); 2737 } 2738 2739 InVals.push_back(Val); 2740 } 2741 2742 return Chain; 2743 } 2744 2745 // Add code to pass special inputs required depending on used features separate 2746 // from the explicit user arguments present in the IR. 2747 void SITargetLowering::passSpecialInputs( 2748 CallLoweringInfo &CLI, 2749 CCState &CCInfo, 2750 const SIMachineFunctionInfo &Info, 2751 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2752 SmallVectorImpl<SDValue> &MemOpChains, 2753 SDValue Chain) const { 2754 // If we don't have a call site, this was a call inserted by 2755 // legalization. These can never use special inputs. 2756 if (!CLI.CB) 2757 return; 2758 2759 SelectionDAG &DAG = CLI.DAG; 2760 const SDLoc &DL = CLI.DL; 2761 2762 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2763 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2764 2765 const AMDGPUFunctionArgInfo *CalleeArgInfo 2766 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2767 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2768 auto &ArgUsageInfo = 2769 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2770 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2771 } 2772 2773 // TODO: Unify with private memory register handling. This is complicated by 2774 // the fact that at least in kernels, the input argument is not necessarily 2775 // in the same location as the input. 2776 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2777 StringLiteral> ImplicitAttrs[] = { 2778 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2779 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2780 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2781 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2782 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2783 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2784 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2785 }; 2786 2787 for (auto Attr : ImplicitAttrs) { 2788 const ArgDescriptor *OutgoingArg; 2789 const TargetRegisterClass *ArgRC; 2790 LLT ArgTy; 2791 2792 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2793 2794 // If the callee does not use the attribute value, skip copying the value. 2795 if (CLI.CB->hasFnAttr(Attr.second)) 2796 continue; 2797 2798 std::tie(OutgoingArg, ArgRC, ArgTy) = 2799 CalleeArgInfo->getPreloadedValue(InputID); 2800 if (!OutgoingArg) 2801 continue; 2802 2803 const ArgDescriptor *IncomingArg; 2804 const TargetRegisterClass *IncomingArgRC; 2805 LLT Ty; 2806 std::tie(IncomingArg, IncomingArgRC, Ty) = 2807 CallerArgInfo.getPreloadedValue(InputID); 2808 assert(IncomingArgRC == ArgRC); 2809 2810 // All special arguments are ints for now. 2811 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2812 SDValue InputReg; 2813 2814 if (IncomingArg) { 2815 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2816 } else { 2817 // The implicit arg ptr is special because it doesn't have a corresponding 2818 // input for kernels, and is computed from the kernarg segment pointer. 2819 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2820 InputReg = getImplicitArgPtr(DAG, DL); 2821 } 2822 2823 if (OutgoingArg->isRegister()) { 2824 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2825 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2826 report_fatal_error("failed to allocate implicit input argument"); 2827 } else { 2828 unsigned SpecialArgOffset = 2829 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2830 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2831 SpecialArgOffset); 2832 MemOpChains.push_back(ArgStore); 2833 } 2834 } 2835 2836 // Pack workitem IDs into a single register or pass it as is if already 2837 // packed. 2838 const ArgDescriptor *OutgoingArg; 2839 const TargetRegisterClass *ArgRC; 2840 LLT Ty; 2841 2842 std::tie(OutgoingArg, ArgRC, Ty) = 2843 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2844 if (!OutgoingArg) 2845 std::tie(OutgoingArg, ArgRC, Ty) = 2846 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2847 if (!OutgoingArg) 2848 std::tie(OutgoingArg, ArgRC, Ty) = 2849 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2850 if (!OutgoingArg) 2851 return; 2852 2853 const ArgDescriptor *IncomingArgX = std::get<0>( 2854 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2855 const ArgDescriptor *IncomingArgY = std::get<0>( 2856 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2857 const ArgDescriptor *IncomingArgZ = std::get<0>( 2858 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2859 2860 SDValue InputReg; 2861 SDLoc SL; 2862 2863 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2864 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2865 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2866 2867 // If incoming ids are not packed we need to pack them. 2868 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2869 NeedWorkItemIDX) 2870 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2871 2872 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2873 NeedWorkItemIDY) { 2874 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2875 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2876 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2877 InputReg = InputReg.getNode() ? 2878 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2879 } 2880 2881 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2882 NeedWorkItemIDZ) { 2883 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2884 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2885 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2886 InputReg = InputReg.getNode() ? 2887 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2888 } 2889 2890 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2891 // Workitem ids are already packed, any of present incoming arguments 2892 // will carry all required fields. 2893 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2894 IncomingArgX ? *IncomingArgX : 2895 IncomingArgY ? *IncomingArgY : 2896 *IncomingArgZ, ~0u); 2897 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2898 } 2899 2900 if (OutgoingArg->isRegister()) { 2901 if (InputReg) 2902 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2903 2904 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2905 } else { 2906 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2907 if (InputReg) { 2908 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2909 SpecialArgOffset); 2910 MemOpChains.push_back(ArgStore); 2911 } 2912 } 2913 } 2914 2915 static bool canGuaranteeTCO(CallingConv::ID CC) { 2916 return CC == CallingConv::Fast; 2917 } 2918 2919 /// Return true if we might ever do TCO for calls with this calling convention. 2920 static bool mayTailCallThisCC(CallingConv::ID CC) { 2921 switch (CC) { 2922 case CallingConv::C: 2923 case CallingConv::AMDGPU_Gfx: 2924 return true; 2925 default: 2926 return canGuaranteeTCO(CC); 2927 } 2928 } 2929 2930 bool SITargetLowering::isEligibleForTailCallOptimization( 2931 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2932 const SmallVectorImpl<ISD::OutputArg> &Outs, 2933 const SmallVectorImpl<SDValue> &OutVals, 2934 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2935 if (!mayTailCallThisCC(CalleeCC)) 2936 return false; 2937 2938 // For a divergent call target, we need to do a waterfall loop over the 2939 // possible callees which precludes us from using a simple jump. 2940 if (Callee->isDivergent()) 2941 return false; 2942 2943 MachineFunction &MF = DAG.getMachineFunction(); 2944 const Function &CallerF = MF.getFunction(); 2945 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2946 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2947 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2948 2949 // Kernels aren't callable, and don't have a live in return address so it 2950 // doesn't make sense to do a tail call with entry functions. 2951 if (!CallerPreserved) 2952 return false; 2953 2954 bool CCMatch = CallerCC == CalleeCC; 2955 2956 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2957 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2958 return true; 2959 return false; 2960 } 2961 2962 // TODO: Can we handle var args? 2963 if (IsVarArg) 2964 return false; 2965 2966 for (const Argument &Arg : CallerF.args()) { 2967 if (Arg.hasByValAttr()) 2968 return false; 2969 } 2970 2971 LLVMContext &Ctx = *DAG.getContext(); 2972 2973 // Check that the call results are passed in the same way. 2974 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2975 CCAssignFnForCall(CalleeCC, IsVarArg), 2976 CCAssignFnForCall(CallerCC, IsVarArg))) 2977 return false; 2978 2979 // The callee has to preserve all registers the caller needs to preserve. 2980 if (!CCMatch) { 2981 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2982 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2983 return false; 2984 } 2985 2986 // Nothing more to check if the callee is taking no arguments. 2987 if (Outs.empty()) 2988 return true; 2989 2990 SmallVector<CCValAssign, 16> ArgLocs; 2991 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2992 2993 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2994 2995 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2996 // If the stack arguments for this call do not fit into our own save area then 2997 // the call cannot be made tail. 2998 // TODO: Is this really necessary? 2999 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3000 return false; 3001 3002 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3003 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3004 } 3005 3006 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3007 if (!CI->isTailCall()) 3008 return false; 3009 3010 const Function *ParentFn = CI->getParent()->getParent(); 3011 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3012 return false; 3013 return true; 3014 } 3015 3016 // The wave scratch offset register is used as the global base pointer. 3017 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3018 SmallVectorImpl<SDValue> &InVals) const { 3019 SelectionDAG &DAG = CLI.DAG; 3020 const SDLoc &DL = CLI.DL; 3021 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3022 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3023 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3024 SDValue Chain = CLI.Chain; 3025 SDValue Callee = CLI.Callee; 3026 bool &IsTailCall = CLI.IsTailCall; 3027 CallingConv::ID CallConv = CLI.CallConv; 3028 bool IsVarArg = CLI.IsVarArg; 3029 bool IsSibCall = false; 3030 bool IsThisReturn = false; 3031 MachineFunction &MF = DAG.getMachineFunction(); 3032 3033 if (Callee.isUndef() || isNullConstant(Callee)) { 3034 if (!CLI.IsTailCall) { 3035 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3036 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3037 } 3038 3039 return Chain; 3040 } 3041 3042 if (IsVarArg) { 3043 return lowerUnhandledCall(CLI, InVals, 3044 "unsupported call to variadic function "); 3045 } 3046 3047 if (!CLI.CB) 3048 report_fatal_error("unsupported libcall legalization"); 3049 3050 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3051 return lowerUnhandledCall(CLI, InVals, 3052 "unsupported required tail call to function "); 3053 } 3054 3055 if (AMDGPU::isShader(CallConv)) { 3056 // Note the issue is with the CC of the called function, not of the call 3057 // itself. 3058 return lowerUnhandledCall(CLI, InVals, 3059 "unsupported call to a shader function "); 3060 } 3061 3062 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3063 CallConv != CallingConv::AMDGPU_Gfx) { 3064 // Only allow calls with specific calling conventions. 3065 return lowerUnhandledCall(CLI, InVals, 3066 "unsupported calling convention for call from " 3067 "graphics shader of function "); 3068 } 3069 3070 if (IsTailCall) { 3071 IsTailCall = isEligibleForTailCallOptimization( 3072 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3073 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3074 report_fatal_error("failed to perform tail call elimination on a call " 3075 "site marked musttail"); 3076 } 3077 3078 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3079 3080 // A sibling call is one where we're under the usual C ABI and not planning 3081 // to change that but can still do a tail call: 3082 if (!TailCallOpt && IsTailCall) 3083 IsSibCall = true; 3084 3085 if (IsTailCall) 3086 ++NumTailCalls; 3087 } 3088 3089 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3090 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3091 SmallVector<SDValue, 8> MemOpChains; 3092 3093 // Analyze operands of the call, assigning locations to each operand. 3094 SmallVector<CCValAssign, 16> ArgLocs; 3095 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3096 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3097 3098 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3099 CallConv != CallingConv::AMDGPU_Gfx) { 3100 // With a fixed ABI, allocate fixed registers before user arguments. 3101 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3102 } 3103 3104 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3105 3106 // Get a count of how many bytes are to be pushed on the stack. 3107 unsigned NumBytes = CCInfo.getNextStackOffset(); 3108 3109 if (IsSibCall) { 3110 // Since we're not changing the ABI to make this a tail call, the memory 3111 // operands are already available in the caller's incoming argument space. 3112 NumBytes = 0; 3113 } 3114 3115 // FPDiff is the byte offset of the call's argument area from the callee's. 3116 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3117 // by this amount for a tail call. In a sibling call it must be 0 because the 3118 // caller will deallocate the entire stack and the callee still expects its 3119 // arguments to begin at SP+0. Completely unused for non-tail calls. 3120 int32_t FPDiff = 0; 3121 MachineFrameInfo &MFI = MF.getFrameInfo(); 3122 3123 // Adjust the stack pointer for the new arguments... 3124 // These operations are automatically eliminated by the prolog/epilog pass 3125 if (!IsSibCall) { 3126 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3127 3128 if (!Subtarget->enableFlatScratch()) { 3129 SmallVector<SDValue, 4> CopyFromChains; 3130 3131 // In the HSA case, this should be an identity copy. 3132 SDValue ScratchRSrcReg 3133 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3134 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3135 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3136 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3137 } 3138 } 3139 3140 MVT PtrVT = MVT::i32; 3141 3142 // Walk the register/memloc assignments, inserting copies/loads. 3143 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3144 CCValAssign &VA = ArgLocs[i]; 3145 SDValue Arg = OutVals[i]; 3146 3147 // Promote the value if needed. 3148 switch (VA.getLocInfo()) { 3149 case CCValAssign::Full: 3150 break; 3151 case CCValAssign::BCvt: 3152 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3153 break; 3154 case CCValAssign::ZExt: 3155 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3156 break; 3157 case CCValAssign::SExt: 3158 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3159 break; 3160 case CCValAssign::AExt: 3161 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3162 break; 3163 case CCValAssign::FPExt: 3164 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3165 break; 3166 default: 3167 llvm_unreachable("Unknown loc info!"); 3168 } 3169 3170 if (VA.isRegLoc()) { 3171 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3172 } else { 3173 assert(VA.isMemLoc()); 3174 3175 SDValue DstAddr; 3176 MachinePointerInfo DstInfo; 3177 3178 unsigned LocMemOffset = VA.getLocMemOffset(); 3179 int32_t Offset = LocMemOffset; 3180 3181 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3182 MaybeAlign Alignment; 3183 3184 if (IsTailCall) { 3185 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3186 unsigned OpSize = Flags.isByVal() ? 3187 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3188 3189 // FIXME: We can have better than the minimum byval required alignment. 3190 Alignment = 3191 Flags.isByVal() 3192 ? Flags.getNonZeroByValAlign() 3193 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3194 3195 Offset = Offset + FPDiff; 3196 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3197 3198 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3199 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3200 3201 // Make sure any stack arguments overlapping with where we're storing 3202 // are loaded before this eventual operation. Otherwise they'll be 3203 // clobbered. 3204 3205 // FIXME: Why is this really necessary? This seems to just result in a 3206 // lot of code to copy the stack and write them back to the same 3207 // locations, which are supposed to be immutable? 3208 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3209 } else { 3210 // Stores to the argument stack area are relative to the stack pointer. 3211 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3212 MVT::i32); 3213 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3214 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3215 Alignment = 3216 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3217 } 3218 3219 if (Outs[i].Flags.isByVal()) { 3220 SDValue SizeNode = 3221 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3222 SDValue Cpy = 3223 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3224 Outs[i].Flags.getNonZeroByValAlign(), 3225 /*isVol = */ false, /*AlwaysInline = */ true, 3226 /*isTailCall = */ false, DstInfo, 3227 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3228 3229 MemOpChains.push_back(Cpy); 3230 } else { 3231 SDValue Store = 3232 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3233 MemOpChains.push_back(Store); 3234 } 3235 } 3236 } 3237 3238 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3239 CallConv != CallingConv::AMDGPU_Gfx) { 3240 // Copy special input registers after user input arguments. 3241 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3242 } 3243 3244 if (!MemOpChains.empty()) 3245 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3246 3247 // Build a sequence of copy-to-reg nodes chained together with token chain 3248 // and flag operands which copy the outgoing args into the appropriate regs. 3249 SDValue InFlag; 3250 for (auto &RegToPass : RegsToPass) { 3251 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3252 RegToPass.second, InFlag); 3253 InFlag = Chain.getValue(1); 3254 } 3255 3256 3257 SDValue PhysReturnAddrReg; 3258 if (IsTailCall) { 3259 // Since the return is being combined with the call, we need to pass on the 3260 // return address. 3261 3262 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3263 SDValue ReturnAddrReg = CreateLiveInRegister( 3264 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3265 3266 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3267 MVT::i64); 3268 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3269 InFlag = Chain.getValue(1); 3270 } 3271 3272 // We don't usually want to end the call-sequence here because we would tidy 3273 // the frame up *after* the call, however in the ABI-changing tail-call case 3274 // we've carefully laid out the parameters so that when sp is reset they'll be 3275 // in the correct location. 3276 if (IsTailCall && !IsSibCall) { 3277 Chain = DAG.getCALLSEQ_END(Chain, 3278 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3279 DAG.getTargetConstant(0, DL, MVT::i32), 3280 InFlag, DL); 3281 InFlag = Chain.getValue(1); 3282 } 3283 3284 std::vector<SDValue> Ops; 3285 Ops.push_back(Chain); 3286 Ops.push_back(Callee); 3287 // Add a redundant copy of the callee global which will not be legalized, as 3288 // we need direct access to the callee later. 3289 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3290 const GlobalValue *GV = GSD->getGlobal(); 3291 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3292 } else { 3293 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3294 } 3295 3296 if (IsTailCall) { 3297 // Each tail call may have to adjust the stack by a different amount, so 3298 // this information must travel along with the operation for eventual 3299 // consumption by emitEpilogue. 3300 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3301 3302 Ops.push_back(PhysReturnAddrReg); 3303 } 3304 3305 // Add argument registers to the end of the list so that they are known live 3306 // into the call. 3307 for (auto &RegToPass : RegsToPass) { 3308 Ops.push_back(DAG.getRegister(RegToPass.first, 3309 RegToPass.second.getValueType())); 3310 } 3311 3312 // Add a register mask operand representing the call-preserved registers. 3313 3314 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3315 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3316 assert(Mask && "Missing call preserved mask for calling convention"); 3317 Ops.push_back(DAG.getRegisterMask(Mask)); 3318 3319 if (InFlag.getNode()) 3320 Ops.push_back(InFlag); 3321 3322 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3323 3324 // If we're doing a tall call, use a TC_RETURN here rather than an 3325 // actual call instruction. 3326 if (IsTailCall) { 3327 MFI.setHasTailCall(); 3328 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3329 } 3330 3331 // Returns a chain and a flag for retval copy to use. 3332 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3333 Chain = Call.getValue(0); 3334 InFlag = Call.getValue(1); 3335 3336 uint64_t CalleePopBytes = NumBytes; 3337 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3338 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3339 InFlag, DL); 3340 if (!Ins.empty()) 3341 InFlag = Chain.getValue(1); 3342 3343 // Handle result values, copying them out of physregs into vregs that we 3344 // return. 3345 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3346 InVals, IsThisReturn, 3347 IsThisReturn ? OutVals[0] : SDValue()); 3348 } 3349 3350 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3351 // except for applying the wave size scale to the increment amount. 3352 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3353 SDValue Op, SelectionDAG &DAG) const { 3354 const MachineFunction &MF = DAG.getMachineFunction(); 3355 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3356 3357 SDLoc dl(Op); 3358 EVT VT = Op.getValueType(); 3359 SDValue Tmp1 = Op; 3360 SDValue Tmp2 = Op.getValue(1); 3361 SDValue Tmp3 = Op.getOperand(2); 3362 SDValue Chain = Tmp1.getOperand(0); 3363 3364 Register SPReg = Info->getStackPtrOffsetReg(); 3365 3366 // Chain the dynamic stack allocation so that it doesn't modify the stack 3367 // pointer when other instructions are using the stack. 3368 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3369 3370 SDValue Size = Tmp2.getOperand(1); 3371 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3372 Chain = SP.getValue(1); 3373 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3374 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3375 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3376 unsigned Opc = 3377 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3378 ISD::ADD : ISD::SUB; 3379 3380 SDValue ScaledSize = DAG.getNode( 3381 ISD::SHL, dl, VT, Size, 3382 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3383 3384 Align StackAlign = TFL->getStackAlign(); 3385 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3386 if (Alignment && *Alignment > StackAlign) { 3387 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3388 DAG.getConstant(-(uint64_t)Alignment->value() 3389 << ST.getWavefrontSizeLog2(), 3390 dl, VT)); 3391 } 3392 3393 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3394 Tmp2 = DAG.getCALLSEQ_END( 3395 Chain, DAG.getIntPtrConstant(0, dl, true), 3396 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3397 3398 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3399 } 3400 3401 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3402 SelectionDAG &DAG) const { 3403 // We only handle constant sizes here to allow non-entry block, static sized 3404 // allocas. A truly dynamic value is more difficult to support because we 3405 // don't know if the size value is uniform or not. If the size isn't uniform, 3406 // we would need to do a wave reduction to get the maximum size to know how 3407 // much to increment the uniform stack pointer. 3408 SDValue Size = Op.getOperand(1); 3409 if (isa<ConstantSDNode>(Size)) 3410 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3411 3412 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3413 } 3414 3415 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3416 const MachineFunction &MF) const { 3417 Register Reg = StringSwitch<Register>(RegName) 3418 .Case("m0", AMDGPU::M0) 3419 .Case("exec", AMDGPU::EXEC) 3420 .Case("exec_lo", AMDGPU::EXEC_LO) 3421 .Case("exec_hi", AMDGPU::EXEC_HI) 3422 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3423 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3424 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3425 .Default(Register()); 3426 3427 if (Reg == AMDGPU::NoRegister) { 3428 report_fatal_error(Twine("invalid register name \"" 3429 + StringRef(RegName) + "\".")); 3430 3431 } 3432 3433 if (!Subtarget->hasFlatScrRegister() && 3434 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3435 report_fatal_error(Twine("invalid register \"" 3436 + StringRef(RegName) + "\" for subtarget.")); 3437 } 3438 3439 switch (Reg) { 3440 case AMDGPU::M0: 3441 case AMDGPU::EXEC_LO: 3442 case AMDGPU::EXEC_HI: 3443 case AMDGPU::FLAT_SCR_LO: 3444 case AMDGPU::FLAT_SCR_HI: 3445 if (VT.getSizeInBits() == 32) 3446 return Reg; 3447 break; 3448 case AMDGPU::EXEC: 3449 case AMDGPU::FLAT_SCR: 3450 if (VT.getSizeInBits() == 64) 3451 return Reg; 3452 break; 3453 default: 3454 llvm_unreachable("missing register type checking"); 3455 } 3456 3457 report_fatal_error(Twine("invalid type for register \"" 3458 + StringRef(RegName) + "\".")); 3459 } 3460 3461 // If kill is not the last instruction, split the block so kill is always a 3462 // proper terminator. 3463 MachineBasicBlock * 3464 SITargetLowering::splitKillBlock(MachineInstr &MI, 3465 MachineBasicBlock *BB) const { 3466 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3467 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3468 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3469 return SplitBB; 3470 } 3471 3472 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3473 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3474 // be the first instruction in the remainder block. 3475 // 3476 /// \returns { LoopBody, Remainder } 3477 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3478 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3479 MachineFunction *MF = MBB.getParent(); 3480 MachineBasicBlock::iterator I(&MI); 3481 3482 // To insert the loop we need to split the block. Move everything after this 3483 // point to a new block, and insert a new empty block between the two. 3484 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3485 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3486 MachineFunction::iterator MBBI(MBB); 3487 ++MBBI; 3488 3489 MF->insert(MBBI, LoopBB); 3490 MF->insert(MBBI, RemainderBB); 3491 3492 LoopBB->addSuccessor(LoopBB); 3493 LoopBB->addSuccessor(RemainderBB); 3494 3495 // Move the rest of the block into a new block. 3496 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3497 3498 if (InstInLoop) { 3499 auto Next = std::next(I); 3500 3501 // Move instruction to loop body. 3502 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3503 3504 // Move the rest of the block. 3505 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3506 } else { 3507 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3508 } 3509 3510 MBB.addSuccessor(LoopBB); 3511 3512 return std::make_pair(LoopBB, RemainderBB); 3513 } 3514 3515 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3516 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3517 MachineBasicBlock *MBB = MI.getParent(); 3518 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3519 auto I = MI.getIterator(); 3520 auto E = std::next(I); 3521 3522 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3523 .addImm(0); 3524 3525 MIBundleBuilder Bundler(*MBB, I, E); 3526 finalizeBundle(*MBB, Bundler.begin()); 3527 } 3528 3529 MachineBasicBlock * 3530 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3531 MachineBasicBlock *BB) const { 3532 const DebugLoc &DL = MI.getDebugLoc(); 3533 3534 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3535 3536 MachineBasicBlock *LoopBB; 3537 MachineBasicBlock *RemainderBB; 3538 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3539 3540 // Apparently kill flags are only valid if the def is in the same block? 3541 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3542 Src->setIsKill(false); 3543 3544 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3545 3546 MachineBasicBlock::iterator I = LoopBB->end(); 3547 3548 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3549 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3550 3551 // Clear TRAP_STS.MEM_VIOL 3552 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3553 .addImm(0) 3554 .addImm(EncodedReg); 3555 3556 bundleInstWithWaitcnt(MI); 3557 3558 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3559 3560 // Load and check TRAP_STS.MEM_VIOL 3561 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3562 .addImm(EncodedReg); 3563 3564 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3565 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3566 .addReg(Reg, RegState::Kill) 3567 .addImm(0); 3568 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3569 .addMBB(LoopBB); 3570 3571 return RemainderBB; 3572 } 3573 3574 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3575 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3576 // will only do one iteration. In the worst case, this will loop 64 times. 3577 // 3578 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3579 static MachineBasicBlock::iterator 3580 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3581 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3582 const DebugLoc &DL, const MachineOperand &Idx, 3583 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3584 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3585 Register &SGPRIdxReg) { 3586 3587 MachineFunction *MF = OrigBB.getParent(); 3588 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3589 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3590 MachineBasicBlock::iterator I = LoopBB.begin(); 3591 3592 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3593 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3594 Register NewExec = MRI.createVirtualRegister(BoolRC); 3595 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3596 Register CondReg = MRI.createVirtualRegister(BoolRC); 3597 3598 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3599 .addReg(InitReg) 3600 .addMBB(&OrigBB) 3601 .addReg(ResultReg) 3602 .addMBB(&LoopBB); 3603 3604 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3605 .addReg(InitSaveExecReg) 3606 .addMBB(&OrigBB) 3607 .addReg(NewExec) 3608 .addMBB(&LoopBB); 3609 3610 // Read the next variant <- also loop target. 3611 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3612 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3613 3614 // Compare the just read M0 value to all possible Idx values. 3615 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3616 .addReg(CurrentIdxReg) 3617 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3618 3619 // Update EXEC, save the original EXEC value to VCC. 3620 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3621 : AMDGPU::S_AND_SAVEEXEC_B64), 3622 NewExec) 3623 .addReg(CondReg, RegState::Kill); 3624 3625 MRI.setSimpleHint(NewExec, CondReg); 3626 3627 if (UseGPRIdxMode) { 3628 if (Offset == 0) { 3629 SGPRIdxReg = CurrentIdxReg; 3630 } else { 3631 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3632 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3633 .addReg(CurrentIdxReg, RegState::Kill) 3634 .addImm(Offset); 3635 } 3636 } else { 3637 // Move index from VCC into M0 3638 if (Offset == 0) { 3639 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3640 .addReg(CurrentIdxReg, RegState::Kill); 3641 } else { 3642 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3643 .addReg(CurrentIdxReg, RegState::Kill) 3644 .addImm(Offset); 3645 } 3646 } 3647 3648 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3649 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3650 MachineInstr *InsertPt = 3651 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3652 : AMDGPU::S_XOR_B64_term), Exec) 3653 .addReg(Exec) 3654 .addReg(NewExec); 3655 3656 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3657 // s_cbranch_scc0? 3658 3659 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3660 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3661 .addMBB(&LoopBB); 3662 3663 return InsertPt->getIterator(); 3664 } 3665 3666 // This has slightly sub-optimal regalloc when the source vector is killed by 3667 // the read. The register allocator does not understand that the kill is 3668 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3669 // subregister from it, using 1 more VGPR than necessary. This was saved when 3670 // this was expanded after register allocation. 3671 static MachineBasicBlock::iterator 3672 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3673 unsigned InitResultReg, unsigned PhiReg, int Offset, 3674 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3675 MachineFunction *MF = MBB.getParent(); 3676 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3677 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3678 MachineRegisterInfo &MRI = MF->getRegInfo(); 3679 const DebugLoc &DL = MI.getDebugLoc(); 3680 MachineBasicBlock::iterator I(&MI); 3681 3682 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3683 Register DstReg = MI.getOperand(0).getReg(); 3684 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3685 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3686 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3687 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3688 3689 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3690 3691 // Save the EXEC mask 3692 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3693 .addReg(Exec); 3694 3695 MachineBasicBlock *LoopBB; 3696 MachineBasicBlock *RemainderBB; 3697 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3698 3699 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3700 3701 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3702 InitResultReg, DstReg, PhiReg, TmpExec, 3703 Offset, UseGPRIdxMode, SGPRIdxReg); 3704 3705 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3706 MachineFunction::iterator MBBI(LoopBB); 3707 ++MBBI; 3708 MF->insert(MBBI, LandingPad); 3709 LoopBB->removeSuccessor(RemainderBB); 3710 LandingPad->addSuccessor(RemainderBB); 3711 LoopBB->addSuccessor(LandingPad); 3712 MachineBasicBlock::iterator First = LandingPad->begin(); 3713 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3714 .addReg(SaveExec); 3715 3716 return InsPt; 3717 } 3718 3719 // Returns subreg index, offset 3720 static std::pair<unsigned, int> 3721 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3722 const TargetRegisterClass *SuperRC, 3723 unsigned VecReg, 3724 int Offset) { 3725 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3726 3727 // Skip out of bounds offsets, or else we would end up using an undefined 3728 // register. 3729 if (Offset >= NumElts || Offset < 0) 3730 return std::make_pair(AMDGPU::sub0, Offset); 3731 3732 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3733 } 3734 3735 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3736 MachineRegisterInfo &MRI, MachineInstr &MI, 3737 int Offset) { 3738 MachineBasicBlock *MBB = MI.getParent(); 3739 const DebugLoc &DL = MI.getDebugLoc(); 3740 MachineBasicBlock::iterator I(&MI); 3741 3742 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3743 3744 assert(Idx->getReg() != AMDGPU::NoRegister); 3745 3746 if (Offset == 0) { 3747 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3748 } else { 3749 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3750 .add(*Idx) 3751 .addImm(Offset); 3752 } 3753 } 3754 3755 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3756 MachineRegisterInfo &MRI, MachineInstr &MI, 3757 int Offset) { 3758 MachineBasicBlock *MBB = MI.getParent(); 3759 const DebugLoc &DL = MI.getDebugLoc(); 3760 MachineBasicBlock::iterator I(&MI); 3761 3762 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3763 3764 if (Offset == 0) 3765 return Idx->getReg(); 3766 3767 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3768 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3769 .add(*Idx) 3770 .addImm(Offset); 3771 return Tmp; 3772 } 3773 3774 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3775 MachineBasicBlock &MBB, 3776 const GCNSubtarget &ST) { 3777 const SIInstrInfo *TII = ST.getInstrInfo(); 3778 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3779 MachineFunction *MF = MBB.getParent(); 3780 MachineRegisterInfo &MRI = MF->getRegInfo(); 3781 3782 Register Dst = MI.getOperand(0).getReg(); 3783 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3784 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3785 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3786 3787 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3788 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3789 3790 unsigned SubReg; 3791 std::tie(SubReg, Offset) 3792 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3793 3794 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3795 3796 // Check for a SGPR index. 3797 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3798 MachineBasicBlock::iterator I(&MI); 3799 const DebugLoc &DL = MI.getDebugLoc(); 3800 3801 if (UseGPRIdxMode) { 3802 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3803 // to avoid interfering with other uses, so probably requires a new 3804 // optimization pass. 3805 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3806 3807 const MCInstrDesc &GPRIDXDesc = 3808 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3809 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3810 .addReg(SrcReg) 3811 .addReg(Idx) 3812 .addImm(SubReg); 3813 } else { 3814 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3815 3816 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3817 .addReg(SrcReg, 0, SubReg) 3818 .addReg(SrcReg, RegState::Implicit); 3819 } 3820 3821 MI.eraseFromParent(); 3822 3823 return &MBB; 3824 } 3825 3826 // Control flow needs to be inserted if indexing with a VGPR. 3827 const DebugLoc &DL = MI.getDebugLoc(); 3828 MachineBasicBlock::iterator I(&MI); 3829 3830 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3831 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3832 3833 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3834 3835 Register SGPRIdxReg; 3836 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3837 UseGPRIdxMode, SGPRIdxReg); 3838 3839 MachineBasicBlock *LoopBB = InsPt->getParent(); 3840 3841 if (UseGPRIdxMode) { 3842 const MCInstrDesc &GPRIDXDesc = 3843 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3844 3845 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3846 .addReg(SrcReg) 3847 .addReg(SGPRIdxReg) 3848 .addImm(SubReg); 3849 } else { 3850 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3851 .addReg(SrcReg, 0, SubReg) 3852 .addReg(SrcReg, RegState::Implicit); 3853 } 3854 3855 MI.eraseFromParent(); 3856 3857 return LoopBB; 3858 } 3859 3860 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3861 MachineBasicBlock &MBB, 3862 const GCNSubtarget &ST) { 3863 const SIInstrInfo *TII = ST.getInstrInfo(); 3864 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3865 MachineFunction *MF = MBB.getParent(); 3866 MachineRegisterInfo &MRI = MF->getRegInfo(); 3867 3868 Register Dst = MI.getOperand(0).getReg(); 3869 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3870 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3871 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3872 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3873 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3874 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3875 3876 // This can be an immediate, but will be folded later. 3877 assert(Val->getReg()); 3878 3879 unsigned SubReg; 3880 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3881 SrcVec->getReg(), 3882 Offset); 3883 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3884 3885 if (Idx->getReg() == AMDGPU::NoRegister) { 3886 MachineBasicBlock::iterator I(&MI); 3887 const DebugLoc &DL = MI.getDebugLoc(); 3888 3889 assert(Offset == 0); 3890 3891 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3892 .add(*SrcVec) 3893 .add(*Val) 3894 .addImm(SubReg); 3895 3896 MI.eraseFromParent(); 3897 return &MBB; 3898 } 3899 3900 // Check for a SGPR index. 3901 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3902 MachineBasicBlock::iterator I(&MI); 3903 const DebugLoc &DL = MI.getDebugLoc(); 3904 3905 if (UseGPRIdxMode) { 3906 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3907 3908 const MCInstrDesc &GPRIDXDesc = 3909 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3910 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3911 .addReg(SrcVec->getReg()) 3912 .add(*Val) 3913 .addReg(Idx) 3914 .addImm(SubReg); 3915 } else { 3916 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3917 3918 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3919 TRI.getRegSizeInBits(*VecRC), 32, false); 3920 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3921 .addReg(SrcVec->getReg()) 3922 .add(*Val) 3923 .addImm(SubReg); 3924 } 3925 MI.eraseFromParent(); 3926 return &MBB; 3927 } 3928 3929 // Control flow needs to be inserted if indexing with a VGPR. 3930 if (Val->isReg()) 3931 MRI.clearKillFlags(Val->getReg()); 3932 3933 const DebugLoc &DL = MI.getDebugLoc(); 3934 3935 Register PhiReg = MRI.createVirtualRegister(VecRC); 3936 3937 Register SGPRIdxReg; 3938 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3939 UseGPRIdxMode, SGPRIdxReg); 3940 MachineBasicBlock *LoopBB = InsPt->getParent(); 3941 3942 if (UseGPRIdxMode) { 3943 const MCInstrDesc &GPRIDXDesc = 3944 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3945 3946 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3947 .addReg(PhiReg) 3948 .add(*Val) 3949 .addReg(SGPRIdxReg) 3950 .addImm(AMDGPU::sub0); 3951 } else { 3952 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3953 TRI.getRegSizeInBits(*VecRC), 32, false); 3954 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3955 .addReg(PhiReg) 3956 .add(*Val) 3957 .addImm(AMDGPU::sub0); 3958 } 3959 3960 MI.eraseFromParent(); 3961 return LoopBB; 3962 } 3963 3964 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3965 MachineInstr &MI, MachineBasicBlock *BB) const { 3966 3967 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3968 MachineFunction *MF = BB->getParent(); 3969 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3970 3971 switch (MI.getOpcode()) { 3972 case AMDGPU::S_UADDO_PSEUDO: 3973 case AMDGPU::S_USUBO_PSEUDO: { 3974 const DebugLoc &DL = MI.getDebugLoc(); 3975 MachineOperand &Dest0 = MI.getOperand(0); 3976 MachineOperand &Dest1 = MI.getOperand(1); 3977 MachineOperand &Src0 = MI.getOperand(2); 3978 MachineOperand &Src1 = MI.getOperand(3); 3979 3980 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3981 ? AMDGPU::S_ADD_I32 3982 : AMDGPU::S_SUB_I32; 3983 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3984 3985 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3986 .addImm(1) 3987 .addImm(0); 3988 3989 MI.eraseFromParent(); 3990 return BB; 3991 } 3992 case AMDGPU::S_ADD_U64_PSEUDO: 3993 case AMDGPU::S_SUB_U64_PSEUDO: { 3994 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3995 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3996 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3997 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3998 const DebugLoc &DL = MI.getDebugLoc(); 3999 4000 MachineOperand &Dest = MI.getOperand(0); 4001 MachineOperand &Src0 = MI.getOperand(1); 4002 MachineOperand &Src1 = MI.getOperand(2); 4003 4004 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4005 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4006 4007 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4008 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4009 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4010 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4011 4012 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4013 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4014 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4015 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4016 4017 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4018 4019 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4020 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4021 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4022 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4023 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4024 .addReg(DestSub0) 4025 .addImm(AMDGPU::sub0) 4026 .addReg(DestSub1) 4027 .addImm(AMDGPU::sub1); 4028 MI.eraseFromParent(); 4029 return BB; 4030 } 4031 case AMDGPU::V_ADD_U64_PSEUDO: 4032 case AMDGPU::V_SUB_U64_PSEUDO: { 4033 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4034 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4035 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4036 const DebugLoc &DL = MI.getDebugLoc(); 4037 4038 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4039 4040 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4041 4042 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4043 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4044 4045 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4046 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4047 4048 MachineOperand &Dest = MI.getOperand(0); 4049 MachineOperand &Src0 = MI.getOperand(1); 4050 MachineOperand &Src1 = MI.getOperand(2); 4051 4052 const TargetRegisterClass *Src0RC = Src0.isReg() 4053 ? MRI.getRegClass(Src0.getReg()) 4054 : &AMDGPU::VReg_64RegClass; 4055 const TargetRegisterClass *Src1RC = Src1.isReg() 4056 ? MRI.getRegClass(Src1.getReg()) 4057 : &AMDGPU::VReg_64RegClass; 4058 4059 const TargetRegisterClass *Src0SubRC = 4060 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4061 const TargetRegisterClass *Src1SubRC = 4062 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4063 4064 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4065 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4066 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4067 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4068 4069 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4070 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4071 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4072 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4073 4074 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4075 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4076 .addReg(CarryReg, RegState::Define) 4077 .add(SrcReg0Sub0) 4078 .add(SrcReg1Sub0) 4079 .addImm(0); // clamp bit 4080 4081 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4082 MachineInstr *HiHalf = 4083 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4084 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4085 .add(SrcReg0Sub1) 4086 .add(SrcReg1Sub1) 4087 .addReg(CarryReg, RegState::Kill) 4088 .addImm(0); // clamp bit 4089 4090 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4091 .addReg(DestSub0) 4092 .addImm(AMDGPU::sub0) 4093 .addReg(DestSub1) 4094 .addImm(AMDGPU::sub1); 4095 TII->legalizeOperands(*LoHalf); 4096 TII->legalizeOperands(*HiHalf); 4097 MI.eraseFromParent(); 4098 return BB; 4099 } 4100 case AMDGPU::S_ADD_CO_PSEUDO: 4101 case AMDGPU::S_SUB_CO_PSEUDO: { 4102 // This pseudo has a chance to be selected 4103 // only from uniform add/subcarry node. All the VGPR operands 4104 // therefore assumed to be splat vectors. 4105 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4106 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4107 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4108 MachineBasicBlock::iterator MII = MI; 4109 const DebugLoc &DL = MI.getDebugLoc(); 4110 MachineOperand &Dest = MI.getOperand(0); 4111 MachineOperand &CarryDest = MI.getOperand(1); 4112 MachineOperand &Src0 = MI.getOperand(2); 4113 MachineOperand &Src1 = MI.getOperand(3); 4114 MachineOperand &Src2 = MI.getOperand(4); 4115 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4116 ? AMDGPU::S_ADDC_U32 4117 : AMDGPU::S_SUBB_U32; 4118 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4119 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4120 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4121 .addReg(Src0.getReg()); 4122 Src0.setReg(RegOp0); 4123 } 4124 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4125 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4126 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4127 .addReg(Src1.getReg()); 4128 Src1.setReg(RegOp1); 4129 } 4130 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4131 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4132 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4133 .addReg(Src2.getReg()); 4134 Src2.setReg(RegOp2); 4135 } 4136 4137 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4138 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4139 if (ST.hasScalarCompareEq64()) { 4140 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4141 .addReg(Src2.getReg()) 4142 .addImm(0); 4143 } else { 4144 const TargetRegisterClass *SubRC = 4145 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4146 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4147 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4148 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4149 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4150 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4151 4152 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4153 .add(Src2Sub0) 4154 .add(Src2Sub1); 4155 4156 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4157 .addReg(Src2_32, RegState::Kill) 4158 .addImm(0); 4159 } 4160 } else { 4161 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4162 .addReg(Src2.getReg()) 4163 .addImm(0); 4164 } 4165 4166 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4167 4168 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4169 .addReg(AMDGPU::SCC); 4170 MI.eraseFromParent(); 4171 return BB; 4172 } 4173 case AMDGPU::SI_INIT_M0: { 4174 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4175 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4176 .add(MI.getOperand(0)); 4177 MI.eraseFromParent(); 4178 return BB; 4179 } 4180 case AMDGPU::GET_GROUPSTATICSIZE: { 4181 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4182 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4183 DebugLoc DL = MI.getDebugLoc(); 4184 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4185 .add(MI.getOperand(0)) 4186 .addImm(MFI->getLDSSize()); 4187 MI.eraseFromParent(); 4188 return BB; 4189 } 4190 case AMDGPU::SI_INDIRECT_SRC_V1: 4191 case AMDGPU::SI_INDIRECT_SRC_V2: 4192 case AMDGPU::SI_INDIRECT_SRC_V4: 4193 case AMDGPU::SI_INDIRECT_SRC_V8: 4194 case AMDGPU::SI_INDIRECT_SRC_V16: 4195 case AMDGPU::SI_INDIRECT_SRC_V32: 4196 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4197 case AMDGPU::SI_INDIRECT_DST_V1: 4198 case AMDGPU::SI_INDIRECT_DST_V2: 4199 case AMDGPU::SI_INDIRECT_DST_V4: 4200 case AMDGPU::SI_INDIRECT_DST_V8: 4201 case AMDGPU::SI_INDIRECT_DST_V16: 4202 case AMDGPU::SI_INDIRECT_DST_V32: 4203 return emitIndirectDst(MI, *BB, *getSubtarget()); 4204 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4205 case AMDGPU::SI_KILL_I1_PSEUDO: 4206 return splitKillBlock(MI, BB); 4207 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4208 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4209 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4210 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4211 4212 Register Dst = MI.getOperand(0).getReg(); 4213 Register Src0 = MI.getOperand(1).getReg(); 4214 Register Src1 = MI.getOperand(2).getReg(); 4215 const DebugLoc &DL = MI.getDebugLoc(); 4216 Register SrcCond = MI.getOperand(3).getReg(); 4217 4218 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4219 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4220 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4221 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4222 4223 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4224 .addReg(SrcCond); 4225 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4226 .addImm(0) 4227 .addReg(Src0, 0, AMDGPU::sub0) 4228 .addImm(0) 4229 .addReg(Src1, 0, AMDGPU::sub0) 4230 .addReg(SrcCondCopy); 4231 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4232 .addImm(0) 4233 .addReg(Src0, 0, AMDGPU::sub1) 4234 .addImm(0) 4235 .addReg(Src1, 0, AMDGPU::sub1) 4236 .addReg(SrcCondCopy); 4237 4238 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4239 .addReg(DstLo) 4240 .addImm(AMDGPU::sub0) 4241 .addReg(DstHi) 4242 .addImm(AMDGPU::sub1); 4243 MI.eraseFromParent(); 4244 return BB; 4245 } 4246 case AMDGPU::SI_BR_UNDEF: { 4247 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4248 const DebugLoc &DL = MI.getDebugLoc(); 4249 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4250 .add(MI.getOperand(0)); 4251 Br->getOperand(1).setIsUndef(true); // read undef SCC 4252 MI.eraseFromParent(); 4253 return BB; 4254 } 4255 case AMDGPU::ADJCALLSTACKUP: 4256 case AMDGPU::ADJCALLSTACKDOWN: { 4257 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4258 MachineInstrBuilder MIB(*MF, &MI); 4259 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4260 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4261 return BB; 4262 } 4263 case AMDGPU::SI_CALL_ISEL: { 4264 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4265 const DebugLoc &DL = MI.getDebugLoc(); 4266 4267 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4268 4269 MachineInstrBuilder MIB; 4270 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4271 4272 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4273 MIB.add(MI.getOperand(I)); 4274 4275 MIB.cloneMemRefs(MI); 4276 MI.eraseFromParent(); 4277 return BB; 4278 } 4279 case AMDGPU::V_ADD_CO_U32_e32: 4280 case AMDGPU::V_SUB_CO_U32_e32: 4281 case AMDGPU::V_SUBREV_CO_U32_e32: { 4282 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4283 const DebugLoc &DL = MI.getDebugLoc(); 4284 unsigned Opc = MI.getOpcode(); 4285 4286 bool NeedClampOperand = false; 4287 if (TII->pseudoToMCOpcode(Opc) == -1) { 4288 Opc = AMDGPU::getVOPe64(Opc); 4289 NeedClampOperand = true; 4290 } 4291 4292 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4293 if (TII->isVOP3(*I)) { 4294 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4295 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4296 I.addReg(TRI->getVCC(), RegState::Define); 4297 } 4298 I.add(MI.getOperand(1)) 4299 .add(MI.getOperand(2)); 4300 if (NeedClampOperand) 4301 I.addImm(0); // clamp bit for e64 encoding 4302 4303 TII->legalizeOperands(*I); 4304 4305 MI.eraseFromParent(); 4306 return BB; 4307 } 4308 case AMDGPU::V_ADDC_U32_e32: 4309 case AMDGPU::V_SUBB_U32_e32: 4310 case AMDGPU::V_SUBBREV_U32_e32: 4311 // These instructions have an implicit use of vcc which counts towards the 4312 // constant bus limit. 4313 TII->legalizeOperands(MI); 4314 return BB; 4315 case AMDGPU::DS_GWS_INIT: 4316 case AMDGPU::DS_GWS_SEMA_BR: 4317 case AMDGPU::DS_GWS_BARRIER: 4318 if (Subtarget->needsAlignedVGPRs()) { 4319 // Add implicit aligned super-reg to force alignment on the data operand. 4320 const DebugLoc &DL = MI.getDebugLoc(); 4321 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4322 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4323 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4324 Register DataReg = Op->getReg(); 4325 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4326 Register Undef = MRI.createVirtualRegister( 4327 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4328 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4329 Register NewVR = 4330 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4331 : &AMDGPU::VReg_64_Align2RegClass); 4332 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4333 .addReg(DataReg, 0, Op->getSubReg()) 4334 .addImm(AMDGPU::sub0) 4335 .addReg(Undef) 4336 .addImm(AMDGPU::sub1); 4337 Op->setReg(NewVR); 4338 Op->setSubReg(AMDGPU::sub0); 4339 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4340 } 4341 LLVM_FALLTHROUGH; 4342 case AMDGPU::DS_GWS_SEMA_V: 4343 case AMDGPU::DS_GWS_SEMA_P: 4344 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4345 // A s_waitcnt 0 is required to be the instruction immediately following. 4346 if (getSubtarget()->hasGWSAutoReplay()) { 4347 bundleInstWithWaitcnt(MI); 4348 return BB; 4349 } 4350 4351 return emitGWSMemViolTestLoop(MI, BB); 4352 case AMDGPU::S_SETREG_B32: { 4353 // Try to optimize cases that only set the denormal mode or rounding mode. 4354 // 4355 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4356 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4357 // instead. 4358 // 4359 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4360 // allow you to have a no side effect instruction in the output of a 4361 // sideeffecting pattern. 4362 unsigned ID, Offset, Width; 4363 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4364 if (ID != AMDGPU::Hwreg::ID_MODE) 4365 return BB; 4366 4367 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4368 const unsigned SetMask = WidthMask << Offset; 4369 4370 if (getSubtarget()->hasDenormModeInst()) { 4371 unsigned SetDenormOp = 0; 4372 unsigned SetRoundOp = 0; 4373 4374 // The dedicated instructions can only set the whole denorm or round mode 4375 // at once, not a subset of bits in either. 4376 if (SetMask == 4377 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4378 // If this fully sets both the round and denorm mode, emit the two 4379 // dedicated instructions for these. 4380 SetRoundOp = AMDGPU::S_ROUND_MODE; 4381 SetDenormOp = AMDGPU::S_DENORM_MODE; 4382 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4383 SetRoundOp = AMDGPU::S_ROUND_MODE; 4384 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4385 SetDenormOp = AMDGPU::S_DENORM_MODE; 4386 } 4387 4388 if (SetRoundOp || SetDenormOp) { 4389 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4390 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4391 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4392 unsigned ImmVal = Def->getOperand(1).getImm(); 4393 if (SetRoundOp) { 4394 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4395 .addImm(ImmVal & 0xf); 4396 4397 // If we also have the denorm mode, get just the denorm mode bits. 4398 ImmVal >>= 4; 4399 } 4400 4401 if (SetDenormOp) { 4402 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4403 .addImm(ImmVal & 0xf); 4404 } 4405 4406 MI.eraseFromParent(); 4407 return BB; 4408 } 4409 } 4410 } 4411 4412 // If only FP bits are touched, used the no side effects pseudo. 4413 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4414 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4415 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4416 4417 return BB; 4418 } 4419 default: 4420 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4421 } 4422 } 4423 4424 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4425 return isTypeLegal(VT.getScalarType()); 4426 } 4427 4428 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4429 // This currently forces unfolding various combinations of fsub into fma with 4430 // free fneg'd operands. As long as we have fast FMA (controlled by 4431 // isFMAFasterThanFMulAndFAdd), we should perform these. 4432 4433 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4434 // most of these combines appear to be cycle neutral but save on instruction 4435 // count / code size. 4436 return true; 4437 } 4438 4439 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4440 EVT VT) const { 4441 if (!VT.isVector()) { 4442 return MVT::i1; 4443 } 4444 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4445 } 4446 4447 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4448 // TODO: Should i16 be used always if legal? For now it would force VALU 4449 // shifts. 4450 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4451 } 4452 4453 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4454 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4455 ? Ty.changeElementSize(16) 4456 : Ty.changeElementSize(32); 4457 } 4458 4459 // Answering this is somewhat tricky and depends on the specific device which 4460 // have different rates for fma or all f64 operations. 4461 // 4462 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4463 // regardless of which device (although the number of cycles differs between 4464 // devices), so it is always profitable for f64. 4465 // 4466 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4467 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4468 // which we can always do even without fused FP ops since it returns the same 4469 // result as the separate operations and since it is always full 4470 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4471 // however does not support denormals, so we do report fma as faster if we have 4472 // a fast fma device and require denormals. 4473 // 4474 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4475 EVT VT) const { 4476 VT = VT.getScalarType(); 4477 4478 switch (VT.getSimpleVT().SimpleTy) { 4479 case MVT::f32: { 4480 // If mad is not available this depends only on if f32 fma is full rate. 4481 if (!Subtarget->hasMadMacF32Insts()) 4482 return Subtarget->hasFastFMAF32(); 4483 4484 // Otherwise f32 mad is always full rate and returns the same result as 4485 // the separate operations so should be preferred over fma. 4486 // However does not support denomals. 4487 if (hasFP32Denormals(MF)) 4488 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4489 4490 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4491 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4492 } 4493 case MVT::f64: 4494 return true; 4495 case MVT::f16: 4496 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4497 default: 4498 break; 4499 } 4500 4501 return false; 4502 } 4503 4504 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4505 const SDNode *N) const { 4506 // TODO: Check future ftz flag 4507 // v_mad_f32/v_mac_f32 do not support denormals. 4508 EVT VT = N->getValueType(0); 4509 if (VT == MVT::f32) 4510 return Subtarget->hasMadMacF32Insts() && 4511 !hasFP32Denormals(DAG.getMachineFunction()); 4512 if (VT == MVT::f16) { 4513 return Subtarget->hasMadF16() && 4514 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4515 } 4516 4517 return false; 4518 } 4519 4520 //===----------------------------------------------------------------------===// 4521 // Custom DAG Lowering Operations 4522 //===----------------------------------------------------------------------===// 4523 4524 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4525 // wider vector type is legal. 4526 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4527 SelectionDAG &DAG) const { 4528 unsigned Opc = Op.getOpcode(); 4529 EVT VT = Op.getValueType(); 4530 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4531 4532 SDValue Lo, Hi; 4533 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4534 4535 SDLoc SL(Op); 4536 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4537 Op->getFlags()); 4538 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4539 Op->getFlags()); 4540 4541 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4542 } 4543 4544 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4545 // wider vector type is legal. 4546 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4547 SelectionDAG &DAG) const { 4548 unsigned Opc = Op.getOpcode(); 4549 EVT VT = Op.getValueType(); 4550 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4551 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4552 4553 SDValue Lo0, Hi0; 4554 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4555 SDValue Lo1, Hi1; 4556 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4557 4558 SDLoc SL(Op); 4559 4560 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4561 Op->getFlags()); 4562 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4563 Op->getFlags()); 4564 4565 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4566 } 4567 4568 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4569 SelectionDAG &DAG) const { 4570 unsigned Opc = Op.getOpcode(); 4571 EVT VT = Op.getValueType(); 4572 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4573 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4574 4575 SDValue Lo0, Hi0; 4576 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4577 SDValue Lo1, Hi1; 4578 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4579 SDValue Lo2, Hi2; 4580 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4581 4582 SDLoc SL(Op); 4583 4584 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4585 Op->getFlags()); 4586 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4587 Op->getFlags()); 4588 4589 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4590 } 4591 4592 4593 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4594 switch (Op.getOpcode()) { 4595 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4596 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4597 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4598 case ISD::LOAD: { 4599 SDValue Result = LowerLOAD(Op, DAG); 4600 assert((!Result.getNode() || 4601 Result.getNode()->getNumValues() == 2) && 4602 "Load should return a value and a chain"); 4603 return Result; 4604 } 4605 4606 case ISD::FSIN: 4607 case ISD::FCOS: 4608 return LowerTrig(Op, DAG); 4609 case ISD::SELECT: return LowerSELECT(Op, DAG); 4610 case ISD::FDIV: return LowerFDIV(Op, DAG); 4611 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4612 case ISD::STORE: return LowerSTORE(Op, DAG); 4613 case ISD::GlobalAddress: { 4614 MachineFunction &MF = DAG.getMachineFunction(); 4615 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4616 return LowerGlobalAddress(MFI, Op, DAG); 4617 } 4618 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4619 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4620 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4621 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4622 case ISD::INSERT_SUBVECTOR: 4623 return lowerINSERT_SUBVECTOR(Op, DAG); 4624 case ISD::INSERT_VECTOR_ELT: 4625 return lowerINSERT_VECTOR_ELT(Op, DAG); 4626 case ISD::EXTRACT_VECTOR_ELT: 4627 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4628 case ISD::VECTOR_SHUFFLE: 4629 return lowerVECTOR_SHUFFLE(Op, DAG); 4630 case ISD::BUILD_VECTOR: 4631 return lowerBUILD_VECTOR(Op, DAG); 4632 case ISD::FP_ROUND: 4633 return lowerFP_ROUND(Op, DAG); 4634 case ISD::TRAP: 4635 return lowerTRAP(Op, DAG); 4636 case ISD::DEBUGTRAP: 4637 return lowerDEBUGTRAP(Op, DAG); 4638 case ISD::FABS: 4639 case ISD::FNEG: 4640 case ISD::FCANONICALIZE: 4641 case ISD::BSWAP: 4642 return splitUnaryVectorOp(Op, DAG); 4643 case ISD::FMINNUM: 4644 case ISD::FMAXNUM: 4645 return lowerFMINNUM_FMAXNUM(Op, DAG); 4646 case ISD::FMA: 4647 return splitTernaryVectorOp(Op, DAG); 4648 case ISD::FP_TO_SINT: 4649 case ISD::FP_TO_UINT: 4650 return LowerFP_TO_INT(Op, DAG); 4651 case ISD::SHL: 4652 case ISD::SRA: 4653 case ISD::SRL: 4654 case ISD::ADD: 4655 case ISD::SUB: 4656 case ISD::MUL: 4657 case ISD::SMIN: 4658 case ISD::SMAX: 4659 case ISD::UMIN: 4660 case ISD::UMAX: 4661 case ISD::FADD: 4662 case ISD::FMUL: 4663 case ISD::FMINNUM_IEEE: 4664 case ISD::FMAXNUM_IEEE: 4665 case ISD::UADDSAT: 4666 case ISD::USUBSAT: 4667 case ISD::SADDSAT: 4668 case ISD::SSUBSAT: 4669 return splitBinaryVectorOp(Op, DAG); 4670 case ISD::SMULO: 4671 case ISD::UMULO: 4672 return lowerXMULO(Op, DAG); 4673 case ISD::DYNAMIC_STACKALLOC: 4674 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4675 } 4676 return SDValue(); 4677 } 4678 4679 // Used for D16: Casts the result of an instruction into the right vector, 4680 // packs values if loads return unpacked values. 4681 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4682 const SDLoc &DL, 4683 SelectionDAG &DAG, bool Unpacked) { 4684 if (!LoadVT.isVector()) 4685 return Result; 4686 4687 // Cast back to the original packed type or to a larger type that is a 4688 // multiple of 32 bit for D16. Widening the return type is a required for 4689 // legalization. 4690 EVT FittingLoadVT = LoadVT; 4691 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4692 FittingLoadVT = 4693 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4694 LoadVT.getVectorNumElements() + 1); 4695 } 4696 4697 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4698 // Truncate to v2i16/v4i16. 4699 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4700 4701 // Workaround legalizer not scalarizing truncate after vector op 4702 // legalization but not creating intermediate vector trunc. 4703 SmallVector<SDValue, 4> Elts; 4704 DAG.ExtractVectorElements(Result, Elts); 4705 for (SDValue &Elt : Elts) 4706 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4707 4708 // Pad illegal v1i16/v3fi6 to v4i16 4709 if ((LoadVT.getVectorNumElements() % 2) == 1) 4710 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4711 4712 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4713 4714 // Bitcast to original type (v2f16/v4f16). 4715 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4716 } 4717 4718 // Cast back to the original packed type. 4719 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4720 } 4721 4722 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4723 MemSDNode *M, 4724 SelectionDAG &DAG, 4725 ArrayRef<SDValue> Ops, 4726 bool IsIntrinsic) const { 4727 SDLoc DL(M); 4728 4729 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4730 EVT LoadVT = M->getValueType(0); 4731 4732 EVT EquivLoadVT = LoadVT; 4733 if (LoadVT.isVector()) { 4734 if (Unpacked) { 4735 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4736 LoadVT.getVectorNumElements()); 4737 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4738 // Widen v3f16 to legal type 4739 EquivLoadVT = 4740 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4741 LoadVT.getVectorNumElements() + 1); 4742 } 4743 } 4744 4745 // Change from v4f16/v2f16 to EquivLoadVT. 4746 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4747 4748 SDValue Load 4749 = DAG.getMemIntrinsicNode( 4750 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4751 VTList, Ops, M->getMemoryVT(), 4752 M->getMemOperand()); 4753 4754 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4755 4756 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4757 } 4758 4759 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4760 SelectionDAG &DAG, 4761 ArrayRef<SDValue> Ops) const { 4762 SDLoc DL(M); 4763 EVT LoadVT = M->getValueType(0); 4764 EVT EltType = LoadVT.getScalarType(); 4765 EVT IntVT = LoadVT.changeTypeToInteger(); 4766 4767 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4768 4769 unsigned Opc = 4770 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4771 4772 if (IsD16) { 4773 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4774 } 4775 4776 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4777 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4778 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4779 4780 if (isTypeLegal(LoadVT)) { 4781 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4782 M->getMemOperand(), DAG); 4783 } 4784 4785 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4786 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4787 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4788 M->getMemOperand(), DAG); 4789 return DAG.getMergeValues( 4790 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4791 DL); 4792 } 4793 4794 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4795 SDNode *N, SelectionDAG &DAG) { 4796 EVT VT = N->getValueType(0); 4797 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4798 unsigned CondCode = CD->getZExtValue(); 4799 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4800 return DAG.getUNDEF(VT); 4801 4802 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4803 4804 SDValue LHS = N->getOperand(1); 4805 SDValue RHS = N->getOperand(2); 4806 4807 SDLoc DL(N); 4808 4809 EVT CmpVT = LHS.getValueType(); 4810 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4811 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4812 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4813 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4814 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4815 } 4816 4817 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4818 4819 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4820 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4821 4822 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4823 DAG.getCondCode(CCOpcode)); 4824 if (VT.bitsEq(CCVT)) 4825 return SetCC; 4826 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4827 } 4828 4829 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4830 SDNode *N, SelectionDAG &DAG) { 4831 EVT VT = N->getValueType(0); 4832 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4833 4834 unsigned CondCode = CD->getZExtValue(); 4835 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4836 return DAG.getUNDEF(VT); 4837 4838 SDValue Src0 = N->getOperand(1); 4839 SDValue Src1 = N->getOperand(2); 4840 EVT CmpVT = Src0.getValueType(); 4841 SDLoc SL(N); 4842 4843 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4844 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4845 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4846 } 4847 4848 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4849 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4850 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4851 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4852 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4853 Src1, DAG.getCondCode(CCOpcode)); 4854 if (VT.bitsEq(CCVT)) 4855 return SetCC; 4856 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4857 } 4858 4859 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4860 SelectionDAG &DAG) { 4861 EVT VT = N->getValueType(0); 4862 SDValue Src = N->getOperand(1); 4863 SDLoc SL(N); 4864 4865 if (Src.getOpcode() == ISD::SETCC) { 4866 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4867 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4868 Src.getOperand(1), Src.getOperand(2)); 4869 } 4870 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4871 // (ballot 0) -> 0 4872 if (Arg->isZero()) 4873 return DAG.getConstant(0, SL, VT); 4874 4875 // (ballot 1) -> EXEC/EXEC_LO 4876 if (Arg->isOne()) { 4877 Register Exec; 4878 if (VT.getScalarSizeInBits() == 32) 4879 Exec = AMDGPU::EXEC_LO; 4880 else if (VT.getScalarSizeInBits() == 64) 4881 Exec = AMDGPU::EXEC; 4882 else 4883 return SDValue(); 4884 4885 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4886 } 4887 } 4888 4889 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4890 // ISD::SETNE) 4891 return DAG.getNode( 4892 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4893 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4894 } 4895 4896 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4897 SmallVectorImpl<SDValue> &Results, 4898 SelectionDAG &DAG) const { 4899 switch (N->getOpcode()) { 4900 case ISD::INSERT_VECTOR_ELT: { 4901 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4902 Results.push_back(Res); 4903 return; 4904 } 4905 case ISD::EXTRACT_VECTOR_ELT: { 4906 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4907 Results.push_back(Res); 4908 return; 4909 } 4910 case ISD::INTRINSIC_WO_CHAIN: { 4911 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4912 switch (IID) { 4913 case Intrinsic::amdgcn_cvt_pkrtz: { 4914 SDValue Src0 = N->getOperand(1); 4915 SDValue Src1 = N->getOperand(2); 4916 SDLoc SL(N); 4917 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4918 Src0, Src1); 4919 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4920 return; 4921 } 4922 case Intrinsic::amdgcn_cvt_pknorm_i16: 4923 case Intrinsic::amdgcn_cvt_pknorm_u16: 4924 case Intrinsic::amdgcn_cvt_pk_i16: 4925 case Intrinsic::amdgcn_cvt_pk_u16: { 4926 SDValue Src0 = N->getOperand(1); 4927 SDValue Src1 = N->getOperand(2); 4928 SDLoc SL(N); 4929 unsigned Opcode; 4930 4931 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4932 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4933 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4934 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4935 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4936 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4937 else 4938 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4939 4940 EVT VT = N->getValueType(0); 4941 if (isTypeLegal(VT)) 4942 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4943 else { 4944 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4945 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4946 } 4947 return; 4948 } 4949 } 4950 break; 4951 } 4952 case ISD::INTRINSIC_W_CHAIN: { 4953 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4954 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4955 // FIXME: Hacky 4956 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4957 Results.push_back(Res.getOperand(I)); 4958 } 4959 } else { 4960 Results.push_back(Res); 4961 Results.push_back(Res.getValue(1)); 4962 } 4963 return; 4964 } 4965 4966 break; 4967 } 4968 case ISD::SELECT: { 4969 SDLoc SL(N); 4970 EVT VT = N->getValueType(0); 4971 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4972 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4973 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4974 4975 EVT SelectVT = NewVT; 4976 if (NewVT.bitsLT(MVT::i32)) { 4977 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4978 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4979 SelectVT = MVT::i32; 4980 } 4981 4982 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4983 N->getOperand(0), LHS, RHS); 4984 4985 if (NewVT != SelectVT) 4986 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4987 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4988 return; 4989 } 4990 case ISD::FNEG: { 4991 if (N->getValueType(0) != MVT::v2f16) 4992 break; 4993 4994 SDLoc SL(N); 4995 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4996 4997 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4998 BC, 4999 DAG.getConstant(0x80008000, SL, MVT::i32)); 5000 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5001 return; 5002 } 5003 case ISD::FABS: { 5004 if (N->getValueType(0) != MVT::v2f16) 5005 break; 5006 5007 SDLoc SL(N); 5008 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5009 5010 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5011 BC, 5012 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5013 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5014 return; 5015 } 5016 default: 5017 break; 5018 } 5019 } 5020 5021 /// Helper function for LowerBRCOND 5022 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5023 5024 SDNode *Parent = Value.getNode(); 5025 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5026 I != E; ++I) { 5027 5028 if (I.getUse().get() != Value) 5029 continue; 5030 5031 if (I->getOpcode() == Opcode) 5032 return *I; 5033 } 5034 return nullptr; 5035 } 5036 5037 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5038 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5039 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5040 case Intrinsic::amdgcn_if: 5041 return AMDGPUISD::IF; 5042 case Intrinsic::amdgcn_else: 5043 return AMDGPUISD::ELSE; 5044 case Intrinsic::amdgcn_loop: 5045 return AMDGPUISD::LOOP; 5046 case Intrinsic::amdgcn_end_cf: 5047 llvm_unreachable("should not occur"); 5048 default: 5049 return 0; 5050 } 5051 } 5052 5053 // break, if_break, else_break are all only used as inputs to loop, not 5054 // directly as branch conditions. 5055 return 0; 5056 } 5057 5058 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5059 const Triple &TT = getTargetMachine().getTargetTriple(); 5060 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5061 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5062 AMDGPU::shouldEmitConstantsToTextSection(TT); 5063 } 5064 5065 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5066 // FIXME: Either avoid relying on address space here or change the default 5067 // address space for functions to avoid the explicit check. 5068 return (GV->getValueType()->isFunctionTy() || 5069 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5070 !shouldEmitFixup(GV) && 5071 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5072 } 5073 5074 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5075 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5076 } 5077 5078 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5079 if (!GV->hasExternalLinkage()) 5080 return true; 5081 5082 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5083 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5084 } 5085 5086 /// This transforms the control flow intrinsics to get the branch destination as 5087 /// last parameter, also switches branch target with BR if the need arise 5088 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5089 SelectionDAG &DAG) const { 5090 SDLoc DL(BRCOND); 5091 5092 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5093 SDValue Target = BRCOND.getOperand(2); 5094 SDNode *BR = nullptr; 5095 SDNode *SetCC = nullptr; 5096 5097 if (Intr->getOpcode() == ISD::SETCC) { 5098 // As long as we negate the condition everything is fine 5099 SetCC = Intr; 5100 Intr = SetCC->getOperand(0).getNode(); 5101 5102 } else { 5103 // Get the target from BR if we don't negate the condition 5104 BR = findUser(BRCOND, ISD::BR); 5105 assert(BR && "brcond missing unconditional branch user"); 5106 Target = BR->getOperand(1); 5107 } 5108 5109 unsigned CFNode = isCFIntrinsic(Intr); 5110 if (CFNode == 0) { 5111 // This is a uniform branch so we don't need to legalize. 5112 return BRCOND; 5113 } 5114 5115 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5116 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5117 5118 assert(!SetCC || 5119 (SetCC->getConstantOperandVal(1) == 1 && 5120 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5121 ISD::SETNE)); 5122 5123 // operands of the new intrinsic call 5124 SmallVector<SDValue, 4> Ops; 5125 if (HaveChain) 5126 Ops.push_back(BRCOND.getOperand(0)); 5127 5128 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5129 Ops.push_back(Target); 5130 5131 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5132 5133 // build the new intrinsic call 5134 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5135 5136 if (!HaveChain) { 5137 SDValue Ops[] = { 5138 SDValue(Result, 0), 5139 BRCOND.getOperand(0) 5140 }; 5141 5142 Result = DAG.getMergeValues(Ops, DL).getNode(); 5143 } 5144 5145 if (BR) { 5146 // Give the branch instruction our target 5147 SDValue Ops[] = { 5148 BR->getOperand(0), 5149 BRCOND.getOperand(2) 5150 }; 5151 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5152 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5153 } 5154 5155 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5156 5157 // Copy the intrinsic results to registers 5158 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5159 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5160 if (!CopyToReg) 5161 continue; 5162 5163 Chain = DAG.getCopyToReg( 5164 Chain, DL, 5165 CopyToReg->getOperand(1), 5166 SDValue(Result, i - 1), 5167 SDValue()); 5168 5169 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5170 } 5171 5172 // Remove the old intrinsic from the chain 5173 DAG.ReplaceAllUsesOfValueWith( 5174 SDValue(Intr, Intr->getNumValues() - 1), 5175 Intr->getOperand(0)); 5176 5177 return Chain; 5178 } 5179 5180 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5181 SelectionDAG &DAG) const { 5182 MVT VT = Op.getSimpleValueType(); 5183 SDLoc DL(Op); 5184 // Checking the depth 5185 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5186 return DAG.getConstant(0, DL, VT); 5187 5188 MachineFunction &MF = DAG.getMachineFunction(); 5189 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5190 // Check for kernel and shader functions 5191 if (Info->isEntryFunction()) 5192 return DAG.getConstant(0, DL, VT); 5193 5194 MachineFrameInfo &MFI = MF.getFrameInfo(); 5195 // There is a call to @llvm.returnaddress in this function 5196 MFI.setReturnAddressIsTaken(true); 5197 5198 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5199 // Get the return address reg and mark it as an implicit live-in 5200 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5201 5202 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5203 } 5204 5205 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5206 SDValue Op, 5207 const SDLoc &DL, 5208 EVT VT) const { 5209 return Op.getValueType().bitsLE(VT) ? 5210 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5211 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5212 DAG.getTargetConstant(0, DL, MVT::i32)); 5213 } 5214 5215 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5216 assert(Op.getValueType() == MVT::f16 && 5217 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5218 5219 SDValue Src = Op.getOperand(0); 5220 EVT SrcVT = Src.getValueType(); 5221 if (SrcVT != MVT::f64) 5222 return Op; 5223 5224 SDLoc DL(Op); 5225 5226 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5227 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5228 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5229 } 5230 5231 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5232 SelectionDAG &DAG) const { 5233 EVT VT = Op.getValueType(); 5234 const MachineFunction &MF = DAG.getMachineFunction(); 5235 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5236 bool IsIEEEMode = Info->getMode().IEEE; 5237 5238 // FIXME: Assert during selection that this is only selected for 5239 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5240 // mode functions, but this happens to be OK since it's only done in cases 5241 // where there is known no sNaN. 5242 if (IsIEEEMode) 5243 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5244 5245 if (VT == MVT::v4f16) 5246 return splitBinaryVectorOp(Op, DAG); 5247 return Op; 5248 } 5249 5250 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5251 EVT VT = Op.getValueType(); 5252 SDLoc SL(Op); 5253 SDValue LHS = Op.getOperand(0); 5254 SDValue RHS = Op.getOperand(1); 5255 bool isSigned = Op.getOpcode() == ISD::SMULO; 5256 5257 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5258 const APInt &C = RHSC->getAPIntValue(); 5259 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5260 if (C.isPowerOf2()) { 5261 // smulo(x, signed_min) is same as umulo(x, signed_min). 5262 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5263 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5264 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5265 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5266 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5267 SL, VT, Result, ShiftAmt), 5268 LHS, ISD::SETNE); 5269 return DAG.getMergeValues({ Result, Overflow }, SL); 5270 } 5271 } 5272 5273 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5274 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5275 SL, VT, LHS, RHS); 5276 5277 SDValue Sign = isSigned 5278 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5279 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5280 : DAG.getConstant(0, SL, VT); 5281 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5282 5283 return DAG.getMergeValues({ Result, Overflow }, SL); 5284 } 5285 5286 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5287 if (!Subtarget->isTrapHandlerEnabled() || 5288 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5289 return lowerTrapEndpgm(Op, DAG); 5290 5291 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5292 switch (*HsaAbiVer) { 5293 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5294 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5295 return lowerTrapHsaQueuePtr(Op, DAG); 5296 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5297 return Subtarget->supportsGetDoorbellID() ? 5298 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5299 } 5300 } 5301 5302 llvm_unreachable("Unknown trap handler"); 5303 } 5304 5305 SDValue SITargetLowering::lowerTrapEndpgm( 5306 SDValue Op, SelectionDAG &DAG) const { 5307 SDLoc SL(Op); 5308 SDValue Chain = Op.getOperand(0); 5309 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5310 } 5311 5312 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5313 SDValue Op, SelectionDAG &DAG) const { 5314 SDLoc SL(Op); 5315 SDValue Chain = Op.getOperand(0); 5316 5317 MachineFunction &MF = DAG.getMachineFunction(); 5318 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5319 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5320 5321 SDValue QueuePtr; 5322 if (UserSGPR == AMDGPU::NoRegister) { 5323 // We probably are in a function incorrectly marked with 5324 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5325 // so just use a null pointer. 5326 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5327 } else { 5328 QueuePtr = CreateLiveInRegister( 5329 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5330 } 5331 5332 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5333 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5334 QueuePtr, SDValue()); 5335 5336 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5337 SDValue Ops[] = { 5338 ToReg, 5339 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5340 SGPR01, 5341 ToReg.getValue(1) 5342 }; 5343 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5344 } 5345 5346 SDValue SITargetLowering::lowerTrapHsa( 5347 SDValue Op, SelectionDAG &DAG) const { 5348 SDLoc SL(Op); 5349 SDValue Chain = Op.getOperand(0); 5350 5351 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5352 SDValue Ops[] = { 5353 Chain, 5354 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5355 }; 5356 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5357 } 5358 5359 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5360 SDLoc SL(Op); 5361 SDValue Chain = Op.getOperand(0); 5362 MachineFunction &MF = DAG.getMachineFunction(); 5363 5364 if (!Subtarget->isTrapHandlerEnabled() || 5365 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5366 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5367 "debugtrap handler not supported", 5368 Op.getDebugLoc(), 5369 DS_Warning); 5370 LLVMContext &Ctx = MF.getFunction().getContext(); 5371 Ctx.diagnose(NoTrap); 5372 return Chain; 5373 } 5374 5375 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5376 SDValue Ops[] = { 5377 Chain, 5378 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5379 }; 5380 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5381 } 5382 5383 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5384 SelectionDAG &DAG) const { 5385 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5386 if (Subtarget->hasApertureRegs()) { 5387 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5388 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5389 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5390 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5391 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5392 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5393 unsigned Encoding = 5394 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5395 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5396 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5397 5398 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5399 SDValue ApertureReg = SDValue( 5400 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5401 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5402 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5403 } 5404 5405 MachineFunction &MF = DAG.getMachineFunction(); 5406 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5407 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5408 if (UserSGPR == AMDGPU::NoRegister) { 5409 // We probably are in a function incorrectly marked with 5410 // amdgpu-no-queue-ptr. This is undefined. 5411 return DAG.getUNDEF(MVT::i32); 5412 } 5413 5414 SDValue QueuePtr = CreateLiveInRegister( 5415 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5416 5417 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5418 // private_segment_aperture_base_hi. 5419 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5420 5421 SDValue Ptr = 5422 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5423 5424 // TODO: Use custom target PseudoSourceValue. 5425 // TODO: We should use the value from the IR intrinsic call, but it might not 5426 // be available and how do we get it? 5427 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5428 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5429 commonAlignment(Align(64), StructOffset), 5430 MachineMemOperand::MODereferenceable | 5431 MachineMemOperand::MOInvariant); 5432 } 5433 5434 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5435 SelectionDAG &DAG) const { 5436 SDLoc SL(Op); 5437 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5438 5439 SDValue Src = ASC->getOperand(0); 5440 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5441 5442 const AMDGPUTargetMachine &TM = 5443 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5444 5445 // flat -> local/private 5446 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5447 unsigned DestAS = ASC->getDestAddressSpace(); 5448 5449 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5450 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5451 unsigned NullVal = TM.getNullPointerValue(DestAS); 5452 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5453 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5454 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5455 5456 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5457 NonNull, Ptr, SegmentNullPtr); 5458 } 5459 } 5460 5461 // local/private -> flat 5462 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5463 unsigned SrcAS = ASC->getSrcAddressSpace(); 5464 5465 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5466 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5467 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5468 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5469 5470 SDValue NonNull 5471 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5472 5473 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5474 SDValue CvtPtr 5475 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5476 5477 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5478 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5479 FlatNullPtr); 5480 } 5481 } 5482 5483 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5484 Src.getValueType() == MVT::i64) 5485 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5486 5487 // global <-> flat are no-ops and never emitted. 5488 5489 const MachineFunction &MF = DAG.getMachineFunction(); 5490 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5491 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5492 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5493 5494 return DAG.getUNDEF(ASC->getValueType(0)); 5495 } 5496 5497 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5498 // the small vector and inserting them into the big vector. That is better than 5499 // the default expansion of doing it via a stack slot. Even though the use of 5500 // the stack slot would be optimized away afterwards, the stack slot itself 5501 // remains. 5502 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5503 SelectionDAG &DAG) const { 5504 SDValue Vec = Op.getOperand(0); 5505 SDValue Ins = Op.getOperand(1); 5506 SDValue Idx = Op.getOperand(2); 5507 EVT VecVT = Vec.getValueType(); 5508 EVT InsVT = Ins.getValueType(); 5509 EVT EltVT = VecVT.getVectorElementType(); 5510 unsigned InsNumElts = InsVT.getVectorNumElements(); 5511 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5512 SDLoc SL(Op); 5513 5514 for (unsigned I = 0; I != InsNumElts; ++I) { 5515 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5516 DAG.getConstant(I, SL, MVT::i32)); 5517 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5518 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5519 } 5520 return Vec; 5521 } 5522 5523 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5524 SelectionDAG &DAG) const { 5525 SDValue Vec = Op.getOperand(0); 5526 SDValue InsVal = Op.getOperand(1); 5527 SDValue Idx = Op.getOperand(2); 5528 EVT VecVT = Vec.getValueType(); 5529 EVT EltVT = VecVT.getVectorElementType(); 5530 unsigned VecSize = VecVT.getSizeInBits(); 5531 unsigned EltSize = EltVT.getSizeInBits(); 5532 5533 5534 assert(VecSize <= 64); 5535 5536 unsigned NumElts = VecVT.getVectorNumElements(); 5537 SDLoc SL(Op); 5538 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5539 5540 if (NumElts == 4 && EltSize == 16 && KIdx) { 5541 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5542 5543 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5544 DAG.getConstant(0, SL, MVT::i32)); 5545 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5546 DAG.getConstant(1, SL, MVT::i32)); 5547 5548 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5549 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5550 5551 unsigned Idx = KIdx->getZExtValue(); 5552 bool InsertLo = Idx < 2; 5553 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5554 InsertLo ? LoVec : HiVec, 5555 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5556 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5557 5558 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5559 5560 SDValue Concat = InsertLo ? 5561 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5562 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5563 5564 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5565 } 5566 5567 if (isa<ConstantSDNode>(Idx)) 5568 return SDValue(); 5569 5570 MVT IntVT = MVT::getIntegerVT(VecSize); 5571 5572 // Avoid stack access for dynamic indexing. 5573 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5574 5575 // Create a congruent vector with the target value in each element so that 5576 // the required element can be masked and ORed into the target vector. 5577 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5578 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5579 5580 assert(isPowerOf2_32(EltSize)); 5581 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5582 5583 // Convert vector index to bit-index. 5584 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5585 5586 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5587 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5588 DAG.getConstant(0xffff, SL, IntVT), 5589 ScaledIdx); 5590 5591 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5592 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5593 DAG.getNOT(SL, BFM, IntVT), BCVec); 5594 5595 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5596 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5597 } 5598 5599 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5600 SelectionDAG &DAG) const { 5601 SDLoc SL(Op); 5602 5603 EVT ResultVT = Op.getValueType(); 5604 SDValue Vec = Op.getOperand(0); 5605 SDValue Idx = Op.getOperand(1); 5606 EVT VecVT = Vec.getValueType(); 5607 unsigned VecSize = VecVT.getSizeInBits(); 5608 EVT EltVT = VecVT.getVectorElementType(); 5609 assert(VecSize <= 64); 5610 5611 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5612 5613 // Make sure we do any optimizations that will make it easier to fold 5614 // source modifiers before obscuring it with bit operations. 5615 5616 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5617 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5618 return Combined; 5619 5620 unsigned EltSize = EltVT.getSizeInBits(); 5621 assert(isPowerOf2_32(EltSize)); 5622 5623 MVT IntVT = MVT::getIntegerVT(VecSize); 5624 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5625 5626 // Convert vector index to bit-index (* EltSize) 5627 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5628 5629 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5630 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5631 5632 if (ResultVT == MVT::f16) { 5633 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5634 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5635 } 5636 5637 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5638 } 5639 5640 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5641 assert(Elt % 2 == 0); 5642 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5643 } 5644 5645 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5646 SelectionDAG &DAG) const { 5647 SDLoc SL(Op); 5648 EVT ResultVT = Op.getValueType(); 5649 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5650 5651 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5652 EVT EltVT = PackVT.getVectorElementType(); 5653 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5654 5655 // vector_shuffle <0,1,6,7> lhs, rhs 5656 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5657 // 5658 // vector_shuffle <6,7,2,3> lhs, rhs 5659 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5660 // 5661 // vector_shuffle <6,7,0,1> lhs, rhs 5662 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5663 5664 // Avoid scalarizing when both halves are reading from consecutive elements. 5665 SmallVector<SDValue, 4> Pieces; 5666 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5667 if (elementPairIsContiguous(SVN->getMask(), I)) { 5668 const int Idx = SVN->getMaskElt(I); 5669 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5670 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5671 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5672 PackVT, SVN->getOperand(VecIdx), 5673 DAG.getConstant(EltIdx, SL, MVT::i32)); 5674 Pieces.push_back(SubVec); 5675 } else { 5676 const int Idx0 = SVN->getMaskElt(I); 5677 const int Idx1 = SVN->getMaskElt(I + 1); 5678 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5679 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5680 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5681 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5682 5683 SDValue Vec0 = SVN->getOperand(VecIdx0); 5684 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5685 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5686 5687 SDValue Vec1 = SVN->getOperand(VecIdx1); 5688 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5689 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5690 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5691 } 5692 } 5693 5694 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5695 } 5696 5697 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5698 SelectionDAG &DAG) const { 5699 SDLoc SL(Op); 5700 EVT VT = Op.getValueType(); 5701 5702 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5703 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5704 5705 // Turn into pair of packed build_vectors. 5706 // TODO: Special case for constants that can be materialized with s_mov_b64. 5707 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5708 { Op.getOperand(0), Op.getOperand(1) }); 5709 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5710 { Op.getOperand(2), Op.getOperand(3) }); 5711 5712 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5713 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5714 5715 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5716 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5717 } 5718 5719 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5720 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5721 5722 SDValue Lo = Op.getOperand(0); 5723 SDValue Hi = Op.getOperand(1); 5724 5725 // Avoid adding defined bits with the zero_extend. 5726 if (Hi.isUndef()) { 5727 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5728 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5729 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5730 } 5731 5732 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5733 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5734 5735 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5736 DAG.getConstant(16, SL, MVT::i32)); 5737 if (Lo.isUndef()) 5738 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5739 5740 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5741 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5742 5743 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5744 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5745 } 5746 5747 bool 5748 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5749 // We can fold offsets for anything that doesn't require a GOT relocation. 5750 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5751 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5752 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5753 !shouldEmitGOTReloc(GA->getGlobal()); 5754 } 5755 5756 static SDValue 5757 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5758 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5759 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5760 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5761 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5762 // lowered to the following code sequence: 5763 // 5764 // For constant address space: 5765 // s_getpc_b64 s[0:1] 5766 // s_add_u32 s0, s0, $symbol 5767 // s_addc_u32 s1, s1, 0 5768 // 5769 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5770 // a fixup or relocation is emitted to replace $symbol with a literal 5771 // constant, which is a pc-relative offset from the encoding of the $symbol 5772 // operand to the global variable. 5773 // 5774 // For global address space: 5775 // s_getpc_b64 s[0:1] 5776 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5777 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5778 // 5779 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5780 // fixups or relocations are emitted to replace $symbol@*@lo and 5781 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5782 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5783 // operand to the global variable. 5784 // 5785 // What we want here is an offset from the value returned by s_getpc 5786 // (which is the address of the s_add_u32 instruction) to the global 5787 // variable, but since the encoding of $symbol starts 4 bytes after the start 5788 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5789 // small. This requires us to add 4 to the global variable offset in order to 5790 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5791 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5792 // instruction. 5793 SDValue PtrLo = 5794 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5795 SDValue PtrHi; 5796 if (GAFlags == SIInstrInfo::MO_NONE) { 5797 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5798 } else { 5799 PtrHi = 5800 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5801 } 5802 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5803 } 5804 5805 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5806 SDValue Op, 5807 SelectionDAG &DAG) const { 5808 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5809 SDLoc DL(GSD); 5810 EVT PtrVT = Op.getValueType(); 5811 5812 const GlobalValue *GV = GSD->getGlobal(); 5813 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5814 shouldUseLDSConstAddress(GV)) || 5815 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5816 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5817 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5818 GV->hasExternalLinkage()) { 5819 Type *Ty = GV->getValueType(); 5820 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5821 // zero-sized type in other languages to declare the dynamic shared 5822 // memory which size is not known at the compile time. They will be 5823 // allocated by the runtime and placed directly after the static 5824 // allocated ones. They all share the same offset. 5825 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5826 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5827 // Adjust alignment for that dynamic shared memory array. 5828 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5829 return SDValue( 5830 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5831 } 5832 } 5833 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5834 } 5835 5836 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5837 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5838 SIInstrInfo::MO_ABS32_LO); 5839 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5840 } 5841 5842 if (shouldEmitFixup(GV)) 5843 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5844 else if (shouldEmitPCReloc(GV)) 5845 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5846 SIInstrInfo::MO_REL32); 5847 5848 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5849 SIInstrInfo::MO_GOTPCREL32); 5850 5851 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5852 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5853 const DataLayout &DataLayout = DAG.getDataLayout(); 5854 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5855 MachinePointerInfo PtrInfo 5856 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5857 5858 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5859 MachineMemOperand::MODereferenceable | 5860 MachineMemOperand::MOInvariant); 5861 } 5862 5863 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5864 const SDLoc &DL, SDValue V) const { 5865 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5866 // the destination register. 5867 // 5868 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5869 // so we will end up with redundant moves to m0. 5870 // 5871 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5872 5873 // A Null SDValue creates a glue result. 5874 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5875 V, Chain); 5876 return SDValue(M0, 0); 5877 } 5878 5879 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5880 SDValue Op, 5881 MVT VT, 5882 unsigned Offset) const { 5883 SDLoc SL(Op); 5884 SDValue Param = lowerKernargMemParameter( 5885 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5886 // The local size values will have the hi 16-bits as zero. 5887 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5888 DAG.getValueType(VT)); 5889 } 5890 5891 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5892 EVT VT) { 5893 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5894 "non-hsa intrinsic with hsa target", 5895 DL.getDebugLoc()); 5896 DAG.getContext()->diagnose(BadIntrin); 5897 return DAG.getUNDEF(VT); 5898 } 5899 5900 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5901 EVT VT) { 5902 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5903 "intrinsic not supported on subtarget", 5904 DL.getDebugLoc()); 5905 DAG.getContext()->diagnose(BadIntrin); 5906 return DAG.getUNDEF(VT); 5907 } 5908 5909 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5910 ArrayRef<SDValue> Elts) { 5911 assert(!Elts.empty()); 5912 MVT Type; 5913 unsigned NumElts = Elts.size(); 5914 5915 if (NumElts <= 8) { 5916 Type = MVT::getVectorVT(MVT::f32, NumElts); 5917 } else { 5918 assert(Elts.size() <= 16); 5919 Type = MVT::v16f32; 5920 NumElts = 16; 5921 } 5922 5923 SmallVector<SDValue, 16> VecElts(NumElts); 5924 for (unsigned i = 0; i < Elts.size(); ++i) { 5925 SDValue Elt = Elts[i]; 5926 if (Elt.getValueType() != MVT::f32) 5927 Elt = DAG.getBitcast(MVT::f32, Elt); 5928 VecElts[i] = Elt; 5929 } 5930 for (unsigned i = Elts.size(); i < NumElts; ++i) 5931 VecElts[i] = DAG.getUNDEF(MVT::f32); 5932 5933 if (NumElts == 1) 5934 return VecElts[0]; 5935 return DAG.getBuildVector(Type, DL, VecElts); 5936 } 5937 5938 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5939 SDValue Src, int ExtraElts) { 5940 EVT SrcVT = Src.getValueType(); 5941 5942 SmallVector<SDValue, 8> Elts; 5943 5944 if (SrcVT.isVector()) 5945 DAG.ExtractVectorElements(Src, Elts); 5946 else 5947 Elts.push_back(Src); 5948 5949 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5950 while (ExtraElts--) 5951 Elts.push_back(Undef); 5952 5953 return DAG.getBuildVector(CastVT, DL, Elts); 5954 } 5955 5956 // Re-construct the required return value for a image load intrinsic. 5957 // This is more complicated due to the optional use TexFailCtrl which means the required 5958 // return type is an aggregate 5959 static SDValue constructRetValue(SelectionDAG &DAG, 5960 MachineSDNode *Result, 5961 ArrayRef<EVT> ResultTypes, 5962 bool IsTexFail, bool Unpacked, bool IsD16, 5963 int DMaskPop, int NumVDataDwords, 5964 const SDLoc &DL) { 5965 // Determine the required return type. This is the same regardless of IsTexFail flag 5966 EVT ReqRetVT = ResultTypes[0]; 5967 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5968 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5969 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5970 5971 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5972 DMaskPop : (DMaskPop + 1) / 2; 5973 5974 MVT DataDwordVT = NumDataDwords == 1 ? 5975 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5976 5977 MVT MaskPopVT = MaskPopDwords == 1 ? 5978 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5979 5980 SDValue Data(Result, 0); 5981 SDValue TexFail; 5982 5983 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5984 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5985 if (MaskPopVT.isVector()) { 5986 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5987 SDValue(Result, 0), ZeroIdx); 5988 } else { 5989 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5990 SDValue(Result, 0), ZeroIdx); 5991 } 5992 } 5993 5994 if (DataDwordVT.isVector()) 5995 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5996 NumDataDwords - MaskPopDwords); 5997 5998 if (IsD16) 5999 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6000 6001 EVT LegalReqRetVT = ReqRetVT; 6002 if (!ReqRetVT.isVector()) { 6003 if (!Data.getValueType().isInteger()) 6004 Data = DAG.getNode(ISD::BITCAST, DL, 6005 Data.getValueType().changeTypeToInteger(), Data); 6006 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6007 } else { 6008 // We need to widen the return vector to a legal type 6009 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6010 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6011 LegalReqRetVT = 6012 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6013 ReqRetVT.getVectorNumElements() + 1); 6014 } 6015 } 6016 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6017 6018 if (IsTexFail) { 6019 TexFail = 6020 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6021 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6022 6023 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6024 } 6025 6026 if (Result->getNumValues() == 1) 6027 return Data; 6028 6029 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6030 } 6031 6032 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6033 SDValue *LWE, bool &IsTexFail) { 6034 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6035 6036 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6037 if (Value) { 6038 IsTexFail = true; 6039 } 6040 6041 SDLoc DL(TexFailCtrlConst); 6042 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6043 Value &= ~(uint64_t)0x1; 6044 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6045 Value &= ~(uint64_t)0x2; 6046 6047 return Value == 0; 6048 } 6049 6050 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6051 MVT PackVectorVT, 6052 SmallVectorImpl<SDValue> &PackedAddrs, 6053 unsigned DimIdx, unsigned EndIdx, 6054 unsigned NumGradients) { 6055 SDLoc DL(Op); 6056 for (unsigned I = DimIdx; I < EndIdx; I++) { 6057 SDValue Addr = Op.getOperand(I); 6058 6059 // Gradients are packed with undef for each coordinate. 6060 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6061 // 1D: undef,dx/dh; undef,dx/dv 6062 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6063 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6064 if (((I + 1) >= EndIdx) || 6065 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6066 I == DimIdx + NumGradients - 1))) { 6067 if (Addr.getValueType() != MVT::i16) 6068 Addr = DAG.getBitcast(MVT::i16, Addr); 6069 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6070 } else { 6071 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6072 I++; 6073 } 6074 Addr = DAG.getBitcast(MVT::f32, Addr); 6075 PackedAddrs.push_back(Addr); 6076 } 6077 } 6078 6079 SDValue SITargetLowering::lowerImage(SDValue Op, 6080 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6081 SelectionDAG &DAG, bool WithChain) const { 6082 SDLoc DL(Op); 6083 MachineFunction &MF = DAG.getMachineFunction(); 6084 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6085 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6086 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6087 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6088 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6089 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6090 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6091 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6092 unsigned IntrOpcode = Intr->BaseOpcode; 6093 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6094 6095 SmallVector<EVT, 3> ResultTypes(Op->values()); 6096 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6097 bool IsD16 = false; 6098 bool IsG16 = false; 6099 bool IsA16 = false; 6100 SDValue VData; 6101 int NumVDataDwords; 6102 bool AdjustRetType = false; 6103 6104 // Offset of intrinsic arguments 6105 const unsigned ArgOffset = WithChain ? 2 : 1; 6106 6107 unsigned DMask; 6108 unsigned DMaskLanes = 0; 6109 6110 if (BaseOpcode->Atomic) { 6111 VData = Op.getOperand(2); 6112 6113 bool Is64Bit = VData.getValueType() == MVT::i64; 6114 if (BaseOpcode->AtomicX2) { 6115 SDValue VData2 = Op.getOperand(3); 6116 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6117 {VData, VData2}); 6118 if (Is64Bit) 6119 VData = DAG.getBitcast(MVT::v4i32, VData); 6120 6121 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6122 DMask = Is64Bit ? 0xf : 0x3; 6123 NumVDataDwords = Is64Bit ? 4 : 2; 6124 } else { 6125 DMask = Is64Bit ? 0x3 : 0x1; 6126 NumVDataDwords = Is64Bit ? 2 : 1; 6127 } 6128 } else { 6129 auto *DMaskConst = 6130 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6131 DMask = DMaskConst->getZExtValue(); 6132 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6133 6134 if (BaseOpcode->Store) { 6135 VData = Op.getOperand(2); 6136 6137 MVT StoreVT = VData.getSimpleValueType(); 6138 if (StoreVT.getScalarType() == MVT::f16) { 6139 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6140 return Op; // D16 is unsupported for this instruction 6141 6142 IsD16 = true; 6143 VData = handleD16VData(VData, DAG, true); 6144 } 6145 6146 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6147 } else { 6148 // Work out the num dwords based on the dmask popcount and underlying type 6149 // and whether packing is supported. 6150 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6151 if (LoadVT.getScalarType() == MVT::f16) { 6152 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6153 return Op; // D16 is unsupported for this instruction 6154 6155 IsD16 = true; 6156 } 6157 6158 // Confirm that the return type is large enough for the dmask specified 6159 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6160 (!LoadVT.isVector() && DMaskLanes > 1)) 6161 return Op; 6162 6163 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6164 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6165 // instructions. 6166 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6167 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6168 NumVDataDwords = (DMaskLanes + 1) / 2; 6169 else 6170 NumVDataDwords = DMaskLanes; 6171 6172 AdjustRetType = true; 6173 } 6174 } 6175 6176 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6177 SmallVector<SDValue, 4> VAddrs; 6178 6179 // Optimize _L to _LZ when _L is zero 6180 if (LZMappingInfo) { 6181 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6182 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6183 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6184 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6185 VAddrEnd--; // remove 'lod' 6186 } 6187 } 6188 } 6189 6190 // Optimize _mip away, when 'lod' is zero 6191 if (MIPMappingInfo) { 6192 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6193 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6194 if (ConstantLod->isZero()) { 6195 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6196 VAddrEnd--; // remove 'mip' 6197 } 6198 } 6199 } 6200 6201 // Push back extra arguments. 6202 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6203 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6204 6205 // Check for 16 bit addresses or derivatives and pack if true. 6206 MVT VAddrVT = 6207 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6208 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6209 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6210 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6211 6212 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6213 VAddrScalarVT = VAddrVT.getScalarType(); 6214 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6215 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6216 6217 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6218 // 16 bit gradients are supported, but are tied to the A16 control 6219 // so both gradients and addresses must be 16 bit 6220 LLVM_DEBUG( 6221 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6222 "require 16 bit args for both gradients and addresses"); 6223 return Op; 6224 } 6225 6226 if (IsA16) { 6227 if (!ST->hasA16()) { 6228 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6229 "support 16 bit addresses\n"); 6230 return Op; 6231 } 6232 } 6233 6234 // We've dealt with incorrect input so we know that if IsA16, IsG16 6235 // are set then we have to compress/pack operands (either address, 6236 // gradient or both) 6237 // In the case where a16 and gradients are tied (no G16 support) then we 6238 // have already verified that both IsA16 and IsG16 are true 6239 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6240 // Activate g16 6241 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6242 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6243 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6244 } 6245 6246 // Add gradients (packed or unpacked) 6247 if (IsG16) { 6248 // Pack the gradients 6249 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6250 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6251 ArgOffset + Intr->GradientStart, 6252 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6253 } else { 6254 for (unsigned I = ArgOffset + Intr->GradientStart; 6255 I < ArgOffset + Intr->CoordStart; I++) 6256 VAddrs.push_back(Op.getOperand(I)); 6257 } 6258 6259 // Add addresses (packed or unpacked) 6260 if (IsA16) { 6261 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6262 ArgOffset + Intr->CoordStart, VAddrEnd, 6263 0 /* No gradients */); 6264 } else { 6265 // Add uncompressed address 6266 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6267 VAddrs.push_back(Op.getOperand(I)); 6268 } 6269 6270 // If the register allocator cannot place the address registers contiguously 6271 // without introducing moves, then using the non-sequential address encoding 6272 // is always preferable, since it saves VALU instructions and is usually a 6273 // wash in terms of code size or even better. 6274 // 6275 // However, we currently have no way of hinting to the register allocator that 6276 // MIMG addresses should be placed contiguously when it is possible to do so, 6277 // so force non-NSA for the common 2-address case as a heuristic. 6278 // 6279 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6280 // allocation when possible. 6281 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6282 VAddrs.size() >= 3 && 6283 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6284 SDValue VAddr; 6285 if (!UseNSA) 6286 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6287 6288 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6289 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6290 SDValue Unorm; 6291 if (!BaseOpcode->Sampler) { 6292 Unorm = True; 6293 } else { 6294 auto UnormConst = 6295 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6296 6297 Unorm = UnormConst->getZExtValue() ? True : False; 6298 } 6299 6300 SDValue TFE; 6301 SDValue LWE; 6302 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6303 bool IsTexFail = false; 6304 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6305 return Op; 6306 6307 if (IsTexFail) { 6308 if (!DMaskLanes) { 6309 // Expecting to get an error flag since TFC is on - and dmask is 0 6310 // Force dmask to be at least 1 otherwise the instruction will fail 6311 DMask = 0x1; 6312 DMaskLanes = 1; 6313 NumVDataDwords = 1; 6314 } 6315 NumVDataDwords += 1; 6316 AdjustRetType = true; 6317 } 6318 6319 // Has something earlier tagged that the return type needs adjusting 6320 // This happens if the instruction is a load or has set TexFailCtrl flags 6321 if (AdjustRetType) { 6322 // NumVDataDwords reflects the true number of dwords required in the return type 6323 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6324 // This is a no-op load. This can be eliminated 6325 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6326 if (isa<MemSDNode>(Op)) 6327 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6328 return Undef; 6329 } 6330 6331 EVT NewVT = NumVDataDwords > 1 ? 6332 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6333 : MVT::i32; 6334 6335 ResultTypes[0] = NewVT; 6336 if (ResultTypes.size() == 3) { 6337 // Original result was aggregate type used for TexFailCtrl results 6338 // The actual instruction returns as a vector type which has now been 6339 // created. Remove the aggregate result. 6340 ResultTypes.erase(&ResultTypes[1]); 6341 } 6342 } 6343 6344 unsigned CPol = cast<ConstantSDNode>( 6345 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6346 if (BaseOpcode->Atomic) 6347 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6348 if (CPol & ~AMDGPU::CPol::ALL) 6349 return Op; 6350 6351 SmallVector<SDValue, 26> Ops; 6352 if (BaseOpcode->Store || BaseOpcode->Atomic) 6353 Ops.push_back(VData); // vdata 6354 if (UseNSA) 6355 append_range(Ops, VAddrs); 6356 else 6357 Ops.push_back(VAddr); 6358 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6359 if (BaseOpcode->Sampler) 6360 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6361 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6362 if (IsGFX10Plus) 6363 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6364 Ops.push_back(Unorm); 6365 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6366 Ops.push_back(IsA16 && // r128, a16 for gfx9 6367 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6368 if (IsGFX10Plus) 6369 Ops.push_back(IsA16 ? True : False); 6370 if (!Subtarget->hasGFX90AInsts()) { 6371 Ops.push_back(TFE); //tfe 6372 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6373 report_fatal_error("TFE is not supported on this GPU"); 6374 } 6375 Ops.push_back(LWE); // lwe 6376 if (!IsGFX10Plus) 6377 Ops.push_back(DimInfo->DA ? True : False); 6378 if (BaseOpcode->HasD16) 6379 Ops.push_back(IsD16 ? True : False); 6380 if (isa<MemSDNode>(Op)) 6381 Ops.push_back(Op.getOperand(0)); // chain 6382 6383 int NumVAddrDwords = 6384 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6385 int Opcode = -1; 6386 6387 if (IsGFX10Plus) { 6388 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6389 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6390 : AMDGPU::MIMGEncGfx10Default, 6391 NumVDataDwords, NumVAddrDwords); 6392 } else { 6393 if (Subtarget->hasGFX90AInsts()) { 6394 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6395 NumVDataDwords, NumVAddrDwords); 6396 if (Opcode == -1) 6397 report_fatal_error( 6398 "requested image instruction is not supported on this GPU"); 6399 } 6400 if (Opcode == -1 && 6401 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6402 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6403 NumVDataDwords, NumVAddrDwords); 6404 if (Opcode == -1) 6405 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6406 NumVDataDwords, NumVAddrDwords); 6407 } 6408 assert(Opcode != -1); 6409 6410 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6411 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6412 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6413 DAG.setNodeMemRefs(NewNode, {MemRef}); 6414 } 6415 6416 if (BaseOpcode->AtomicX2) { 6417 SmallVector<SDValue, 1> Elt; 6418 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6419 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6420 } 6421 if (BaseOpcode->Store) 6422 return SDValue(NewNode, 0); 6423 return constructRetValue(DAG, NewNode, 6424 OrigResultTypes, IsTexFail, 6425 Subtarget->hasUnpackedD16VMem(), IsD16, 6426 DMaskLanes, NumVDataDwords, DL); 6427 } 6428 6429 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6430 SDValue Offset, SDValue CachePolicy, 6431 SelectionDAG &DAG) const { 6432 MachineFunction &MF = DAG.getMachineFunction(); 6433 6434 const DataLayout &DataLayout = DAG.getDataLayout(); 6435 Align Alignment = 6436 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6437 6438 MachineMemOperand *MMO = MF.getMachineMemOperand( 6439 MachinePointerInfo(), 6440 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6441 MachineMemOperand::MOInvariant, 6442 VT.getStoreSize(), Alignment); 6443 6444 if (!Offset->isDivergent()) { 6445 SDValue Ops[] = { 6446 Rsrc, 6447 Offset, // Offset 6448 CachePolicy 6449 }; 6450 6451 // Widen vec3 load to vec4. 6452 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6453 EVT WidenedVT = 6454 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6455 auto WidenedOp = DAG.getMemIntrinsicNode( 6456 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6457 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6458 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6459 DAG.getVectorIdxConstant(0, DL)); 6460 return Subvector; 6461 } 6462 6463 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6464 DAG.getVTList(VT), Ops, VT, MMO); 6465 } 6466 6467 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6468 // assume that the buffer is unswizzled. 6469 SmallVector<SDValue, 4> Loads; 6470 unsigned NumLoads = 1; 6471 MVT LoadVT = VT.getSimpleVT(); 6472 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6473 assert((LoadVT.getScalarType() == MVT::i32 || 6474 LoadVT.getScalarType() == MVT::f32)); 6475 6476 if (NumElts == 8 || NumElts == 16) { 6477 NumLoads = NumElts / 4; 6478 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6479 } 6480 6481 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6482 SDValue Ops[] = { 6483 DAG.getEntryNode(), // Chain 6484 Rsrc, // rsrc 6485 DAG.getConstant(0, DL, MVT::i32), // vindex 6486 {}, // voffset 6487 {}, // soffset 6488 {}, // offset 6489 CachePolicy, // cachepolicy 6490 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6491 }; 6492 6493 // Use the alignment to ensure that the required offsets will fit into the 6494 // immediate offsets. 6495 setBufferOffsets(Offset, DAG, &Ops[3], 6496 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6497 6498 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6499 for (unsigned i = 0; i < NumLoads; ++i) { 6500 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6501 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6502 LoadVT, MMO, DAG)); 6503 } 6504 6505 if (NumElts == 8 || NumElts == 16) 6506 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6507 6508 return Loads[0]; 6509 } 6510 6511 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6512 SelectionDAG &DAG) const { 6513 MachineFunction &MF = DAG.getMachineFunction(); 6514 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6515 6516 EVT VT = Op.getValueType(); 6517 SDLoc DL(Op); 6518 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6519 6520 // TODO: Should this propagate fast-math-flags? 6521 6522 switch (IntrinsicID) { 6523 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6524 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6525 return emitNonHSAIntrinsicError(DAG, DL, VT); 6526 return getPreloadedValue(DAG, *MFI, VT, 6527 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6528 } 6529 case Intrinsic::amdgcn_dispatch_ptr: 6530 case Intrinsic::amdgcn_queue_ptr: { 6531 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6532 DiagnosticInfoUnsupported BadIntrin( 6533 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6534 DL.getDebugLoc()); 6535 DAG.getContext()->diagnose(BadIntrin); 6536 return DAG.getUNDEF(VT); 6537 } 6538 6539 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6540 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6541 return getPreloadedValue(DAG, *MFI, VT, RegID); 6542 } 6543 case Intrinsic::amdgcn_implicitarg_ptr: { 6544 if (MFI->isEntryFunction()) 6545 return getImplicitArgPtr(DAG, DL); 6546 return getPreloadedValue(DAG, *MFI, VT, 6547 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6548 } 6549 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6550 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6551 // This only makes sense to call in a kernel, so just lower to null. 6552 return DAG.getConstant(0, DL, VT); 6553 } 6554 6555 return getPreloadedValue(DAG, *MFI, VT, 6556 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6557 } 6558 case Intrinsic::amdgcn_dispatch_id: { 6559 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6560 } 6561 case Intrinsic::amdgcn_rcp: 6562 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6563 case Intrinsic::amdgcn_rsq: 6564 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6565 case Intrinsic::amdgcn_rsq_legacy: 6566 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6567 return emitRemovedIntrinsicError(DAG, DL, VT); 6568 return SDValue(); 6569 case Intrinsic::amdgcn_rcp_legacy: 6570 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6571 return emitRemovedIntrinsicError(DAG, DL, VT); 6572 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6573 case Intrinsic::amdgcn_rsq_clamp: { 6574 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6575 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6576 6577 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6578 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6579 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6580 6581 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6582 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6583 DAG.getConstantFP(Max, DL, VT)); 6584 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6585 DAG.getConstantFP(Min, DL, VT)); 6586 } 6587 case Intrinsic::r600_read_ngroups_x: 6588 if (Subtarget->isAmdHsaOS()) 6589 return emitNonHSAIntrinsicError(DAG, DL, VT); 6590 6591 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6592 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6593 false); 6594 case Intrinsic::r600_read_ngroups_y: 6595 if (Subtarget->isAmdHsaOS()) 6596 return emitNonHSAIntrinsicError(DAG, DL, VT); 6597 6598 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6599 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6600 false); 6601 case Intrinsic::r600_read_ngroups_z: 6602 if (Subtarget->isAmdHsaOS()) 6603 return emitNonHSAIntrinsicError(DAG, DL, VT); 6604 6605 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6606 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6607 false); 6608 case Intrinsic::r600_read_global_size_x: 6609 if (Subtarget->isAmdHsaOS()) 6610 return emitNonHSAIntrinsicError(DAG, DL, VT); 6611 6612 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6613 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6614 Align(4), false); 6615 case Intrinsic::r600_read_global_size_y: 6616 if (Subtarget->isAmdHsaOS()) 6617 return emitNonHSAIntrinsicError(DAG, DL, VT); 6618 6619 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6620 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6621 Align(4), false); 6622 case Intrinsic::r600_read_global_size_z: 6623 if (Subtarget->isAmdHsaOS()) 6624 return emitNonHSAIntrinsicError(DAG, DL, VT); 6625 6626 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6627 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6628 Align(4), false); 6629 case Intrinsic::r600_read_local_size_x: 6630 if (Subtarget->isAmdHsaOS()) 6631 return emitNonHSAIntrinsicError(DAG, DL, VT); 6632 6633 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6634 SI::KernelInputOffsets::LOCAL_SIZE_X); 6635 case Intrinsic::r600_read_local_size_y: 6636 if (Subtarget->isAmdHsaOS()) 6637 return emitNonHSAIntrinsicError(DAG, DL, VT); 6638 6639 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6640 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6641 case Intrinsic::r600_read_local_size_z: 6642 if (Subtarget->isAmdHsaOS()) 6643 return emitNonHSAIntrinsicError(DAG, DL, VT); 6644 6645 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6646 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6647 case Intrinsic::amdgcn_workgroup_id_x: 6648 return getPreloadedValue(DAG, *MFI, VT, 6649 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6650 case Intrinsic::amdgcn_workgroup_id_y: 6651 return getPreloadedValue(DAG, *MFI, VT, 6652 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6653 case Intrinsic::amdgcn_workgroup_id_z: 6654 return getPreloadedValue(DAG, *MFI, VT, 6655 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6656 case Intrinsic::amdgcn_workitem_id_x: 6657 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6658 SDLoc(DAG.getEntryNode()), 6659 MFI->getArgInfo().WorkItemIDX); 6660 case Intrinsic::amdgcn_workitem_id_y: 6661 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6662 SDLoc(DAG.getEntryNode()), 6663 MFI->getArgInfo().WorkItemIDY); 6664 case Intrinsic::amdgcn_workitem_id_z: 6665 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6666 SDLoc(DAG.getEntryNode()), 6667 MFI->getArgInfo().WorkItemIDZ); 6668 case Intrinsic::amdgcn_wavefrontsize: 6669 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6670 SDLoc(Op), MVT::i32); 6671 case Intrinsic::amdgcn_s_buffer_load: { 6672 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6673 if (CPol & ~AMDGPU::CPol::ALL) 6674 return Op; 6675 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6676 DAG); 6677 } 6678 case Intrinsic::amdgcn_fdiv_fast: 6679 return lowerFDIV_FAST(Op, DAG); 6680 case Intrinsic::amdgcn_sin: 6681 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6682 6683 case Intrinsic::amdgcn_cos: 6684 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6685 6686 case Intrinsic::amdgcn_mul_u24: 6687 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6688 case Intrinsic::amdgcn_mul_i24: 6689 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6690 6691 case Intrinsic::amdgcn_log_clamp: { 6692 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6693 return SDValue(); 6694 6695 return emitRemovedIntrinsicError(DAG, DL, VT); 6696 } 6697 case Intrinsic::amdgcn_ldexp: 6698 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6699 Op.getOperand(1), Op.getOperand(2)); 6700 6701 case Intrinsic::amdgcn_fract: 6702 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6703 6704 case Intrinsic::amdgcn_class: 6705 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6706 Op.getOperand(1), Op.getOperand(2)); 6707 case Intrinsic::amdgcn_div_fmas: 6708 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6709 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6710 Op.getOperand(4)); 6711 6712 case Intrinsic::amdgcn_div_fixup: 6713 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6714 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6715 6716 case Intrinsic::amdgcn_div_scale: { 6717 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6718 6719 // Translate to the operands expected by the machine instruction. The 6720 // first parameter must be the same as the first instruction. 6721 SDValue Numerator = Op.getOperand(1); 6722 SDValue Denominator = Op.getOperand(2); 6723 6724 // Note this order is opposite of the machine instruction's operations, 6725 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6726 // intrinsic has the numerator as the first operand to match a normal 6727 // division operation. 6728 6729 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6730 6731 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6732 Denominator, Numerator); 6733 } 6734 case Intrinsic::amdgcn_icmp: { 6735 // There is a Pat that handles this variant, so return it as-is. 6736 if (Op.getOperand(1).getValueType() == MVT::i1 && 6737 Op.getConstantOperandVal(2) == 0 && 6738 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6739 return Op; 6740 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6741 } 6742 case Intrinsic::amdgcn_fcmp: { 6743 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6744 } 6745 case Intrinsic::amdgcn_ballot: 6746 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6747 case Intrinsic::amdgcn_fmed3: 6748 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6749 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6750 case Intrinsic::amdgcn_fdot2: 6751 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6752 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6753 Op.getOperand(4)); 6754 case Intrinsic::amdgcn_fmul_legacy: 6755 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6756 Op.getOperand(1), Op.getOperand(2)); 6757 case Intrinsic::amdgcn_sffbh: 6758 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6759 case Intrinsic::amdgcn_sbfe: 6760 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6761 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6762 case Intrinsic::amdgcn_ubfe: 6763 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6764 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6765 case Intrinsic::amdgcn_cvt_pkrtz: 6766 case Intrinsic::amdgcn_cvt_pknorm_i16: 6767 case Intrinsic::amdgcn_cvt_pknorm_u16: 6768 case Intrinsic::amdgcn_cvt_pk_i16: 6769 case Intrinsic::amdgcn_cvt_pk_u16: { 6770 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6771 EVT VT = Op.getValueType(); 6772 unsigned Opcode; 6773 6774 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6775 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6776 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6777 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6778 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6779 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6780 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6781 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6782 else 6783 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6784 6785 if (isTypeLegal(VT)) 6786 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6787 6788 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6789 Op.getOperand(1), Op.getOperand(2)); 6790 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6791 } 6792 case Intrinsic::amdgcn_fmad_ftz: 6793 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6794 Op.getOperand(2), Op.getOperand(3)); 6795 6796 case Intrinsic::amdgcn_if_break: 6797 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6798 Op->getOperand(1), Op->getOperand(2)), 0); 6799 6800 case Intrinsic::amdgcn_groupstaticsize: { 6801 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6802 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6803 return Op; 6804 6805 const Module *M = MF.getFunction().getParent(); 6806 const GlobalValue *GV = 6807 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6808 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6809 SIInstrInfo::MO_ABS32_LO); 6810 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6811 } 6812 case Intrinsic::amdgcn_is_shared: 6813 case Intrinsic::amdgcn_is_private: { 6814 SDLoc SL(Op); 6815 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6816 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6817 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6818 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6819 Op.getOperand(1)); 6820 6821 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6822 DAG.getConstant(1, SL, MVT::i32)); 6823 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6824 } 6825 case Intrinsic::amdgcn_alignbit: 6826 return DAG.getNode(ISD::FSHR, DL, VT, 6827 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6828 case Intrinsic::amdgcn_perm: 6829 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6830 Op.getOperand(2), Op.getOperand(3)); 6831 case Intrinsic::amdgcn_reloc_constant: { 6832 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6833 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6834 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6835 auto RelocSymbol = cast<GlobalVariable>( 6836 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6837 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6838 SIInstrInfo::MO_ABS32_LO); 6839 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6840 } 6841 default: 6842 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6843 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6844 return lowerImage(Op, ImageDimIntr, DAG, false); 6845 6846 return Op; 6847 } 6848 } 6849 6850 /// Update \p MMO based on the offset inputs to an intrinsic. 6851 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6852 SDValue SOffset, SDValue Offset, 6853 SDValue VIndex = SDValue()) { 6854 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6855 !isa<ConstantSDNode>(Offset)) { 6856 // The combined offset is not known to be constant, so we cannot represent 6857 // it in the MMO. Give up. 6858 MMO->setValue((Value *)nullptr); 6859 return; 6860 } 6861 6862 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6863 !cast<ConstantSDNode>(VIndex)->isZero())) { 6864 // The strided index component of the address is not known to be zero, so we 6865 // cannot represent it in the MMO. Give up. 6866 MMO->setValue((Value *)nullptr); 6867 return; 6868 } 6869 6870 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6871 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6872 cast<ConstantSDNode>(Offset)->getSExtValue()); 6873 } 6874 6875 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6876 SelectionDAG &DAG, 6877 unsigned NewOpcode) const { 6878 SDLoc DL(Op); 6879 6880 SDValue VData = Op.getOperand(2); 6881 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6882 SDValue Ops[] = { 6883 Op.getOperand(0), // Chain 6884 VData, // vdata 6885 Op.getOperand(3), // rsrc 6886 DAG.getConstant(0, DL, MVT::i32), // vindex 6887 Offsets.first, // voffset 6888 Op.getOperand(5), // soffset 6889 Offsets.second, // offset 6890 Op.getOperand(6), // cachepolicy 6891 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6892 }; 6893 6894 auto *M = cast<MemSDNode>(Op); 6895 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6896 6897 EVT MemVT = VData.getValueType(); 6898 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6899 M->getMemOperand()); 6900 } 6901 6902 // Return a value to use for the idxen operand by examining the vindex operand. 6903 static unsigned getIdxEn(SDValue VIndex) { 6904 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6905 // No need to set idxen if vindex is known to be zero. 6906 return VIndexC->getZExtValue() != 0; 6907 return 1; 6908 } 6909 6910 SDValue 6911 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6912 unsigned NewOpcode) const { 6913 SDLoc DL(Op); 6914 6915 SDValue VData = Op.getOperand(2); 6916 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6917 SDValue Ops[] = { 6918 Op.getOperand(0), // Chain 6919 VData, // vdata 6920 Op.getOperand(3), // rsrc 6921 Op.getOperand(4), // vindex 6922 Offsets.first, // voffset 6923 Op.getOperand(6), // soffset 6924 Offsets.second, // offset 6925 Op.getOperand(7), // cachepolicy 6926 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6927 }; 6928 6929 auto *M = cast<MemSDNode>(Op); 6930 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 6931 6932 EVT MemVT = VData.getValueType(); 6933 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6934 M->getMemOperand()); 6935 } 6936 6937 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6938 SelectionDAG &DAG) const { 6939 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6940 SDLoc DL(Op); 6941 6942 switch (IntrID) { 6943 case Intrinsic::amdgcn_ds_ordered_add: 6944 case Intrinsic::amdgcn_ds_ordered_swap: { 6945 MemSDNode *M = cast<MemSDNode>(Op); 6946 SDValue Chain = M->getOperand(0); 6947 SDValue M0 = M->getOperand(2); 6948 SDValue Value = M->getOperand(3); 6949 unsigned IndexOperand = M->getConstantOperandVal(7); 6950 unsigned WaveRelease = M->getConstantOperandVal(8); 6951 unsigned WaveDone = M->getConstantOperandVal(9); 6952 6953 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6954 IndexOperand &= ~0x3f; 6955 unsigned CountDw = 0; 6956 6957 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6958 CountDw = (IndexOperand >> 24) & 0xf; 6959 IndexOperand &= ~(0xf << 24); 6960 6961 if (CountDw < 1 || CountDw > 4) { 6962 report_fatal_error( 6963 "ds_ordered_count: dword count must be between 1 and 4"); 6964 } 6965 } 6966 6967 if (IndexOperand) 6968 report_fatal_error("ds_ordered_count: bad index operand"); 6969 6970 if (WaveDone && !WaveRelease) 6971 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6972 6973 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6974 unsigned ShaderType = 6975 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6976 unsigned Offset0 = OrderedCountIndex << 2; 6977 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6978 (Instruction << 4); 6979 6980 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6981 Offset1 |= (CountDw - 1) << 6; 6982 6983 unsigned Offset = Offset0 | (Offset1 << 8); 6984 6985 SDValue Ops[] = { 6986 Chain, 6987 Value, 6988 DAG.getTargetConstant(Offset, DL, MVT::i16), 6989 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6990 }; 6991 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6992 M->getVTList(), Ops, M->getMemoryVT(), 6993 M->getMemOperand()); 6994 } 6995 case Intrinsic::amdgcn_ds_fadd: { 6996 MemSDNode *M = cast<MemSDNode>(Op); 6997 unsigned Opc; 6998 switch (IntrID) { 6999 case Intrinsic::amdgcn_ds_fadd: 7000 Opc = ISD::ATOMIC_LOAD_FADD; 7001 break; 7002 } 7003 7004 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7005 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7006 M->getMemOperand()); 7007 } 7008 case Intrinsic::amdgcn_atomic_inc: 7009 case Intrinsic::amdgcn_atomic_dec: 7010 case Intrinsic::amdgcn_ds_fmin: 7011 case Intrinsic::amdgcn_ds_fmax: { 7012 MemSDNode *M = cast<MemSDNode>(Op); 7013 unsigned Opc; 7014 switch (IntrID) { 7015 case Intrinsic::amdgcn_atomic_inc: 7016 Opc = AMDGPUISD::ATOMIC_INC; 7017 break; 7018 case Intrinsic::amdgcn_atomic_dec: 7019 Opc = AMDGPUISD::ATOMIC_DEC; 7020 break; 7021 case Intrinsic::amdgcn_ds_fmin: 7022 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7023 break; 7024 case Intrinsic::amdgcn_ds_fmax: 7025 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7026 break; 7027 default: 7028 llvm_unreachable("Unknown intrinsic!"); 7029 } 7030 SDValue Ops[] = { 7031 M->getOperand(0), // Chain 7032 M->getOperand(2), // Ptr 7033 M->getOperand(3) // Value 7034 }; 7035 7036 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7037 M->getMemoryVT(), M->getMemOperand()); 7038 } 7039 case Intrinsic::amdgcn_buffer_load: 7040 case Intrinsic::amdgcn_buffer_load_format: { 7041 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7042 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7043 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7044 SDValue Ops[] = { 7045 Op.getOperand(0), // Chain 7046 Op.getOperand(2), // rsrc 7047 Op.getOperand(3), // vindex 7048 SDValue(), // voffset -- will be set by setBufferOffsets 7049 SDValue(), // soffset -- will be set by setBufferOffsets 7050 SDValue(), // offset -- will be set by setBufferOffsets 7051 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7052 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7053 }; 7054 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7055 7056 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7057 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7058 7059 EVT VT = Op.getValueType(); 7060 EVT IntVT = VT.changeTypeToInteger(); 7061 auto *M = cast<MemSDNode>(Op); 7062 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7063 EVT LoadVT = Op.getValueType(); 7064 7065 if (LoadVT.getScalarType() == MVT::f16) 7066 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7067 M, DAG, Ops); 7068 7069 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7070 if (LoadVT.getScalarType() == MVT::i8 || 7071 LoadVT.getScalarType() == MVT::i16) 7072 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7073 7074 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7075 M->getMemOperand(), DAG); 7076 } 7077 case Intrinsic::amdgcn_raw_buffer_load: 7078 case Intrinsic::amdgcn_raw_buffer_load_format: { 7079 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7080 7081 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7082 SDValue Ops[] = { 7083 Op.getOperand(0), // Chain 7084 Op.getOperand(2), // rsrc 7085 DAG.getConstant(0, DL, MVT::i32), // vindex 7086 Offsets.first, // voffset 7087 Op.getOperand(4), // soffset 7088 Offsets.second, // offset 7089 Op.getOperand(5), // cachepolicy, swizzled buffer 7090 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7091 }; 7092 7093 auto *M = cast<MemSDNode>(Op); 7094 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7095 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7096 } 7097 case Intrinsic::amdgcn_struct_buffer_load: 7098 case Intrinsic::amdgcn_struct_buffer_load_format: { 7099 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7100 7101 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7102 SDValue Ops[] = { 7103 Op.getOperand(0), // Chain 7104 Op.getOperand(2), // rsrc 7105 Op.getOperand(3), // vindex 7106 Offsets.first, // voffset 7107 Op.getOperand(5), // soffset 7108 Offsets.second, // offset 7109 Op.getOperand(6), // cachepolicy, swizzled buffer 7110 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7111 }; 7112 7113 auto *M = cast<MemSDNode>(Op); 7114 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7115 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7116 } 7117 case Intrinsic::amdgcn_tbuffer_load: { 7118 MemSDNode *M = cast<MemSDNode>(Op); 7119 EVT LoadVT = Op.getValueType(); 7120 7121 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7122 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7123 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7124 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7125 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7126 SDValue Ops[] = { 7127 Op.getOperand(0), // Chain 7128 Op.getOperand(2), // rsrc 7129 Op.getOperand(3), // vindex 7130 Op.getOperand(4), // voffset 7131 Op.getOperand(5), // soffset 7132 Op.getOperand(6), // offset 7133 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7134 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7135 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7136 }; 7137 7138 if (LoadVT.getScalarType() == MVT::f16) 7139 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7140 M, DAG, Ops); 7141 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7142 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7143 DAG); 7144 } 7145 case Intrinsic::amdgcn_raw_tbuffer_load: { 7146 MemSDNode *M = cast<MemSDNode>(Op); 7147 EVT LoadVT = Op.getValueType(); 7148 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7149 7150 SDValue Ops[] = { 7151 Op.getOperand(0), // Chain 7152 Op.getOperand(2), // rsrc 7153 DAG.getConstant(0, DL, MVT::i32), // vindex 7154 Offsets.first, // voffset 7155 Op.getOperand(4), // soffset 7156 Offsets.second, // offset 7157 Op.getOperand(5), // format 7158 Op.getOperand(6), // cachepolicy, swizzled buffer 7159 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7160 }; 7161 7162 if (LoadVT.getScalarType() == MVT::f16) 7163 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7164 M, DAG, Ops); 7165 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7166 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7167 DAG); 7168 } 7169 case Intrinsic::amdgcn_struct_tbuffer_load: { 7170 MemSDNode *M = cast<MemSDNode>(Op); 7171 EVT LoadVT = Op.getValueType(); 7172 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7173 7174 SDValue Ops[] = { 7175 Op.getOperand(0), // Chain 7176 Op.getOperand(2), // rsrc 7177 Op.getOperand(3), // vindex 7178 Offsets.first, // voffset 7179 Op.getOperand(5), // soffset 7180 Offsets.second, // offset 7181 Op.getOperand(6), // format 7182 Op.getOperand(7), // cachepolicy, swizzled buffer 7183 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7184 }; 7185 7186 if (LoadVT.getScalarType() == MVT::f16) 7187 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7188 M, DAG, Ops); 7189 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7190 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7191 DAG); 7192 } 7193 case Intrinsic::amdgcn_buffer_atomic_swap: 7194 case Intrinsic::amdgcn_buffer_atomic_add: 7195 case Intrinsic::amdgcn_buffer_atomic_sub: 7196 case Intrinsic::amdgcn_buffer_atomic_csub: 7197 case Intrinsic::amdgcn_buffer_atomic_smin: 7198 case Intrinsic::amdgcn_buffer_atomic_umin: 7199 case Intrinsic::amdgcn_buffer_atomic_smax: 7200 case Intrinsic::amdgcn_buffer_atomic_umax: 7201 case Intrinsic::amdgcn_buffer_atomic_and: 7202 case Intrinsic::amdgcn_buffer_atomic_or: 7203 case Intrinsic::amdgcn_buffer_atomic_xor: 7204 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7205 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7206 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7207 SDValue Ops[] = { 7208 Op.getOperand(0), // Chain 7209 Op.getOperand(2), // vdata 7210 Op.getOperand(3), // rsrc 7211 Op.getOperand(4), // vindex 7212 SDValue(), // voffset -- will be set by setBufferOffsets 7213 SDValue(), // soffset -- will be set by setBufferOffsets 7214 SDValue(), // offset -- will be set by setBufferOffsets 7215 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7216 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7217 }; 7218 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7219 7220 EVT VT = Op.getValueType(); 7221 7222 auto *M = cast<MemSDNode>(Op); 7223 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7224 unsigned Opcode = 0; 7225 7226 switch (IntrID) { 7227 case Intrinsic::amdgcn_buffer_atomic_swap: 7228 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7229 break; 7230 case Intrinsic::amdgcn_buffer_atomic_add: 7231 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7232 break; 7233 case Intrinsic::amdgcn_buffer_atomic_sub: 7234 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7235 break; 7236 case Intrinsic::amdgcn_buffer_atomic_csub: 7237 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7238 break; 7239 case Intrinsic::amdgcn_buffer_atomic_smin: 7240 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7241 break; 7242 case Intrinsic::amdgcn_buffer_atomic_umin: 7243 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7244 break; 7245 case Intrinsic::amdgcn_buffer_atomic_smax: 7246 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7247 break; 7248 case Intrinsic::amdgcn_buffer_atomic_umax: 7249 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7250 break; 7251 case Intrinsic::amdgcn_buffer_atomic_and: 7252 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7253 break; 7254 case Intrinsic::amdgcn_buffer_atomic_or: 7255 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7256 break; 7257 case Intrinsic::amdgcn_buffer_atomic_xor: 7258 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7259 break; 7260 case Intrinsic::amdgcn_buffer_atomic_fadd: 7261 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7262 DiagnosticInfoUnsupported 7263 NoFpRet(DAG.getMachineFunction().getFunction(), 7264 "return versions of fp atomics not supported", 7265 DL.getDebugLoc(), DS_Error); 7266 DAG.getContext()->diagnose(NoFpRet); 7267 return SDValue(); 7268 } 7269 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7270 break; 7271 default: 7272 llvm_unreachable("unhandled atomic opcode"); 7273 } 7274 7275 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7276 M->getMemOperand()); 7277 } 7278 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7279 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7280 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7281 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7282 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7283 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7284 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7285 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7286 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7287 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7288 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7289 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7290 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7291 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7292 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7293 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7294 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7295 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7296 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7297 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7298 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7299 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7300 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7301 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7302 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7303 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7304 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7305 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7306 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7307 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7308 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7309 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7310 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7311 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7312 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7313 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7314 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7315 return lowerStructBufferAtomicIntrin(Op, DAG, 7316 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7317 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7318 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7319 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7320 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7321 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7322 return lowerStructBufferAtomicIntrin(Op, DAG, 7323 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7324 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7325 return lowerStructBufferAtomicIntrin(Op, DAG, 7326 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7327 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7328 return lowerStructBufferAtomicIntrin(Op, DAG, 7329 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7330 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7331 return lowerStructBufferAtomicIntrin(Op, DAG, 7332 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7333 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7334 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7335 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7336 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7337 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7338 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7339 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7340 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7341 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7342 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7343 7344 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7345 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7346 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7347 SDValue Ops[] = { 7348 Op.getOperand(0), // Chain 7349 Op.getOperand(2), // src 7350 Op.getOperand(3), // cmp 7351 Op.getOperand(4), // rsrc 7352 Op.getOperand(5), // vindex 7353 SDValue(), // voffset -- will be set by setBufferOffsets 7354 SDValue(), // soffset -- will be set by setBufferOffsets 7355 SDValue(), // offset -- will be set by setBufferOffsets 7356 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7357 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7358 }; 7359 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7360 7361 EVT VT = Op.getValueType(); 7362 auto *M = cast<MemSDNode>(Op); 7363 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7364 7365 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7366 Op->getVTList(), Ops, VT, M->getMemOperand()); 7367 } 7368 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7369 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7370 SDValue Ops[] = { 7371 Op.getOperand(0), // Chain 7372 Op.getOperand(2), // src 7373 Op.getOperand(3), // cmp 7374 Op.getOperand(4), // rsrc 7375 DAG.getConstant(0, DL, MVT::i32), // vindex 7376 Offsets.first, // voffset 7377 Op.getOperand(6), // soffset 7378 Offsets.second, // offset 7379 Op.getOperand(7), // cachepolicy 7380 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7381 }; 7382 EVT VT = Op.getValueType(); 7383 auto *M = cast<MemSDNode>(Op); 7384 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7385 7386 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7387 Op->getVTList(), Ops, VT, M->getMemOperand()); 7388 } 7389 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7390 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7391 SDValue Ops[] = { 7392 Op.getOperand(0), // Chain 7393 Op.getOperand(2), // src 7394 Op.getOperand(3), // cmp 7395 Op.getOperand(4), // rsrc 7396 Op.getOperand(5), // vindex 7397 Offsets.first, // voffset 7398 Op.getOperand(7), // soffset 7399 Offsets.second, // offset 7400 Op.getOperand(8), // cachepolicy 7401 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7402 }; 7403 EVT VT = Op.getValueType(); 7404 auto *M = cast<MemSDNode>(Op); 7405 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7406 7407 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7408 Op->getVTList(), Ops, VT, M->getMemOperand()); 7409 } 7410 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7411 MemSDNode *M = cast<MemSDNode>(Op); 7412 SDValue NodePtr = M->getOperand(2); 7413 SDValue RayExtent = M->getOperand(3); 7414 SDValue RayOrigin = M->getOperand(4); 7415 SDValue RayDir = M->getOperand(5); 7416 SDValue RayInvDir = M->getOperand(6); 7417 SDValue TDescr = M->getOperand(7); 7418 7419 assert(NodePtr.getValueType() == MVT::i32 || 7420 NodePtr.getValueType() == MVT::i64); 7421 assert(RayDir.getValueType() == MVT::v4f16 || 7422 RayDir.getValueType() == MVT::v4f32); 7423 7424 if (!Subtarget->hasGFX10_AEncoding()) { 7425 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7426 return SDValue(); 7427 } 7428 7429 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7430 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7431 const unsigned NumVDataDwords = 4; 7432 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7433 const bool UseNSA = Subtarget->hasNSAEncoding() && 7434 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7435 const unsigned BaseOpcodes[2][2] = { 7436 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7437 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7438 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7439 int Opcode; 7440 if (UseNSA) { 7441 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7442 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7443 NumVAddrDwords); 7444 } else { 7445 Opcode = AMDGPU::getMIMGOpcode( 7446 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7447 PowerOf2Ceil(NumVAddrDwords)); 7448 } 7449 assert(Opcode != -1); 7450 7451 SmallVector<SDValue, 16> Ops; 7452 7453 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7454 SmallVector<SDValue, 3> Lanes; 7455 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7456 if (Lanes[0].getValueSizeInBits() == 32) { 7457 for (unsigned I = 0; I < 3; ++I) 7458 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7459 } else { 7460 if (IsAligned) { 7461 Ops.push_back( 7462 DAG.getBitcast(MVT::i32, 7463 DAG.getBuildVector(MVT::v2f16, DL, 7464 { Lanes[0], Lanes[1] }))); 7465 Ops.push_back(Lanes[2]); 7466 } else { 7467 SDValue Elt0 = Ops.pop_back_val(); 7468 Ops.push_back( 7469 DAG.getBitcast(MVT::i32, 7470 DAG.getBuildVector(MVT::v2f16, DL, 7471 { Elt0, Lanes[0] }))); 7472 Ops.push_back( 7473 DAG.getBitcast(MVT::i32, 7474 DAG.getBuildVector(MVT::v2f16, DL, 7475 { Lanes[1], Lanes[2] }))); 7476 } 7477 } 7478 }; 7479 7480 if (Is64) 7481 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7482 else 7483 Ops.push_back(NodePtr); 7484 7485 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7486 packLanes(RayOrigin, true); 7487 packLanes(RayDir, true); 7488 packLanes(RayInvDir, false); 7489 7490 if (!UseNSA) { 7491 // Build a single vector containing all the operands so far prepared. 7492 if (NumVAddrDwords > 8) { 7493 SDValue Undef = DAG.getUNDEF(MVT::i32); 7494 Ops.append(16 - Ops.size(), Undef); 7495 } 7496 assert(Ops.size() == 8 || Ops.size() == 16); 7497 SDValue MergedOps = DAG.getBuildVector( 7498 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7499 Ops.clear(); 7500 Ops.push_back(MergedOps); 7501 } 7502 7503 Ops.push_back(TDescr); 7504 if (IsA16) 7505 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7506 Ops.push_back(M->getChain()); 7507 7508 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7509 MachineMemOperand *MemRef = M->getMemOperand(); 7510 DAG.setNodeMemRefs(NewNode, {MemRef}); 7511 return SDValue(NewNode, 0); 7512 } 7513 case Intrinsic::amdgcn_global_atomic_fadd: 7514 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7515 DiagnosticInfoUnsupported 7516 NoFpRet(DAG.getMachineFunction().getFunction(), 7517 "return versions of fp atomics not supported", 7518 DL.getDebugLoc(), DS_Error); 7519 DAG.getContext()->diagnose(NoFpRet); 7520 return SDValue(); 7521 } 7522 LLVM_FALLTHROUGH; 7523 case Intrinsic::amdgcn_global_atomic_fmin: 7524 case Intrinsic::amdgcn_global_atomic_fmax: 7525 case Intrinsic::amdgcn_flat_atomic_fadd: 7526 case Intrinsic::amdgcn_flat_atomic_fmin: 7527 case Intrinsic::amdgcn_flat_atomic_fmax: { 7528 MemSDNode *M = cast<MemSDNode>(Op); 7529 SDValue Ops[] = { 7530 M->getOperand(0), // Chain 7531 M->getOperand(2), // Ptr 7532 M->getOperand(3) // Value 7533 }; 7534 unsigned Opcode = 0; 7535 switch (IntrID) { 7536 case Intrinsic::amdgcn_global_atomic_fadd: 7537 case Intrinsic::amdgcn_flat_atomic_fadd: { 7538 EVT VT = Op.getOperand(3).getValueType(); 7539 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7540 DAG.getVTList(VT, MVT::Other), Ops, 7541 M->getMemOperand()); 7542 } 7543 case Intrinsic::amdgcn_global_atomic_fmin: 7544 case Intrinsic::amdgcn_flat_atomic_fmin: { 7545 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7546 break; 7547 } 7548 case Intrinsic::amdgcn_global_atomic_fmax: 7549 case Intrinsic::amdgcn_flat_atomic_fmax: { 7550 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7551 break; 7552 } 7553 default: 7554 llvm_unreachable("unhandled atomic opcode"); 7555 } 7556 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7557 M->getVTList(), Ops, M->getMemoryVT(), 7558 M->getMemOperand()); 7559 } 7560 default: 7561 7562 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7563 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7564 return lowerImage(Op, ImageDimIntr, DAG, true); 7565 7566 return SDValue(); 7567 } 7568 } 7569 7570 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7571 // dwordx4 if on SI. 7572 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7573 SDVTList VTList, 7574 ArrayRef<SDValue> Ops, EVT MemVT, 7575 MachineMemOperand *MMO, 7576 SelectionDAG &DAG) const { 7577 EVT VT = VTList.VTs[0]; 7578 EVT WidenedVT = VT; 7579 EVT WidenedMemVT = MemVT; 7580 if (!Subtarget->hasDwordx3LoadStores() && 7581 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7582 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7583 WidenedVT.getVectorElementType(), 4); 7584 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7585 WidenedMemVT.getVectorElementType(), 4); 7586 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7587 } 7588 7589 assert(VTList.NumVTs == 2); 7590 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7591 7592 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7593 WidenedMemVT, MMO); 7594 if (WidenedVT != VT) { 7595 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7596 DAG.getVectorIdxConstant(0, DL)); 7597 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7598 } 7599 return NewOp; 7600 } 7601 7602 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7603 bool ImageStore) const { 7604 EVT StoreVT = VData.getValueType(); 7605 7606 // No change for f16 and legal vector D16 types. 7607 if (!StoreVT.isVector()) 7608 return VData; 7609 7610 SDLoc DL(VData); 7611 unsigned NumElements = StoreVT.getVectorNumElements(); 7612 7613 if (Subtarget->hasUnpackedD16VMem()) { 7614 // We need to unpack the packed data to store. 7615 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7616 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7617 7618 EVT EquivStoreVT = 7619 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7621 return DAG.UnrollVectorOp(ZExt.getNode()); 7622 } 7623 7624 // The sq block of gfx8.1 does not estimate register use correctly for d16 7625 // image store instructions. The data operand is computed as if it were not a 7626 // d16 image instruction. 7627 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7628 // Bitcast to i16 7629 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7630 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7631 7632 // Decompose into scalars 7633 SmallVector<SDValue, 4> Elts; 7634 DAG.ExtractVectorElements(IntVData, Elts); 7635 7636 // Group pairs of i16 into v2i16 and bitcast to i32 7637 SmallVector<SDValue, 4> PackedElts; 7638 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7639 SDValue Pair = 7640 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7641 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7642 PackedElts.push_back(IntPair); 7643 } 7644 if ((NumElements % 2) == 1) { 7645 // Handle v3i16 7646 unsigned I = Elts.size() / 2; 7647 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7648 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7649 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7650 PackedElts.push_back(IntPair); 7651 } 7652 7653 // Pad using UNDEF 7654 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7655 7656 // Build final vector 7657 EVT VecVT = 7658 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7659 return DAG.getBuildVector(VecVT, DL, PackedElts); 7660 } 7661 7662 if (NumElements == 3) { 7663 EVT IntStoreVT = 7664 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7665 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7666 7667 EVT WidenedStoreVT = EVT::getVectorVT( 7668 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7669 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7670 WidenedStoreVT.getStoreSizeInBits()); 7671 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7672 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7673 } 7674 7675 assert(isTypeLegal(StoreVT)); 7676 return VData; 7677 } 7678 7679 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7680 SelectionDAG &DAG) const { 7681 SDLoc DL(Op); 7682 SDValue Chain = Op.getOperand(0); 7683 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7684 MachineFunction &MF = DAG.getMachineFunction(); 7685 7686 switch (IntrinsicID) { 7687 case Intrinsic::amdgcn_exp_compr: { 7688 SDValue Src0 = Op.getOperand(4); 7689 SDValue Src1 = Op.getOperand(5); 7690 // Hack around illegal type on SI by directly selecting it. 7691 if (isTypeLegal(Src0.getValueType())) 7692 return SDValue(); 7693 7694 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7695 SDValue Undef = DAG.getUNDEF(MVT::f32); 7696 const SDValue Ops[] = { 7697 Op.getOperand(2), // tgt 7698 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7699 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7700 Undef, // src2 7701 Undef, // src3 7702 Op.getOperand(7), // vm 7703 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7704 Op.getOperand(3), // en 7705 Op.getOperand(0) // Chain 7706 }; 7707 7708 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7709 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7710 } 7711 case Intrinsic::amdgcn_s_barrier: { 7712 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7713 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7714 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7715 if (WGSize <= ST.getWavefrontSize()) 7716 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7717 Op.getOperand(0)), 0); 7718 } 7719 return SDValue(); 7720 }; 7721 case Intrinsic::amdgcn_tbuffer_store: { 7722 SDValue VData = Op.getOperand(2); 7723 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7724 if (IsD16) 7725 VData = handleD16VData(VData, DAG); 7726 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7727 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7728 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7729 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7730 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7731 SDValue Ops[] = { 7732 Chain, 7733 VData, // vdata 7734 Op.getOperand(3), // rsrc 7735 Op.getOperand(4), // vindex 7736 Op.getOperand(5), // voffset 7737 Op.getOperand(6), // soffset 7738 Op.getOperand(7), // offset 7739 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7740 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7741 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7742 }; 7743 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7744 AMDGPUISD::TBUFFER_STORE_FORMAT; 7745 MemSDNode *M = cast<MemSDNode>(Op); 7746 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7747 M->getMemoryVT(), M->getMemOperand()); 7748 } 7749 7750 case Intrinsic::amdgcn_struct_tbuffer_store: { 7751 SDValue VData = Op.getOperand(2); 7752 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7753 if (IsD16) 7754 VData = handleD16VData(VData, DAG); 7755 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7756 SDValue Ops[] = { 7757 Chain, 7758 VData, // vdata 7759 Op.getOperand(3), // rsrc 7760 Op.getOperand(4), // vindex 7761 Offsets.first, // voffset 7762 Op.getOperand(6), // soffset 7763 Offsets.second, // offset 7764 Op.getOperand(7), // format 7765 Op.getOperand(8), // cachepolicy, swizzled buffer 7766 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7767 }; 7768 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7769 AMDGPUISD::TBUFFER_STORE_FORMAT; 7770 MemSDNode *M = cast<MemSDNode>(Op); 7771 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7772 M->getMemoryVT(), M->getMemOperand()); 7773 } 7774 7775 case Intrinsic::amdgcn_raw_tbuffer_store: { 7776 SDValue VData = Op.getOperand(2); 7777 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7778 if (IsD16) 7779 VData = handleD16VData(VData, DAG); 7780 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7781 SDValue Ops[] = { 7782 Chain, 7783 VData, // vdata 7784 Op.getOperand(3), // rsrc 7785 DAG.getConstant(0, DL, MVT::i32), // vindex 7786 Offsets.first, // voffset 7787 Op.getOperand(5), // soffset 7788 Offsets.second, // offset 7789 Op.getOperand(6), // format 7790 Op.getOperand(7), // cachepolicy, swizzled buffer 7791 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7792 }; 7793 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7794 AMDGPUISD::TBUFFER_STORE_FORMAT; 7795 MemSDNode *M = cast<MemSDNode>(Op); 7796 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7797 M->getMemoryVT(), M->getMemOperand()); 7798 } 7799 7800 case Intrinsic::amdgcn_buffer_store: 7801 case Intrinsic::amdgcn_buffer_store_format: { 7802 SDValue VData = Op.getOperand(2); 7803 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7804 if (IsD16) 7805 VData = handleD16VData(VData, DAG); 7806 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7807 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7808 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7809 SDValue Ops[] = { 7810 Chain, 7811 VData, 7812 Op.getOperand(3), // rsrc 7813 Op.getOperand(4), // vindex 7814 SDValue(), // voffset -- will be set by setBufferOffsets 7815 SDValue(), // soffset -- will be set by setBufferOffsets 7816 SDValue(), // offset -- will be set by setBufferOffsets 7817 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7818 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7819 }; 7820 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7821 7822 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7823 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7824 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7825 MemSDNode *M = cast<MemSDNode>(Op); 7826 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7827 7828 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7829 EVT VDataType = VData.getValueType().getScalarType(); 7830 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7831 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7832 7833 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7834 M->getMemoryVT(), M->getMemOperand()); 7835 } 7836 7837 case Intrinsic::amdgcn_raw_buffer_store: 7838 case Intrinsic::amdgcn_raw_buffer_store_format: { 7839 const bool IsFormat = 7840 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7841 7842 SDValue VData = Op.getOperand(2); 7843 EVT VDataVT = VData.getValueType(); 7844 EVT EltType = VDataVT.getScalarType(); 7845 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7846 if (IsD16) { 7847 VData = handleD16VData(VData, DAG); 7848 VDataVT = VData.getValueType(); 7849 } 7850 7851 if (!isTypeLegal(VDataVT)) { 7852 VData = 7853 DAG.getNode(ISD::BITCAST, DL, 7854 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7855 } 7856 7857 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7858 SDValue Ops[] = { 7859 Chain, 7860 VData, 7861 Op.getOperand(3), // rsrc 7862 DAG.getConstant(0, DL, MVT::i32), // vindex 7863 Offsets.first, // voffset 7864 Op.getOperand(5), // soffset 7865 Offsets.second, // offset 7866 Op.getOperand(6), // cachepolicy, swizzled buffer 7867 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7868 }; 7869 unsigned Opc = 7870 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7871 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7872 MemSDNode *M = cast<MemSDNode>(Op); 7873 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7874 7875 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7876 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7877 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7878 7879 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7880 M->getMemoryVT(), M->getMemOperand()); 7881 } 7882 7883 case Intrinsic::amdgcn_struct_buffer_store: 7884 case Intrinsic::amdgcn_struct_buffer_store_format: { 7885 const bool IsFormat = 7886 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7887 7888 SDValue VData = Op.getOperand(2); 7889 EVT VDataVT = VData.getValueType(); 7890 EVT EltType = VDataVT.getScalarType(); 7891 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7892 7893 if (IsD16) { 7894 VData = handleD16VData(VData, DAG); 7895 VDataVT = VData.getValueType(); 7896 } 7897 7898 if (!isTypeLegal(VDataVT)) { 7899 VData = 7900 DAG.getNode(ISD::BITCAST, DL, 7901 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7902 } 7903 7904 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7905 SDValue Ops[] = { 7906 Chain, 7907 VData, 7908 Op.getOperand(3), // rsrc 7909 Op.getOperand(4), // vindex 7910 Offsets.first, // voffset 7911 Op.getOperand(6), // soffset 7912 Offsets.second, // offset 7913 Op.getOperand(7), // cachepolicy, swizzled buffer 7914 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7915 }; 7916 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7917 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7918 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7919 MemSDNode *M = cast<MemSDNode>(Op); 7920 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7921 7922 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7923 EVT VDataType = VData.getValueType().getScalarType(); 7924 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7925 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7926 7927 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7928 M->getMemoryVT(), M->getMemOperand()); 7929 } 7930 case Intrinsic::amdgcn_end_cf: 7931 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7932 Op->getOperand(2), Chain), 0); 7933 7934 default: { 7935 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7936 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7937 return lowerImage(Op, ImageDimIntr, DAG, true); 7938 7939 return Op; 7940 } 7941 } 7942 } 7943 7944 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7945 // offset (the offset that is included in bounds checking and swizzling, to be 7946 // split between the instruction's voffset and immoffset fields) and soffset 7947 // (the offset that is excluded from bounds checking and swizzling, to go in 7948 // the instruction's soffset field). This function takes the first kind of 7949 // offset and figures out how to split it between voffset and immoffset. 7950 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7951 SDValue Offset, SelectionDAG &DAG) const { 7952 SDLoc DL(Offset); 7953 const unsigned MaxImm = 4095; 7954 SDValue N0 = Offset; 7955 ConstantSDNode *C1 = nullptr; 7956 7957 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7958 N0 = SDValue(); 7959 else if (DAG.isBaseWithConstantOffset(N0)) { 7960 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7961 N0 = N0.getOperand(0); 7962 } 7963 7964 if (C1) { 7965 unsigned ImmOffset = C1->getZExtValue(); 7966 // If the immediate value is too big for the immoffset field, put the value 7967 // and -4096 into the immoffset field so that the value that is copied/added 7968 // for the voffset field is a multiple of 4096, and it stands more chance 7969 // of being CSEd with the copy/add for another similar load/store. 7970 // However, do not do that rounding down to a multiple of 4096 if that is a 7971 // negative number, as it appears to be illegal to have a negative offset 7972 // in the vgpr, even if adding the immediate offset makes it positive. 7973 unsigned Overflow = ImmOffset & ~MaxImm; 7974 ImmOffset -= Overflow; 7975 if ((int32_t)Overflow < 0) { 7976 Overflow += ImmOffset; 7977 ImmOffset = 0; 7978 } 7979 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7980 if (Overflow) { 7981 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7982 if (!N0) 7983 N0 = OverflowVal; 7984 else { 7985 SDValue Ops[] = { N0, OverflowVal }; 7986 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7987 } 7988 } 7989 } 7990 if (!N0) 7991 N0 = DAG.getConstant(0, DL, MVT::i32); 7992 if (!C1) 7993 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7994 return {N0, SDValue(C1, 0)}; 7995 } 7996 7997 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7998 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7999 // pointed to by Offsets. 8000 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8001 SelectionDAG &DAG, SDValue *Offsets, 8002 Align Alignment) const { 8003 SDLoc DL(CombinedOffset); 8004 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8005 uint32_t Imm = C->getZExtValue(); 8006 uint32_t SOffset, ImmOffset; 8007 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8008 Alignment)) { 8009 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8010 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8011 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8012 return; 8013 } 8014 } 8015 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8016 SDValue N0 = CombinedOffset.getOperand(0); 8017 SDValue N1 = CombinedOffset.getOperand(1); 8018 uint32_t SOffset, ImmOffset; 8019 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8020 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8021 Subtarget, Alignment)) { 8022 Offsets[0] = N0; 8023 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8024 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8025 return; 8026 } 8027 } 8028 Offsets[0] = CombinedOffset; 8029 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8030 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8031 } 8032 8033 // Handle 8 bit and 16 bit buffer loads 8034 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8035 EVT LoadVT, SDLoc DL, 8036 ArrayRef<SDValue> Ops, 8037 MemSDNode *M) const { 8038 EVT IntVT = LoadVT.changeTypeToInteger(); 8039 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8040 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8041 8042 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8043 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8044 Ops, IntVT, 8045 M->getMemOperand()); 8046 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8047 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8048 8049 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8050 } 8051 8052 // Handle 8 bit and 16 bit buffer stores 8053 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8054 EVT VDataType, SDLoc DL, 8055 SDValue Ops[], 8056 MemSDNode *M) const { 8057 if (VDataType == MVT::f16) 8058 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8059 8060 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8061 Ops[1] = BufferStoreExt; 8062 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8063 AMDGPUISD::BUFFER_STORE_SHORT; 8064 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8065 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8066 M->getMemOperand()); 8067 } 8068 8069 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8070 ISD::LoadExtType ExtType, SDValue Op, 8071 const SDLoc &SL, EVT VT) { 8072 if (VT.bitsLT(Op.getValueType())) 8073 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8074 8075 switch (ExtType) { 8076 case ISD::SEXTLOAD: 8077 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8078 case ISD::ZEXTLOAD: 8079 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8080 case ISD::EXTLOAD: 8081 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8082 case ISD::NON_EXTLOAD: 8083 return Op; 8084 } 8085 8086 llvm_unreachable("invalid ext type"); 8087 } 8088 8089 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8090 SelectionDAG &DAG = DCI.DAG; 8091 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8092 return SDValue(); 8093 8094 // FIXME: Constant loads should all be marked invariant. 8095 unsigned AS = Ld->getAddressSpace(); 8096 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8097 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8098 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8099 return SDValue(); 8100 8101 // Don't do this early, since it may interfere with adjacent load merging for 8102 // illegal types. We can avoid losing alignment information for exotic types 8103 // pre-legalize. 8104 EVT MemVT = Ld->getMemoryVT(); 8105 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8106 MemVT.getSizeInBits() >= 32) 8107 return SDValue(); 8108 8109 SDLoc SL(Ld); 8110 8111 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8112 "unexpected vector extload"); 8113 8114 // TODO: Drop only high part of range. 8115 SDValue Ptr = Ld->getBasePtr(); 8116 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8117 MVT::i32, SL, Ld->getChain(), Ptr, 8118 Ld->getOffset(), 8119 Ld->getPointerInfo(), MVT::i32, 8120 Ld->getAlignment(), 8121 Ld->getMemOperand()->getFlags(), 8122 Ld->getAAInfo(), 8123 nullptr); // Drop ranges 8124 8125 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8126 if (MemVT.isFloatingPoint()) { 8127 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8128 "unexpected fp extload"); 8129 TruncVT = MemVT.changeTypeToInteger(); 8130 } 8131 8132 SDValue Cvt = NewLoad; 8133 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8134 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8135 DAG.getValueType(TruncVT)); 8136 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8137 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8138 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8139 } else { 8140 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8141 } 8142 8143 EVT VT = Ld->getValueType(0); 8144 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8145 8146 DCI.AddToWorklist(Cvt.getNode()); 8147 8148 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8149 // the appropriate extension from the 32-bit load. 8150 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8151 DCI.AddToWorklist(Cvt.getNode()); 8152 8153 // Handle conversion back to floating point if necessary. 8154 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8155 8156 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8157 } 8158 8159 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8160 SDLoc DL(Op); 8161 LoadSDNode *Load = cast<LoadSDNode>(Op); 8162 ISD::LoadExtType ExtType = Load->getExtensionType(); 8163 EVT MemVT = Load->getMemoryVT(); 8164 8165 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8166 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8167 return SDValue(); 8168 8169 // FIXME: Copied from PPC 8170 // First, load into 32 bits, then truncate to 1 bit. 8171 8172 SDValue Chain = Load->getChain(); 8173 SDValue BasePtr = Load->getBasePtr(); 8174 MachineMemOperand *MMO = Load->getMemOperand(); 8175 8176 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8177 8178 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8179 BasePtr, RealMemVT, MMO); 8180 8181 if (!MemVT.isVector()) { 8182 SDValue Ops[] = { 8183 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8184 NewLD.getValue(1) 8185 }; 8186 8187 return DAG.getMergeValues(Ops, DL); 8188 } 8189 8190 SmallVector<SDValue, 3> Elts; 8191 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8192 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8193 DAG.getConstant(I, DL, MVT::i32)); 8194 8195 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8196 } 8197 8198 SDValue Ops[] = { 8199 DAG.getBuildVector(MemVT, DL, Elts), 8200 NewLD.getValue(1) 8201 }; 8202 8203 return DAG.getMergeValues(Ops, DL); 8204 } 8205 8206 if (!MemVT.isVector()) 8207 return SDValue(); 8208 8209 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8210 "Custom lowering for non-i32 vectors hasn't been implemented."); 8211 8212 unsigned Alignment = Load->getAlignment(); 8213 unsigned AS = Load->getAddressSpace(); 8214 if (Subtarget->hasLDSMisalignedBug() && 8215 AS == AMDGPUAS::FLAT_ADDRESS && 8216 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8217 return SplitVectorLoad(Op, DAG); 8218 } 8219 8220 MachineFunction &MF = DAG.getMachineFunction(); 8221 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8222 // If there is a possibilty that flat instruction access scratch memory 8223 // then we need to use the same legalization rules we use for private. 8224 if (AS == AMDGPUAS::FLAT_ADDRESS && 8225 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8226 AS = MFI->hasFlatScratchInit() ? 8227 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8228 8229 unsigned NumElements = MemVT.getVectorNumElements(); 8230 8231 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8232 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8233 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8234 if (MemVT.isPow2VectorType()) 8235 return SDValue(); 8236 return WidenOrSplitVectorLoad(Op, DAG); 8237 } 8238 // Non-uniform loads will be selected to MUBUF instructions, so they 8239 // have the same legalization requirements as global and private 8240 // loads. 8241 // 8242 } 8243 8244 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8245 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8246 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8247 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8248 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8249 Alignment >= 4 && NumElements < 32) { 8250 if (MemVT.isPow2VectorType()) 8251 return SDValue(); 8252 return WidenOrSplitVectorLoad(Op, DAG); 8253 } 8254 // Non-uniform loads will be selected to MUBUF instructions, so they 8255 // have the same legalization requirements as global and private 8256 // loads. 8257 // 8258 } 8259 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8260 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8261 AS == AMDGPUAS::GLOBAL_ADDRESS || 8262 AS == AMDGPUAS::FLAT_ADDRESS) { 8263 if (NumElements > 4) 8264 return SplitVectorLoad(Op, DAG); 8265 // v3 loads not supported on SI. 8266 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8267 return WidenOrSplitVectorLoad(Op, DAG); 8268 8269 // v3 and v4 loads are supported for private and global memory. 8270 return SDValue(); 8271 } 8272 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8273 // Depending on the setting of the private_element_size field in the 8274 // resource descriptor, we can only make private accesses up to a certain 8275 // size. 8276 switch (Subtarget->getMaxPrivateElementSize()) { 8277 case 4: { 8278 SDValue Ops[2]; 8279 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8280 return DAG.getMergeValues(Ops, DL); 8281 } 8282 case 8: 8283 if (NumElements > 2) 8284 return SplitVectorLoad(Op, DAG); 8285 return SDValue(); 8286 case 16: 8287 // Same as global/flat 8288 if (NumElements > 4) 8289 return SplitVectorLoad(Op, DAG); 8290 // v3 loads not supported on SI. 8291 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8292 return WidenOrSplitVectorLoad(Op, DAG); 8293 8294 return SDValue(); 8295 default: 8296 llvm_unreachable("unsupported private_element_size"); 8297 } 8298 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8299 // Use ds_read_b128 or ds_read_b96 when possible. 8300 if (Subtarget->hasDS96AndDS128() && 8301 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8302 MemVT.getStoreSize() == 12) && 8303 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8304 Load->getAlign())) 8305 return SDValue(); 8306 8307 if (NumElements > 2) 8308 return SplitVectorLoad(Op, DAG); 8309 8310 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8311 // address is negative, then the instruction is incorrectly treated as 8312 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8313 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8314 // load later in the SILoadStoreOptimizer. 8315 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8316 NumElements == 2 && MemVT.getStoreSize() == 8 && 8317 Load->getAlignment() < 8) { 8318 return SplitVectorLoad(Op, DAG); 8319 } 8320 } 8321 8322 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8323 MemVT, *Load->getMemOperand())) { 8324 SDValue Ops[2]; 8325 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8326 return DAG.getMergeValues(Ops, DL); 8327 } 8328 8329 return SDValue(); 8330 } 8331 8332 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8333 EVT VT = Op.getValueType(); 8334 assert(VT.getSizeInBits() == 64); 8335 8336 SDLoc DL(Op); 8337 SDValue Cond = Op.getOperand(0); 8338 8339 if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() && 8340 !Op->isDivergent()) { 8341 if (VT == MVT::i64) 8342 return Op; 8343 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1)); 8344 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2)); 8345 return DAG.getNode(ISD::BITCAST, DL, VT, 8346 DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS)); 8347 } 8348 8349 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8350 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8351 8352 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8353 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8354 8355 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8356 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8357 8358 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8359 8360 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8361 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8362 8363 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8364 8365 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8366 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8367 } 8368 8369 // Catch division cases where we can use shortcuts with rcp and rsq 8370 // instructions. 8371 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8372 SelectionDAG &DAG) const { 8373 SDLoc SL(Op); 8374 SDValue LHS = Op.getOperand(0); 8375 SDValue RHS = Op.getOperand(1); 8376 EVT VT = Op.getValueType(); 8377 const SDNodeFlags Flags = Op->getFlags(); 8378 8379 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8380 8381 // Without !fpmath accuracy information, we can't do more because we don't 8382 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8383 if (!AllowInaccurateRcp) 8384 return SDValue(); 8385 8386 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8387 if (CLHS->isExactlyValue(1.0)) { 8388 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8389 // the CI documentation has a worst case error of 1 ulp. 8390 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8391 // use it as long as we aren't trying to use denormals. 8392 // 8393 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8394 8395 // 1.0 / sqrt(x) -> rsq(x) 8396 8397 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8398 // error seems really high at 2^29 ULP. 8399 if (RHS.getOpcode() == ISD::FSQRT) 8400 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8401 8402 // 1.0 / x -> rcp(x) 8403 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8404 } 8405 8406 // Same as for 1.0, but expand the sign out of the constant. 8407 if (CLHS->isExactlyValue(-1.0)) { 8408 // -1.0 / x -> rcp (fneg x) 8409 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8410 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8411 } 8412 } 8413 8414 // Turn into multiply by the reciprocal. 8415 // x / y -> x * (1.0 / y) 8416 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8417 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8418 } 8419 8420 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8421 SelectionDAG &DAG) const { 8422 SDLoc SL(Op); 8423 SDValue X = Op.getOperand(0); 8424 SDValue Y = Op.getOperand(1); 8425 EVT VT = Op.getValueType(); 8426 const SDNodeFlags Flags = Op->getFlags(); 8427 8428 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8429 DAG.getTarget().Options.UnsafeFPMath; 8430 if (!AllowInaccurateDiv) 8431 return SDValue(); 8432 8433 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8434 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8435 8436 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8437 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8438 8439 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8440 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8441 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8442 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8443 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8444 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8445 } 8446 8447 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8448 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8449 SDNodeFlags Flags) { 8450 if (GlueChain->getNumValues() <= 1) { 8451 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8452 } 8453 8454 assert(GlueChain->getNumValues() == 3); 8455 8456 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8457 switch (Opcode) { 8458 default: llvm_unreachable("no chain equivalent for opcode"); 8459 case ISD::FMUL: 8460 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8461 break; 8462 } 8463 8464 return DAG.getNode(Opcode, SL, VTList, 8465 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8466 Flags); 8467 } 8468 8469 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8470 EVT VT, SDValue A, SDValue B, SDValue C, 8471 SDValue GlueChain, SDNodeFlags Flags) { 8472 if (GlueChain->getNumValues() <= 1) { 8473 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8474 } 8475 8476 assert(GlueChain->getNumValues() == 3); 8477 8478 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8479 switch (Opcode) { 8480 default: llvm_unreachable("no chain equivalent for opcode"); 8481 case ISD::FMA: 8482 Opcode = AMDGPUISD::FMA_W_CHAIN; 8483 break; 8484 } 8485 8486 return DAG.getNode(Opcode, SL, VTList, 8487 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8488 Flags); 8489 } 8490 8491 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8492 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8493 return FastLowered; 8494 8495 SDLoc SL(Op); 8496 SDValue Src0 = Op.getOperand(0); 8497 SDValue Src1 = Op.getOperand(1); 8498 8499 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8500 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8501 8502 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8503 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8504 8505 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8506 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8507 8508 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8509 } 8510 8511 // Faster 2.5 ULP division that does not support denormals. 8512 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8513 SDLoc SL(Op); 8514 SDValue LHS = Op.getOperand(1); 8515 SDValue RHS = Op.getOperand(2); 8516 8517 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8518 8519 const APFloat K0Val(BitsToFloat(0x6f800000)); 8520 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8521 8522 const APFloat K1Val(BitsToFloat(0x2f800000)); 8523 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8524 8525 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8526 8527 EVT SetCCVT = 8528 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8529 8530 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8531 8532 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8533 8534 // TODO: Should this propagate fast-math-flags? 8535 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8536 8537 // rcp does not support denormals. 8538 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8539 8540 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8541 8542 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8543 } 8544 8545 // Returns immediate value for setting the F32 denorm mode when using the 8546 // S_DENORM_MODE instruction. 8547 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8548 const SDLoc &SL, const GCNSubtarget *ST) { 8549 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8550 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8551 ? FP_DENORM_FLUSH_NONE 8552 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8553 8554 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8555 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8556 } 8557 8558 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8559 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8560 return FastLowered; 8561 8562 // The selection matcher assumes anything with a chain selecting to a 8563 // mayRaiseFPException machine instruction. Since we're introducing a chain 8564 // here, we need to explicitly report nofpexcept for the regular fdiv 8565 // lowering. 8566 SDNodeFlags Flags = Op->getFlags(); 8567 Flags.setNoFPExcept(true); 8568 8569 SDLoc SL(Op); 8570 SDValue LHS = Op.getOperand(0); 8571 SDValue RHS = Op.getOperand(1); 8572 8573 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8574 8575 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8576 8577 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8578 {RHS, RHS, LHS}, Flags); 8579 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8580 {LHS, RHS, LHS}, Flags); 8581 8582 // Denominator is scaled to not be denormal, so using rcp is ok. 8583 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8584 DenominatorScaled, Flags); 8585 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8586 DenominatorScaled, Flags); 8587 8588 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8589 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8590 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8591 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8592 8593 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8594 8595 if (!HasFP32Denormals) { 8596 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8597 // lowering. The chain dependence is insufficient, and we need glue. We do 8598 // not need the glue variants in a strictfp function. 8599 8600 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8601 8602 SDNode *EnableDenorm; 8603 if (Subtarget->hasDenormModeInst()) { 8604 const SDValue EnableDenormValue = 8605 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8606 8607 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8608 DAG.getEntryNode(), EnableDenormValue).getNode(); 8609 } else { 8610 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8611 SL, MVT::i32); 8612 EnableDenorm = 8613 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8614 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8615 } 8616 8617 SDValue Ops[3] = { 8618 NegDivScale0, 8619 SDValue(EnableDenorm, 0), 8620 SDValue(EnableDenorm, 1) 8621 }; 8622 8623 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8624 } 8625 8626 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8627 ApproxRcp, One, NegDivScale0, Flags); 8628 8629 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8630 ApproxRcp, Fma0, Flags); 8631 8632 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8633 Fma1, Fma1, Flags); 8634 8635 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8636 NumeratorScaled, Mul, Flags); 8637 8638 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8639 Fma2, Fma1, Mul, Fma2, Flags); 8640 8641 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8642 NumeratorScaled, Fma3, Flags); 8643 8644 if (!HasFP32Denormals) { 8645 SDNode *DisableDenorm; 8646 if (Subtarget->hasDenormModeInst()) { 8647 const SDValue DisableDenormValue = 8648 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8649 8650 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8651 Fma4.getValue(1), DisableDenormValue, 8652 Fma4.getValue(2)).getNode(); 8653 } else { 8654 const SDValue DisableDenormValue = 8655 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8656 8657 DisableDenorm = DAG.getMachineNode( 8658 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8659 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8660 } 8661 8662 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8663 SDValue(DisableDenorm, 0), DAG.getRoot()); 8664 DAG.setRoot(OutputChain); 8665 } 8666 8667 SDValue Scale = NumeratorScaled.getValue(1); 8668 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8669 {Fma4, Fma1, Fma3, Scale}, Flags); 8670 8671 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8672 } 8673 8674 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8675 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8676 return FastLowered; 8677 8678 SDLoc SL(Op); 8679 SDValue X = Op.getOperand(0); 8680 SDValue Y = Op.getOperand(1); 8681 8682 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8683 8684 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8685 8686 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8687 8688 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8689 8690 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8691 8692 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8693 8694 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8695 8696 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8697 8698 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8699 8700 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8701 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8702 8703 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8704 NegDivScale0, Mul, DivScale1); 8705 8706 SDValue Scale; 8707 8708 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8709 // Workaround a hardware bug on SI where the condition output from div_scale 8710 // is not usable. 8711 8712 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8713 8714 // Figure out if the scale to use for div_fmas. 8715 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8716 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8717 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8718 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8719 8720 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8721 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8722 8723 SDValue Scale0Hi 8724 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8725 SDValue Scale1Hi 8726 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8727 8728 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8729 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8730 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8731 } else { 8732 Scale = DivScale1.getValue(1); 8733 } 8734 8735 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8736 Fma4, Fma3, Mul, Scale); 8737 8738 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8739 } 8740 8741 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8742 EVT VT = Op.getValueType(); 8743 8744 if (VT == MVT::f32) 8745 return LowerFDIV32(Op, DAG); 8746 8747 if (VT == MVT::f64) 8748 return LowerFDIV64(Op, DAG); 8749 8750 if (VT == MVT::f16) 8751 return LowerFDIV16(Op, DAG); 8752 8753 llvm_unreachable("Unexpected type for fdiv"); 8754 } 8755 8756 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8757 SDLoc DL(Op); 8758 StoreSDNode *Store = cast<StoreSDNode>(Op); 8759 EVT VT = Store->getMemoryVT(); 8760 8761 if (VT == MVT::i1) { 8762 return DAG.getTruncStore(Store->getChain(), DL, 8763 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8764 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8765 } 8766 8767 assert(VT.isVector() && 8768 Store->getValue().getValueType().getScalarType() == MVT::i32); 8769 8770 unsigned AS = Store->getAddressSpace(); 8771 if (Subtarget->hasLDSMisalignedBug() && 8772 AS == AMDGPUAS::FLAT_ADDRESS && 8773 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8774 return SplitVectorStore(Op, DAG); 8775 } 8776 8777 MachineFunction &MF = DAG.getMachineFunction(); 8778 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8779 // If there is a possibilty that flat instruction access scratch memory 8780 // then we need to use the same legalization rules we use for private. 8781 if (AS == AMDGPUAS::FLAT_ADDRESS && 8782 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8783 AS = MFI->hasFlatScratchInit() ? 8784 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8785 8786 unsigned NumElements = VT.getVectorNumElements(); 8787 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8788 AS == AMDGPUAS::FLAT_ADDRESS) { 8789 if (NumElements > 4) 8790 return SplitVectorStore(Op, DAG); 8791 // v3 stores not supported on SI. 8792 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8793 return SplitVectorStore(Op, DAG); 8794 8795 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8796 VT, *Store->getMemOperand())) 8797 return expandUnalignedStore(Store, DAG); 8798 8799 return SDValue(); 8800 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8801 switch (Subtarget->getMaxPrivateElementSize()) { 8802 case 4: 8803 return scalarizeVectorStore(Store, DAG); 8804 case 8: 8805 if (NumElements > 2) 8806 return SplitVectorStore(Op, DAG); 8807 return SDValue(); 8808 case 16: 8809 if (NumElements > 4 || 8810 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8811 return SplitVectorStore(Op, DAG); 8812 return SDValue(); 8813 default: 8814 llvm_unreachable("unsupported private_element_size"); 8815 } 8816 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8817 // Use ds_write_b128 or ds_write_b96 when possible. 8818 if (Subtarget->hasDS96AndDS128() && 8819 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8820 (VT.getStoreSize() == 12)) && 8821 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8822 Store->getAlign())) 8823 return SDValue(); 8824 8825 if (NumElements > 2) 8826 return SplitVectorStore(Op, DAG); 8827 8828 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8829 // address is negative, then the instruction is incorrectly treated as 8830 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8831 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8832 // store later in the SILoadStoreOptimizer. 8833 if (!Subtarget->hasUsableDSOffset() && 8834 NumElements == 2 && VT.getStoreSize() == 8 && 8835 Store->getAlignment() < 8) { 8836 return SplitVectorStore(Op, DAG); 8837 } 8838 8839 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8840 VT, *Store->getMemOperand())) { 8841 if (VT.isVector()) 8842 return SplitVectorStore(Op, DAG); 8843 return expandUnalignedStore(Store, DAG); 8844 } 8845 8846 return SDValue(); 8847 } else { 8848 llvm_unreachable("unhandled address space"); 8849 } 8850 } 8851 8852 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8853 SDLoc DL(Op); 8854 EVT VT = Op.getValueType(); 8855 SDValue Arg = Op.getOperand(0); 8856 SDValue TrigVal; 8857 8858 // Propagate fast-math flags so that the multiply we introduce can be folded 8859 // if Arg is already the result of a multiply by constant. 8860 auto Flags = Op->getFlags(); 8861 8862 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8863 8864 if (Subtarget->hasTrigReducedRange()) { 8865 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8866 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8867 } else { 8868 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8869 } 8870 8871 switch (Op.getOpcode()) { 8872 case ISD::FCOS: 8873 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8874 case ISD::FSIN: 8875 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8876 default: 8877 llvm_unreachable("Wrong trig opcode"); 8878 } 8879 } 8880 8881 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8882 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8883 assert(AtomicNode->isCompareAndSwap()); 8884 unsigned AS = AtomicNode->getAddressSpace(); 8885 8886 // No custom lowering required for local address space 8887 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8888 return Op; 8889 8890 // Non-local address space requires custom lowering for atomic compare 8891 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8892 SDLoc DL(Op); 8893 SDValue ChainIn = Op.getOperand(0); 8894 SDValue Addr = Op.getOperand(1); 8895 SDValue Old = Op.getOperand(2); 8896 SDValue New = Op.getOperand(3); 8897 EVT VT = Op.getValueType(); 8898 MVT SimpleVT = VT.getSimpleVT(); 8899 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8900 8901 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8902 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8903 8904 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8905 Ops, VT, AtomicNode->getMemOperand()); 8906 } 8907 8908 //===----------------------------------------------------------------------===// 8909 // Custom DAG optimizations 8910 //===----------------------------------------------------------------------===// 8911 8912 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8913 DAGCombinerInfo &DCI) const { 8914 EVT VT = N->getValueType(0); 8915 EVT ScalarVT = VT.getScalarType(); 8916 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8917 return SDValue(); 8918 8919 SelectionDAG &DAG = DCI.DAG; 8920 SDLoc DL(N); 8921 8922 SDValue Src = N->getOperand(0); 8923 EVT SrcVT = Src.getValueType(); 8924 8925 // TODO: We could try to match extracting the higher bytes, which would be 8926 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8927 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8928 // about in practice. 8929 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8930 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8931 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8932 DCI.AddToWorklist(Cvt.getNode()); 8933 8934 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8935 if (ScalarVT != MVT::f32) { 8936 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8937 DAG.getTargetConstant(0, DL, MVT::i32)); 8938 } 8939 return Cvt; 8940 } 8941 } 8942 8943 return SDValue(); 8944 } 8945 8946 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8947 8948 // This is a variant of 8949 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8950 // 8951 // The normal DAG combiner will do this, but only if the add has one use since 8952 // that would increase the number of instructions. 8953 // 8954 // This prevents us from seeing a constant offset that can be folded into a 8955 // memory instruction's addressing mode. If we know the resulting add offset of 8956 // a pointer can be folded into an addressing offset, we can replace the pointer 8957 // operand with the add of new constant offset. This eliminates one of the uses, 8958 // and may allow the remaining use to also be simplified. 8959 // 8960 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8961 unsigned AddrSpace, 8962 EVT MemVT, 8963 DAGCombinerInfo &DCI) const { 8964 SDValue N0 = N->getOperand(0); 8965 SDValue N1 = N->getOperand(1); 8966 8967 // We only do this to handle cases where it's profitable when there are 8968 // multiple uses of the add, so defer to the standard combine. 8969 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8970 N0->hasOneUse()) 8971 return SDValue(); 8972 8973 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8974 if (!CN1) 8975 return SDValue(); 8976 8977 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8978 if (!CAdd) 8979 return SDValue(); 8980 8981 // If the resulting offset is too large, we can't fold it into the addressing 8982 // mode offset. 8983 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8984 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8985 8986 AddrMode AM; 8987 AM.HasBaseReg = true; 8988 AM.BaseOffs = Offset.getSExtValue(); 8989 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8990 return SDValue(); 8991 8992 SelectionDAG &DAG = DCI.DAG; 8993 SDLoc SL(N); 8994 EVT VT = N->getValueType(0); 8995 8996 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8997 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8998 8999 SDNodeFlags Flags; 9000 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9001 (N0.getOpcode() == ISD::OR || 9002 N0->getFlags().hasNoUnsignedWrap())); 9003 9004 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9005 } 9006 9007 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9008 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9009 /// specific intrinsic, but they all place the pointer operand first. 9010 static unsigned getBasePtrIndex(const MemSDNode *N) { 9011 switch (N->getOpcode()) { 9012 case ISD::STORE: 9013 case ISD::INTRINSIC_W_CHAIN: 9014 case ISD::INTRINSIC_VOID: 9015 return 2; 9016 default: 9017 return 1; 9018 } 9019 } 9020 9021 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9022 DAGCombinerInfo &DCI) const { 9023 SelectionDAG &DAG = DCI.DAG; 9024 SDLoc SL(N); 9025 9026 unsigned PtrIdx = getBasePtrIndex(N); 9027 SDValue Ptr = N->getOperand(PtrIdx); 9028 9029 // TODO: We could also do this for multiplies. 9030 if (Ptr.getOpcode() == ISD::SHL) { 9031 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9032 N->getMemoryVT(), DCI); 9033 if (NewPtr) { 9034 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9035 9036 NewOps[PtrIdx] = NewPtr; 9037 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9038 } 9039 } 9040 9041 return SDValue(); 9042 } 9043 9044 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9045 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9046 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9047 (Opc == ISD::XOR && Val == 0); 9048 } 9049 9050 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9051 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9052 // integer combine opportunities since most 64-bit operations are decomposed 9053 // this way. TODO: We won't want this for SALU especially if it is an inline 9054 // immediate. 9055 SDValue SITargetLowering::splitBinaryBitConstantOp( 9056 DAGCombinerInfo &DCI, 9057 const SDLoc &SL, 9058 unsigned Opc, SDValue LHS, 9059 const ConstantSDNode *CRHS) const { 9060 uint64_t Val = CRHS->getZExtValue(); 9061 uint32_t ValLo = Lo_32(Val); 9062 uint32_t ValHi = Hi_32(Val); 9063 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9064 9065 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9066 bitOpWithConstantIsReducible(Opc, ValHi)) || 9067 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9068 // If we need to materialize a 64-bit immediate, it will be split up later 9069 // anyway. Avoid creating the harder to understand 64-bit immediate 9070 // materialization. 9071 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9072 } 9073 9074 return SDValue(); 9075 } 9076 9077 // Returns true if argument is a boolean value which is not serialized into 9078 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9079 static bool isBoolSGPR(SDValue V) { 9080 if (V.getValueType() != MVT::i1) 9081 return false; 9082 switch (V.getOpcode()) { 9083 default: 9084 break; 9085 case ISD::SETCC: 9086 case AMDGPUISD::FP_CLASS: 9087 return true; 9088 case ISD::AND: 9089 case ISD::OR: 9090 case ISD::XOR: 9091 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9092 } 9093 return false; 9094 } 9095 9096 // If a constant has all zeroes or all ones within each byte return it. 9097 // Otherwise return 0. 9098 static uint32_t getConstantPermuteMask(uint32_t C) { 9099 // 0xff for any zero byte in the mask 9100 uint32_t ZeroByteMask = 0; 9101 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9102 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9103 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9104 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9105 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9106 if ((NonZeroByteMask & C) != NonZeroByteMask) 9107 return 0; // Partial bytes selected. 9108 return C; 9109 } 9110 9111 // Check if a node selects whole bytes from its operand 0 starting at a byte 9112 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9113 // or -1 if not succeeded. 9114 // Note byte select encoding: 9115 // value 0-3 selects corresponding source byte; 9116 // value 0xc selects zero; 9117 // value 0xff selects 0xff. 9118 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9119 assert(V.getValueSizeInBits() == 32); 9120 9121 if (V.getNumOperands() != 2) 9122 return ~0; 9123 9124 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9125 if (!N1) 9126 return ~0; 9127 9128 uint32_t C = N1->getZExtValue(); 9129 9130 switch (V.getOpcode()) { 9131 default: 9132 break; 9133 case ISD::AND: 9134 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9135 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9136 } 9137 break; 9138 9139 case ISD::OR: 9140 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9141 return (0x03020100 & ~ConstMask) | ConstMask; 9142 } 9143 break; 9144 9145 case ISD::SHL: 9146 if (C % 8) 9147 return ~0; 9148 9149 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9150 9151 case ISD::SRL: 9152 if (C % 8) 9153 return ~0; 9154 9155 return uint32_t(0x0c0c0c0c03020100ull >> C); 9156 } 9157 9158 return ~0; 9159 } 9160 9161 SDValue SITargetLowering::performAndCombine(SDNode *N, 9162 DAGCombinerInfo &DCI) const { 9163 if (DCI.isBeforeLegalize()) 9164 return SDValue(); 9165 9166 SelectionDAG &DAG = DCI.DAG; 9167 EVT VT = N->getValueType(0); 9168 SDValue LHS = N->getOperand(0); 9169 SDValue RHS = N->getOperand(1); 9170 9171 9172 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9173 if (VT == MVT::i64 && CRHS) { 9174 if (SDValue Split 9175 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9176 return Split; 9177 } 9178 9179 if (CRHS && VT == MVT::i32) { 9180 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9181 // nb = number of trailing zeroes in mask 9182 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9183 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9184 uint64_t Mask = CRHS->getZExtValue(); 9185 unsigned Bits = countPopulation(Mask); 9186 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9187 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9188 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9189 unsigned Shift = CShift->getZExtValue(); 9190 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9191 unsigned Offset = NB + Shift; 9192 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9193 SDLoc SL(N); 9194 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9195 LHS->getOperand(0), 9196 DAG.getConstant(Offset, SL, MVT::i32), 9197 DAG.getConstant(Bits, SL, MVT::i32)); 9198 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9199 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9200 DAG.getValueType(NarrowVT)); 9201 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9202 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9203 return Shl; 9204 } 9205 } 9206 } 9207 9208 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9209 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9210 isa<ConstantSDNode>(LHS.getOperand(2))) { 9211 uint32_t Sel = getConstantPermuteMask(Mask); 9212 if (!Sel) 9213 return SDValue(); 9214 9215 // Select 0xc for all zero bytes 9216 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9217 SDLoc DL(N); 9218 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9219 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9220 } 9221 } 9222 9223 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9224 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9225 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9226 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9227 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9228 9229 SDValue X = LHS.getOperand(0); 9230 SDValue Y = RHS.getOperand(0); 9231 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9232 return SDValue(); 9233 9234 if (LCC == ISD::SETO) { 9235 if (X != LHS.getOperand(1)) 9236 return SDValue(); 9237 9238 if (RCC == ISD::SETUNE) { 9239 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9240 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9241 return SDValue(); 9242 9243 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9244 SIInstrFlags::N_SUBNORMAL | 9245 SIInstrFlags::N_ZERO | 9246 SIInstrFlags::P_ZERO | 9247 SIInstrFlags::P_SUBNORMAL | 9248 SIInstrFlags::P_NORMAL; 9249 9250 static_assert(((~(SIInstrFlags::S_NAN | 9251 SIInstrFlags::Q_NAN | 9252 SIInstrFlags::N_INFINITY | 9253 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9254 "mask not equal"); 9255 9256 SDLoc DL(N); 9257 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9258 X, DAG.getConstant(Mask, DL, MVT::i32)); 9259 } 9260 } 9261 } 9262 9263 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9264 std::swap(LHS, RHS); 9265 9266 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9267 RHS.hasOneUse()) { 9268 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9269 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9270 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9271 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9272 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9273 (RHS.getOperand(0) == LHS.getOperand(0) && 9274 LHS.getOperand(0) == LHS.getOperand(1))) { 9275 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9276 unsigned NewMask = LCC == ISD::SETO ? 9277 Mask->getZExtValue() & ~OrdMask : 9278 Mask->getZExtValue() & OrdMask; 9279 9280 SDLoc DL(N); 9281 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9282 DAG.getConstant(NewMask, DL, MVT::i32)); 9283 } 9284 } 9285 9286 if (VT == MVT::i32 && 9287 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9288 // and x, (sext cc from i1) => select cc, x, 0 9289 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9290 std::swap(LHS, RHS); 9291 if (isBoolSGPR(RHS.getOperand(0))) 9292 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9293 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9294 } 9295 9296 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9297 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9298 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9299 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9300 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9301 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9302 if (LHSMask != ~0u && RHSMask != ~0u) { 9303 // Canonicalize the expression in an attempt to have fewer unique masks 9304 // and therefore fewer registers used to hold the masks. 9305 if (LHSMask > RHSMask) { 9306 std::swap(LHSMask, RHSMask); 9307 std::swap(LHS, RHS); 9308 } 9309 9310 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9311 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9312 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9313 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9314 9315 // Check of we need to combine values from two sources within a byte. 9316 if (!(LHSUsedLanes & RHSUsedLanes) && 9317 // If we select high and lower word keep it for SDWA. 9318 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9319 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9320 // Each byte in each mask is either selector mask 0-3, or has higher 9321 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9322 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9323 // mask which is not 0xff wins. By anding both masks we have a correct 9324 // result except that 0x0c shall be corrected to give 0x0c only. 9325 uint32_t Mask = LHSMask & RHSMask; 9326 for (unsigned I = 0; I < 32; I += 8) { 9327 uint32_t ByteSel = 0xff << I; 9328 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9329 Mask &= (0x0c << I) & 0xffffffff; 9330 } 9331 9332 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9333 // or 0x0c. 9334 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9335 SDLoc DL(N); 9336 9337 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9338 LHS.getOperand(0), RHS.getOperand(0), 9339 DAG.getConstant(Sel, DL, MVT::i32)); 9340 } 9341 } 9342 } 9343 9344 return SDValue(); 9345 } 9346 9347 SDValue SITargetLowering::performOrCombine(SDNode *N, 9348 DAGCombinerInfo &DCI) const { 9349 SelectionDAG &DAG = DCI.DAG; 9350 SDValue LHS = N->getOperand(0); 9351 SDValue RHS = N->getOperand(1); 9352 9353 EVT VT = N->getValueType(0); 9354 if (VT == MVT::i1) { 9355 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9356 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9357 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9358 SDValue Src = LHS.getOperand(0); 9359 if (Src != RHS.getOperand(0)) 9360 return SDValue(); 9361 9362 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9363 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9364 if (!CLHS || !CRHS) 9365 return SDValue(); 9366 9367 // Only 10 bits are used. 9368 static const uint32_t MaxMask = 0x3ff; 9369 9370 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9371 SDLoc DL(N); 9372 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9373 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9374 } 9375 9376 return SDValue(); 9377 } 9378 9379 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9380 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9381 LHS.getOpcode() == AMDGPUISD::PERM && 9382 isa<ConstantSDNode>(LHS.getOperand(2))) { 9383 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9384 if (!Sel) 9385 return SDValue(); 9386 9387 Sel |= LHS.getConstantOperandVal(2); 9388 SDLoc DL(N); 9389 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9390 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9391 } 9392 9393 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9394 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9395 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9396 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9397 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9398 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9399 if (LHSMask != ~0u && RHSMask != ~0u) { 9400 // Canonicalize the expression in an attempt to have fewer unique masks 9401 // and therefore fewer registers used to hold the masks. 9402 if (LHSMask > RHSMask) { 9403 std::swap(LHSMask, RHSMask); 9404 std::swap(LHS, RHS); 9405 } 9406 9407 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9408 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9409 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9410 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9411 9412 // Check of we need to combine values from two sources within a byte. 9413 if (!(LHSUsedLanes & RHSUsedLanes) && 9414 // If we select high and lower word keep it for SDWA. 9415 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9416 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9417 // Kill zero bytes selected by other mask. Zero value is 0xc. 9418 LHSMask &= ~RHSUsedLanes; 9419 RHSMask &= ~LHSUsedLanes; 9420 // Add 4 to each active LHS lane 9421 LHSMask |= LHSUsedLanes & 0x04040404; 9422 // Combine masks 9423 uint32_t Sel = LHSMask | RHSMask; 9424 SDLoc DL(N); 9425 9426 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9427 LHS.getOperand(0), RHS.getOperand(0), 9428 DAG.getConstant(Sel, DL, MVT::i32)); 9429 } 9430 } 9431 } 9432 9433 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9434 return SDValue(); 9435 9436 // TODO: This could be a generic combine with a predicate for extracting the 9437 // high half of an integer being free. 9438 9439 // (or i64:x, (zero_extend i32:y)) -> 9440 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9441 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9442 RHS.getOpcode() != ISD::ZERO_EXTEND) 9443 std::swap(LHS, RHS); 9444 9445 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9446 SDValue ExtSrc = RHS.getOperand(0); 9447 EVT SrcVT = ExtSrc.getValueType(); 9448 if (SrcVT == MVT::i32) { 9449 SDLoc SL(N); 9450 SDValue LowLHS, HiBits; 9451 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9452 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9453 9454 DCI.AddToWorklist(LowOr.getNode()); 9455 DCI.AddToWorklist(HiBits.getNode()); 9456 9457 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9458 LowOr, HiBits); 9459 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9460 } 9461 } 9462 9463 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9464 if (CRHS) { 9465 if (SDValue Split 9466 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9467 return Split; 9468 } 9469 9470 return SDValue(); 9471 } 9472 9473 SDValue SITargetLowering::performXorCombine(SDNode *N, 9474 DAGCombinerInfo &DCI) const { 9475 EVT VT = N->getValueType(0); 9476 if (VT != MVT::i64) 9477 return SDValue(); 9478 9479 SDValue LHS = N->getOperand(0); 9480 SDValue RHS = N->getOperand(1); 9481 9482 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9483 if (CRHS) { 9484 if (SDValue Split 9485 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9486 return Split; 9487 } 9488 9489 return SDValue(); 9490 } 9491 9492 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9493 DAGCombinerInfo &DCI) const { 9494 if (!Subtarget->has16BitInsts() || 9495 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9496 return SDValue(); 9497 9498 EVT VT = N->getValueType(0); 9499 if (VT != MVT::i32) 9500 return SDValue(); 9501 9502 SDValue Src = N->getOperand(0); 9503 if (Src.getValueType() != MVT::i16) 9504 return SDValue(); 9505 9506 return SDValue(); 9507 } 9508 9509 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9510 DAGCombinerInfo &DCI) 9511 const { 9512 SDValue Src = N->getOperand(0); 9513 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9514 9515 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9516 VTSign->getVT() == MVT::i8) || 9517 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9518 VTSign->getVT() == MVT::i16)) && 9519 Src.hasOneUse()) { 9520 auto *M = cast<MemSDNode>(Src); 9521 SDValue Ops[] = { 9522 Src.getOperand(0), // Chain 9523 Src.getOperand(1), // rsrc 9524 Src.getOperand(2), // vindex 9525 Src.getOperand(3), // voffset 9526 Src.getOperand(4), // soffset 9527 Src.getOperand(5), // offset 9528 Src.getOperand(6), 9529 Src.getOperand(7) 9530 }; 9531 // replace with BUFFER_LOAD_BYTE/SHORT 9532 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9533 Src.getOperand(0).getValueType()); 9534 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9535 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9536 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9537 ResList, 9538 Ops, M->getMemoryVT(), 9539 M->getMemOperand()); 9540 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9541 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9542 } 9543 return SDValue(); 9544 } 9545 9546 SDValue SITargetLowering::performClassCombine(SDNode *N, 9547 DAGCombinerInfo &DCI) const { 9548 SelectionDAG &DAG = DCI.DAG; 9549 SDValue Mask = N->getOperand(1); 9550 9551 // fp_class x, 0 -> false 9552 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9553 if (CMask->isZero()) 9554 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9555 } 9556 9557 if (N->getOperand(0).isUndef()) 9558 return DAG.getUNDEF(MVT::i1); 9559 9560 return SDValue(); 9561 } 9562 9563 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9564 DAGCombinerInfo &DCI) const { 9565 EVT VT = N->getValueType(0); 9566 SDValue N0 = N->getOperand(0); 9567 9568 if (N0.isUndef()) 9569 return N0; 9570 9571 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9572 N0.getOpcode() == ISD::SINT_TO_FP)) { 9573 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9574 N->getFlags()); 9575 } 9576 9577 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9578 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9579 N0.getOperand(0), N->getFlags()); 9580 } 9581 9582 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9583 } 9584 9585 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9586 unsigned MaxDepth) const { 9587 unsigned Opcode = Op.getOpcode(); 9588 if (Opcode == ISD::FCANONICALIZE) 9589 return true; 9590 9591 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9592 auto F = CFP->getValueAPF(); 9593 if (F.isNaN() && F.isSignaling()) 9594 return false; 9595 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9596 } 9597 9598 // If source is a result of another standard FP operation it is already in 9599 // canonical form. 9600 if (MaxDepth == 0) 9601 return false; 9602 9603 switch (Opcode) { 9604 // These will flush denorms if required. 9605 case ISD::FADD: 9606 case ISD::FSUB: 9607 case ISD::FMUL: 9608 case ISD::FCEIL: 9609 case ISD::FFLOOR: 9610 case ISD::FMA: 9611 case ISD::FMAD: 9612 case ISD::FSQRT: 9613 case ISD::FDIV: 9614 case ISD::FREM: 9615 case ISD::FP_ROUND: 9616 case ISD::FP_EXTEND: 9617 case AMDGPUISD::FMUL_LEGACY: 9618 case AMDGPUISD::FMAD_FTZ: 9619 case AMDGPUISD::RCP: 9620 case AMDGPUISD::RSQ: 9621 case AMDGPUISD::RSQ_CLAMP: 9622 case AMDGPUISD::RCP_LEGACY: 9623 case AMDGPUISD::RCP_IFLAG: 9624 case AMDGPUISD::DIV_SCALE: 9625 case AMDGPUISD::DIV_FMAS: 9626 case AMDGPUISD::DIV_FIXUP: 9627 case AMDGPUISD::FRACT: 9628 case AMDGPUISD::LDEXP: 9629 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9630 case AMDGPUISD::CVT_F32_UBYTE0: 9631 case AMDGPUISD::CVT_F32_UBYTE1: 9632 case AMDGPUISD::CVT_F32_UBYTE2: 9633 case AMDGPUISD::CVT_F32_UBYTE3: 9634 return true; 9635 9636 // It can/will be lowered or combined as a bit operation. 9637 // Need to check their input recursively to handle. 9638 case ISD::FNEG: 9639 case ISD::FABS: 9640 case ISD::FCOPYSIGN: 9641 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9642 9643 case ISD::FSIN: 9644 case ISD::FCOS: 9645 case ISD::FSINCOS: 9646 return Op.getValueType().getScalarType() != MVT::f16; 9647 9648 case ISD::FMINNUM: 9649 case ISD::FMAXNUM: 9650 case ISD::FMINNUM_IEEE: 9651 case ISD::FMAXNUM_IEEE: 9652 case AMDGPUISD::CLAMP: 9653 case AMDGPUISD::FMED3: 9654 case AMDGPUISD::FMAX3: 9655 case AMDGPUISD::FMIN3: { 9656 // FIXME: Shouldn't treat the generic operations different based these. 9657 // However, we aren't really required to flush the result from 9658 // minnum/maxnum.. 9659 9660 // snans will be quieted, so we only need to worry about denormals. 9661 if (Subtarget->supportsMinMaxDenormModes() || 9662 denormalsEnabledForType(DAG, Op.getValueType())) 9663 return true; 9664 9665 // Flushing may be required. 9666 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9667 // targets need to check their input recursively. 9668 9669 // FIXME: Does this apply with clamp? It's implemented with max. 9670 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9671 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9672 return false; 9673 } 9674 9675 return true; 9676 } 9677 case ISD::SELECT: { 9678 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9679 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9680 } 9681 case ISD::BUILD_VECTOR: { 9682 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9683 SDValue SrcOp = Op.getOperand(i); 9684 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9685 return false; 9686 } 9687 9688 return true; 9689 } 9690 case ISD::EXTRACT_VECTOR_ELT: 9691 case ISD::EXTRACT_SUBVECTOR: { 9692 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9693 } 9694 case ISD::INSERT_VECTOR_ELT: { 9695 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9696 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9697 } 9698 case ISD::UNDEF: 9699 // Could be anything. 9700 return false; 9701 9702 case ISD::BITCAST: 9703 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9704 case ISD::TRUNCATE: { 9705 // Hack round the mess we make when legalizing extract_vector_elt 9706 if (Op.getValueType() == MVT::i16) { 9707 SDValue TruncSrc = Op.getOperand(0); 9708 if (TruncSrc.getValueType() == MVT::i32 && 9709 TruncSrc.getOpcode() == ISD::BITCAST && 9710 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9711 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9712 } 9713 } 9714 return false; 9715 } 9716 case ISD::INTRINSIC_WO_CHAIN: { 9717 unsigned IntrinsicID 9718 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9719 // TODO: Handle more intrinsics 9720 switch (IntrinsicID) { 9721 case Intrinsic::amdgcn_cvt_pkrtz: 9722 case Intrinsic::amdgcn_cubeid: 9723 case Intrinsic::amdgcn_frexp_mant: 9724 case Intrinsic::amdgcn_fdot2: 9725 case Intrinsic::amdgcn_rcp: 9726 case Intrinsic::amdgcn_rsq: 9727 case Intrinsic::amdgcn_rsq_clamp: 9728 case Intrinsic::amdgcn_rcp_legacy: 9729 case Intrinsic::amdgcn_rsq_legacy: 9730 case Intrinsic::amdgcn_trig_preop: 9731 return true; 9732 default: 9733 break; 9734 } 9735 9736 LLVM_FALLTHROUGH; 9737 } 9738 default: 9739 return denormalsEnabledForType(DAG, Op.getValueType()) && 9740 DAG.isKnownNeverSNaN(Op); 9741 } 9742 9743 llvm_unreachable("invalid operation"); 9744 } 9745 9746 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9747 unsigned MaxDepth) const { 9748 MachineRegisterInfo &MRI = MF.getRegInfo(); 9749 MachineInstr *MI = MRI.getVRegDef(Reg); 9750 unsigned Opcode = MI->getOpcode(); 9751 9752 if (Opcode == AMDGPU::G_FCANONICALIZE) 9753 return true; 9754 9755 if (Opcode == AMDGPU::G_FCONSTANT) { 9756 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9757 if (F.isNaN() && F.isSignaling()) 9758 return false; 9759 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9760 } 9761 9762 if (MaxDepth == 0) 9763 return false; 9764 9765 switch (Opcode) { 9766 case AMDGPU::G_FMINNUM_IEEE: 9767 case AMDGPU::G_FMAXNUM_IEEE: { 9768 if (Subtarget->supportsMinMaxDenormModes() || 9769 denormalsEnabledForType(MRI.getType(Reg), MF)) 9770 return true; 9771 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9772 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9773 return false; 9774 } 9775 return true; 9776 } 9777 default: 9778 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9779 isKnownNeverSNaN(Reg, MRI); 9780 } 9781 9782 llvm_unreachable("invalid operation"); 9783 } 9784 9785 // Constant fold canonicalize. 9786 SDValue SITargetLowering::getCanonicalConstantFP( 9787 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9788 // Flush denormals to 0 if not enabled. 9789 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9790 return DAG.getConstantFP(0.0, SL, VT); 9791 9792 if (C.isNaN()) { 9793 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9794 if (C.isSignaling()) { 9795 // Quiet a signaling NaN. 9796 // FIXME: Is this supposed to preserve payload bits? 9797 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9798 } 9799 9800 // Make sure it is the canonical NaN bitpattern. 9801 // 9802 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9803 // immediate? 9804 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9805 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9806 } 9807 9808 // Already canonical. 9809 return DAG.getConstantFP(C, SL, VT); 9810 } 9811 9812 static bool vectorEltWillFoldAway(SDValue Op) { 9813 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9814 } 9815 9816 SDValue SITargetLowering::performFCanonicalizeCombine( 9817 SDNode *N, 9818 DAGCombinerInfo &DCI) const { 9819 SelectionDAG &DAG = DCI.DAG; 9820 SDValue N0 = N->getOperand(0); 9821 EVT VT = N->getValueType(0); 9822 9823 // fcanonicalize undef -> qnan 9824 if (N0.isUndef()) { 9825 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9826 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9827 } 9828 9829 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9830 EVT VT = N->getValueType(0); 9831 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9832 } 9833 9834 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9835 // (fcanonicalize k) 9836 // 9837 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9838 9839 // TODO: This could be better with wider vectors that will be split to v2f16, 9840 // and to consider uses since there aren't that many packed operations. 9841 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9842 isTypeLegal(MVT::v2f16)) { 9843 SDLoc SL(N); 9844 SDValue NewElts[2]; 9845 SDValue Lo = N0.getOperand(0); 9846 SDValue Hi = N0.getOperand(1); 9847 EVT EltVT = Lo.getValueType(); 9848 9849 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9850 for (unsigned I = 0; I != 2; ++I) { 9851 SDValue Op = N0.getOperand(I); 9852 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9853 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9854 CFP->getValueAPF()); 9855 } else if (Op.isUndef()) { 9856 // Handled below based on what the other operand is. 9857 NewElts[I] = Op; 9858 } else { 9859 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9860 } 9861 } 9862 9863 // If one half is undef, and one is constant, perfer a splat vector rather 9864 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9865 // cheaper to use and may be free with a packed operation. 9866 if (NewElts[0].isUndef()) { 9867 if (isa<ConstantFPSDNode>(NewElts[1])) 9868 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9869 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9870 } 9871 9872 if (NewElts[1].isUndef()) { 9873 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9874 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9875 } 9876 9877 return DAG.getBuildVector(VT, SL, NewElts); 9878 } 9879 } 9880 9881 unsigned SrcOpc = N0.getOpcode(); 9882 9883 // If it's free to do so, push canonicalizes further up the source, which may 9884 // find a canonical source. 9885 // 9886 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9887 // sNaNs. 9888 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9889 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9890 if (CRHS && N0.hasOneUse()) { 9891 SDLoc SL(N); 9892 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9893 N0.getOperand(0)); 9894 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9895 DCI.AddToWorklist(Canon0.getNode()); 9896 9897 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9898 } 9899 } 9900 9901 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9902 } 9903 9904 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9905 switch (Opc) { 9906 case ISD::FMAXNUM: 9907 case ISD::FMAXNUM_IEEE: 9908 return AMDGPUISD::FMAX3; 9909 case ISD::SMAX: 9910 return AMDGPUISD::SMAX3; 9911 case ISD::UMAX: 9912 return AMDGPUISD::UMAX3; 9913 case ISD::FMINNUM: 9914 case ISD::FMINNUM_IEEE: 9915 return AMDGPUISD::FMIN3; 9916 case ISD::SMIN: 9917 return AMDGPUISD::SMIN3; 9918 case ISD::UMIN: 9919 return AMDGPUISD::UMIN3; 9920 default: 9921 llvm_unreachable("Not a min/max opcode"); 9922 } 9923 } 9924 9925 SDValue SITargetLowering::performIntMed3ImmCombine( 9926 SelectionDAG &DAG, const SDLoc &SL, 9927 SDValue Op0, SDValue Op1, bool Signed) const { 9928 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9929 if (!K1) 9930 return SDValue(); 9931 9932 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9933 if (!K0) 9934 return SDValue(); 9935 9936 if (Signed) { 9937 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9938 return SDValue(); 9939 } else { 9940 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9941 return SDValue(); 9942 } 9943 9944 EVT VT = K0->getValueType(0); 9945 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9946 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9947 return DAG.getNode(Med3Opc, SL, VT, 9948 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9949 } 9950 9951 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9952 if (VT == MVT::i16) { 9953 MVT NVT = MVT::i32; 9954 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9955 9956 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9957 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9958 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9959 9960 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9961 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9962 } 9963 9964 return SDValue(); 9965 } 9966 9967 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9968 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9969 return C; 9970 9971 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9972 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9973 return C; 9974 } 9975 9976 return nullptr; 9977 } 9978 9979 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9980 const SDLoc &SL, 9981 SDValue Op0, 9982 SDValue Op1) const { 9983 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9984 if (!K1) 9985 return SDValue(); 9986 9987 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9988 if (!K0) 9989 return SDValue(); 9990 9991 // Ordered >= (although NaN inputs should have folded away by now). 9992 if (K0->getValueAPF() > K1->getValueAPF()) 9993 return SDValue(); 9994 9995 const MachineFunction &MF = DAG.getMachineFunction(); 9996 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9997 9998 // TODO: Check IEEE bit enabled? 9999 EVT VT = Op0.getValueType(); 10000 if (Info->getMode().DX10Clamp) { 10001 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10002 // hardware fmed3 behavior converting to a min. 10003 // FIXME: Should this be allowing -0.0? 10004 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10005 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10006 } 10007 10008 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10009 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10010 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10011 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10012 // then give the other result, which is different from med3 with a NaN 10013 // input. 10014 SDValue Var = Op0.getOperand(0); 10015 if (!DAG.isKnownNeverSNaN(Var)) 10016 return SDValue(); 10017 10018 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10019 10020 if ((!K0->hasOneUse() || 10021 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10022 (!K1->hasOneUse() || 10023 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10024 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10025 Var, SDValue(K0, 0), SDValue(K1, 0)); 10026 } 10027 } 10028 10029 return SDValue(); 10030 } 10031 10032 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10033 DAGCombinerInfo &DCI) const { 10034 SelectionDAG &DAG = DCI.DAG; 10035 10036 EVT VT = N->getValueType(0); 10037 unsigned Opc = N->getOpcode(); 10038 SDValue Op0 = N->getOperand(0); 10039 SDValue Op1 = N->getOperand(1); 10040 10041 // Only do this if the inner op has one use since this will just increases 10042 // register pressure for no benefit. 10043 10044 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10045 !VT.isVector() && 10046 (VT == MVT::i32 || VT == MVT::f32 || 10047 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10048 // max(max(a, b), c) -> max3(a, b, c) 10049 // min(min(a, b), c) -> min3(a, b, c) 10050 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10051 SDLoc DL(N); 10052 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10053 DL, 10054 N->getValueType(0), 10055 Op0.getOperand(0), 10056 Op0.getOperand(1), 10057 Op1); 10058 } 10059 10060 // Try commuted. 10061 // max(a, max(b, c)) -> max3(a, b, c) 10062 // min(a, min(b, c)) -> min3(a, b, c) 10063 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10064 SDLoc DL(N); 10065 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10066 DL, 10067 N->getValueType(0), 10068 Op0, 10069 Op1.getOperand(0), 10070 Op1.getOperand(1)); 10071 } 10072 } 10073 10074 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10075 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10076 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10077 return Med3; 10078 } 10079 10080 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10081 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10082 return Med3; 10083 } 10084 10085 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10086 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10087 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10088 (Opc == AMDGPUISD::FMIN_LEGACY && 10089 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10090 (VT == MVT::f32 || VT == MVT::f64 || 10091 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10092 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10093 Op0.hasOneUse()) { 10094 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10095 return Res; 10096 } 10097 10098 return SDValue(); 10099 } 10100 10101 static bool isClampZeroToOne(SDValue A, SDValue B) { 10102 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10103 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10104 // FIXME: Should this be allowing -0.0? 10105 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10106 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10107 } 10108 } 10109 10110 return false; 10111 } 10112 10113 // FIXME: Should only worry about snans for version with chain. 10114 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10115 DAGCombinerInfo &DCI) const { 10116 EVT VT = N->getValueType(0); 10117 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10118 // NaNs. With a NaN input, the order of the operands may change the result. 10119 10120 SelectionDAG &DAG = DCI.DAG; 10121 SDLoc SL(N); 10122 10123 SDValue Src0 = N->getOperand(0); 10124 SDValue Src1 = N->getOperand(1); 10125 SDValue Src2 = N->getOperand(2); 10126 10127 if (isClampZeroToOne(Src0, Src1)) { 10128 // const_a, const_b, x -> clamp is safe in all cases including signaling 10129 // nans. 10130 // FIXME: Should this be allowing -0.0? 10131 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10132 } 10133 10134 const MachineFunction &MF = DAG.getMachineFunction(); 10135 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10136 10137 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10138 // handling no dx10-clamp? 10139 if (Info->getMode().DX10Clamp) { 10140 // If NaNs is clamped to 0, we are free to reorder the inputs. 10141 10142 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10143 std::swap(Src0, Src1); 10144 10145 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10146 std::swap(Src1, Src2); 10147 10148 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10149 std::swap(Src0, Src1); 10150 10151 if (isClampZeroToOne(Src1, Src2)) 10152 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10153 } 10154 10155 return SDValue(); 10156 } 10157 10158 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10159 DAGCombinerInfo &DCI) const { 10160 SDValue Src0 = N->getOperand(0); 10161 SDValue Src1 = N->getOperand(1); 10162 if (Src0.isUndef() && Src1.isUndef()) 10163 return DCI.DAG.getUNDEF(N->getValueType(0)); 10164 return SDValue(); 10165 } 10166 10167 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10168 // expanded into a set of cmp/select instructions. 10169 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10170 unsigned NumElem, 10171 bool IsDivergentIdx) { 10172 if (UseDivergentRegisterIndexing) 10173 return false; 10174 10175 unsigned VecSize = EltSize * NumElem; 10176 10177 // Sub-dword vectors of size 2 dword or less have better implementation. 10178 if (VecSize <= 64 && EltSize < 32) 10179 return false; 10180 10181 // Always expand the rest of sub-dword instructions, otherwise it will be 10182 // lowered via memory. 10183 if (EltSize < 32) 10184 return true; 10185 10186 // Always do this if var-idx is divergent, otherwise it will become a loop. 10187 if (IsDivergentIdx) 10188 return true; 10189 10190 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10191 unsigned NumInsts = NumElem /* Number of compares */ + 10192 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10193 return NumInsts <= 16; 10194 } 10195 10196 static bool shouldExpandVectorDynExt(SDNode *N) { 10197 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10198 if (isa<ConstantSDNode>(Idx)) 10199 return false; 10200 10201 SDValue Vec = N->getOperand(0); 10202 EVT VecVT = Vec.getValueType(); 10203 EVT EltVT = VecVT.getVectorElementType(); 10204 unsigned EltSize = EltVT.getSizeInBits(); 10205 unsigned NumElem = VecVT.getVectorNumElements(); 10206 10207 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10208 Idx->isDivergent()); 10209 } 10210 10211 SDValue SITargetLowering::performExtractVectorEltCombine( 10212 SDNode *N, DAGCombinerInfo &DCI) const { 10213 SDValue Vec = N->getOperand(0); 10214 SelectionDAG &DAG = DCI.DAG; 10215 10216 EVT VecVT = Vec.getValueType(); 10217 EVT EltVT = VecVT.getVectorElementType(); 10218 10219 if ((Vec.getOpcode() == ISD::FNEG || 10220 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10221 SDLoc SL(N); 10222 EVT EltVT = N->getValueType(0); 10223 SDValue Idx = N->getOperand(1); 10224 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10225 Vec.getOperand(0), Idx); 10226 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10227 } 10228 10229 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10230 // => 10231 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10232 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10233 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10234 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10235 SDLoc SL(N); 10236 EVT EltVT = N->getValueType(0); 10237 SDValue Idx = N->getOperand(1); 10238 unsigned Opc = Vec.getOpcode(); 10239 10240 switch(Opc) { 10241 default: 10242 break; 10243 // TODO: Support other binary operations. 10244 case ISD::FADD: 10245 case ISD::FSUB: 10246 case ISD::FMUL: 10247 case ISD::ADD: 10248 case ISD::UMIN: 10249 case ISD::UMAX: 10250 case ISD::SMIN: 10251 case ISD::SMAX: 10252 case ISD::FMAXNUM: 10253 case ISD::FMINNUM: 10254 case ISD::FMAXNUM_IEEE: 10255 case ISD::FMINNUM_IEEE: { 10256 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10257 Vec.getOperand(0), Idx); 10258 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10259 Vec.getOperand(1), Idx); 10260 10261 DCI.AddToWorklist(Elt0.getNode()); 10262 DCI.AddToWorklist(Elt1.getNode()); 10263 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10264 } 10265 } 10266 } 10267 10268 unsigned VecSize = VecVT.getSizeInBits(); 10269 unsigned EltSize = EltVT.getSizeInBits(); 10270 10271 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10272 if (::shouldExpandVectorDynExt(N)) { 10273 SDLoc SL(N); 10274 SDValue Idx = N->getOperand(1); 10275 SDValue V; 10276 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10277 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10278 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10279 if (I == 0) 10280 V = Elt; 10281 else 10282 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10283 } 10284 return V; 10285 } 10286 10287 if (!DCI.isBeforeLegalize()) 10288 return SDValue(); 10289 10290 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10291 // elements. This exposes more load reduction opportunities by replacing 10292 // multiple small extract_vector_elements with a single 32-bit extract. 10293 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10294 if (isa<MemSDNode>(Vec) && 10295 EltSize <= 16 && 10296 EltVT.isByteSized() && 10297 VecSize > 32 && 10298 VecSize % 32 == 0 && 10299 Idx) { 10300 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10301 10302 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10303 unsigned EltIdx = BitIndex / 32; 10304 unsigned LeftoverBitIdx = BitIndex % 32; 10305 SDLoc SL(N); 10306 10307 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10308 DCI.AddToWorklist(Cast.getNode()); 10309 10310 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10311 DAG.getConstant(EltIdx, SL, MVT::i32)); 10312 DCI.AddToWorklist(Elt.getNode()); 10313 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10314 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10315 DCI.AddToWorklist(Srl.getNode()); 10316 10317 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10318 DCI.AddToWorklist(Trunc.getNode()); 10319 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10320 } 10321 10322 return SDValue(); 10323 } 10324 10325 SDValue 10326 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10327 DAGCombinerInfo &DCI) const { 10328 SDValue Vec = N->getOperand(0); 10329 SDValue Idx = N->getOperand(2); 10330 EVT VecVT = Vec.getValueType(); 10331 EVT EltVT = VecVT.getVectorElementType(); 10332 10333 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10334 // => BUILD_VECTOR n x select (e, const-idx) 10335 if (!::shouldExpandVectorDynExt(N)) 10336 return SDValue(); 10337 10338 SelectionDAG &DAG = DCI.DAG; 10339 SDLoc SL(N); 10340 SDValue Ins = N->getOperand(1); 10341 EVT IdxVT = Idx.getValueType(); 10342 10343 SmallVector<SDValue, 16> Ops; 10344 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10345 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10346 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10347 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10348 Ops.push_back(V); 10349 } 10350 10351 return DAG.getBuildVector(VecVT, SL, Ops); 10352 } 10353 10354 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10355 const SDNode *N0, 10356 const SDNode *N1) const { 10357 EVT VT = N0->getValueType(0); 10358 10359 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10360 // support denormals ever. 10361 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10362 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10363 getSubtarget()->hasMadF16())) && 10364 isOperationLegal(ISD::FMAD, VT)) 10365 return ISD::FMAD; 10366 10367 const TargetOptions &Options = DAG.getTarget().Options; 10368 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10369 (N0->getFlags().hasAllowContract() && 10370 N1->getFlags().hasAllowContract())) && 10371 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10372 return ISD::FMA; 10373 } 10374 10375 return 0; 10376 } 10377 10378 // For a reassociatable opcode perform: 10379 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10380 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10381 SelectionDAG &DAG) const { 10382 EVT VT = N->getValueType(0); 10383 if (VT != MVT::i32 && VT != MVT::i64) 10384 return SDValue(); 10385 10386 unsigned Opc = N->getOpcode(); 10387 SDValue Op0 = N->getOperand(0); 10388 SDValue Op1 = N->getOperand(1); 10389 10390 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10391 return SDValue(); 10392 10393 if (Op0->isDivergent()) 10394 std::swap(Op0, Op1); 10395 10396 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10397 return SDValue(); 10398 10399 SDValue Op2 = Op1.getOperand(1); 10400 Op1 = Op1.getOperand(0); 10401 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10402 return SDValue(); 10403 10404 if (Op1->isDivergent()) 10405 std::swap(Op1, Op2); 10406 10407 // If either operand is constant this will conflict with 10408 // DAGCombiner::ReassociateOps(). 10409 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10410 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10411 return SDValue(); 10412 10413 SDLoc SL(N); 10414 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10415 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10416 } 10417 10418 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10419 EVT VT, 10420 SDValue N0, SDValue N1, SDValue N2, 10421 bool Signed) { 10422 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10423 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10424 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10425 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10426 } 10427 10428 SDValue SITargetLowering::performAddCombine(SDNode *N, 10429 DAGCombinerInfo &DCI) const { 10430 SelectionDAG &DAG = DCI.DAG; 10431 EVT VT = N->getValueType(0); 10432 SDLoc SL(N); 10433 SDValue LHS = N->getOperand(0); 10434 SDValue RHS = N->getOperand(1); 10435 10436 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10437 && Subtarget->hasMad64_32() && 10438 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10439 VT.getScalarSizeInBits() <= 64) { 10440 if (LHS.getOpcode() != ISD::MUL) 10441 std::swap(LHS, RHS); 10442 10443 SDValue MulLHS = LHS.getOperand(0); 10444 SDValue MulRHS = LHS.getOperand(1); 10445 SDValue AddRHS = RHS; 10446 10447 // TODO: Maybe restrict if SGPR inputs. 10448 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10449 numBitsUnsigned(MulRHS, DAG) <= 32) { 10450 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10451 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10452 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10453 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10454 } 10455 10456 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10457 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10458 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10459 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10460 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10461 } 10462 10463 return SDValue(); 10464 } 10465 10466 if (SDValue V = reassociateScalarOps(N, DAG)) { 10467 return V; 10468 } 10469 10470 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10471 return SDValue(); 10472 10473 // add x, zext (setcc) => addcarry x, 0, setcc 10474 // add x, sext (setcc) => subcarry x, 0, setcc 10475 unsigned Opc = LHS.getOpcode(); 10476 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10477 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10478 std::swap(RHS, LHS); 10479 10480 Opc = RHS.getOpcode(); 10481 switch (Opc) { 10482 default: break; 10483 case ISD::ZERO_EXTEND: 10484 case ISD::SIGN_EXTEND: 10485 case ISD::ANY_EXTEND: { 10486 auto Cond = RHS.getOperand(0); 10487 // If this won't be a real VOPC output, we would still need to insert an 10488 // extra instruction anyway. 10489 if (!isBoolSGPR(Cond)) 10490 break; 10491 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10492 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10493 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10494 return DAG.getNode(Opc, SL, VTList, Args); 10495 } 10496 case ISD::ADDCARRY: { 10497 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10498 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10499 if (!C || C->getZExtValue() != 0) break; 10500 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10501 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10502 } 10503 } 10504 return SDValue(); 10505 } 10506 10507 SDValue SITargetLowering::performSubCombine(SDNode *N, 10508 DAGCombinerInfo &DCI) const { 10509 SelectionDAG &DAG = DCI.DAG; 10510 EVT VT = N->getValueType(0); 10511 10512 if (VT != MVT::i32) 10513 return SDValue(); 10514 10515 SDLoc SL(N); 10516 SDValue LHS = N->getOperand(0); 10517 SDValue RHS = N->getOperand(1); 10518 10519 // sub x, zext (setcc) => subcarry x, 0, setcc 10520 // sub x, sext (setcc) => addcarry x, 0, setcc 10521 unsigned Opc = RHS.getOpcode(); 10522 switch (Opc) { 10523 default: break; 10524 case ISD::ZERO_EXTEND: 10525 case ISD::SIGN_EXTEND: 10526 case ISD::ANY_EXTEND: { 10527 auto Cond = RHS.getOperand(0); 10528 // If this won't be a real VOPC output, we would still need to insert an 10529 // extra instruction anyway. 10530 if (!isBoolSGPR(Cond)) 10531 break; 10532 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10533 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10534 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10535 return DAG.getNode(Opc, SL, VTList, Args); 10536 } 10537 } 10538 10539 if (LHS.getOpcode() == ISD::SUBCARRY) { 10540 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10541 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10542 if (!C || !C->isZero()) 10543 return SDValue(); 10544 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10545 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10546 } 10547 return SDValue(); 10548 } 10549 10550 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10551 DAGCombinerInfo &DCI) const { 10552 10553 if (N->getValueType(0) != MVT::i32) 10554 return SDValue(); 10555 10556 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10557 if (!C || C->getZExtValue() != 0) 10558 return SDValue(); 10559 10560 SelectionDAG &DAG = DCI.DAG; 10561 SDValue LHS = N->getOperand(0); 10562 10563 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10564 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10565 unsigned LHSOpc = LHS.getOpcode(); 10566 unsigned Opc = N->getOpcode(); 10567 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10568 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10569 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10570 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10571 } 10572 return SDValue(); 10573 } 10574 10575 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10576 DAGCombinerInfo &DCI) const { 10577 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10578 return SDValue(); 10579 10580 SelectionDAG &DAG = DCI.DAG; 10581 EVT VT = N->getValueType(0); 10582 10583 SDLoc SL(N); 10584 SDValue LHS = N->getOperand(0); 10585 SDValue RHS = N->getOperand(1); 10586 10587 // These should really be instruction patterns, but writing patterns with 10588 // source modiifiers is a pain. 10589 10590 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10591 if (LHS.getOpcode() == ISD::FADD) { 10592 SDValue A = LHS.getOperand(0); 10593 if (A == LHS.getOperand(1)) { 10594 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10595 if (FusedOp != 0) { 10596 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10597 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10598 } 10599 } 10600 } 10601 10602 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10603 if (RHS.getOpcode() == ISD::FADD) { 10604 SDValue A = RHS.getOperand(0); 10605 if (A == RHS.getOperand(1)) { 10606 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10607 if (FusedOp != 0) { 10608 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10609 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10610 } 10611 } 10612 } 10613 10614 return SDValue(); 10615 } 10616 10617 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10618 DAGCombinerInfo &DCI) const { 10619 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10620 return SDValue(); 10621 10622 SelectionDAG &DAG = DCI.DAG; 10623 SDLoc SL(N); 10624 EVT VT = N->getValueType(0); 10625 assert(!VT.isVector()); 10626 10627 // Try to get the fneg to fold into the source modifier. This undoes generic 10628 // DAG combines and folds them into the mad. 10629 // 10630 // Only do this if we are not trying to support denormals. v_mad_f32 does 10631 // not support denormals ever. 10632 SDValue LHS = N->getOperand(0); 10633 SDValue RHS = N->getOperand(1); 10634 if (LHS.getOpcode() == ISD::FADD) { 10635 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10636 SDValue A = LHS.getOperand(0); 10637 if (A == LHS.getOperand(1)) { 10638 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10639 if (FusedOp != 0){ 10640 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10641 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10642 10643 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10644 } 10645 } 10646 } 10647 10648 if (RHS.getOpcode() == ISD::FADD) { 10649 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10650 10651 SDValue A = RHS.getOperand(0); 10652 if (A == RHS.getOperand(1)) { 10653 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10654 if (FusedOp != 0){ 10655 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10656 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10657 } 10658 } 10659 } 10660 10661 return SDValue(); 10662 } 10663 10664 SDValue SITargetLowering::performFMACombine(SDNode *N, 10665 DAGCombinerInfo &DCI) const { 10666 SelectionDAG &DAG = DCI.DAG; 10667 EVT VT = N->getValueType(0); 10668 SDLoc SL(N); 10669 10670 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10671 return SDValue(); 10672 10673 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10674 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10675 SDValue Op1 = N->getOperand(0); 10676 SDValue Op2 = N->getOperand(1); 10677 SDValue FMA = N->getOperand(2); 10678 10679 if (FMA.getOpcode() != ISD::FMA || 10680 Op1.getOpcode() != ISD::FP_EXTEND || 10681 Op2.getOpcode() != ISD::FP_EXTEND) 10682 return SDValue(); 10683 10684 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10685 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10686 // is sufficient to allow generaing fdot2. 10687 const TargetOptions &Options = DAG.getTarget().Options; 10688 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10689 (N->getFlags().hasAllowContract() && 10690 FMA->getFlags().hasAllowContract())) { 10691 Op1 = Op1.getOperand(0); 10692 Op2 = Op2.getOperand(0); 10693 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10694 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10695 return SDValue(); 10696 10697 SDValue Vec1 = Op1.getOperand(0); 10698 SDValue Idx1 = Op1.getOperand(1); 10699 SDValue Vec2 = Op2.getOperand(0); 10700 10701 SDValue FMAOp1 = FMA.getOperand(0); 10702 SDValue FMAOp2 = FMA.getOperand(1); 10703 SDValue FMAAcc = FMA.getOperand(2); 10704 10705 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10706 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10707 return SDValue(); 10708 10709 FMAOp1 = FMAOp1.getOperand(0); 10710 FMAOp2 = FMAOp2.getOperand(0); 10711 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10712 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10713 return SDValue(); 10714 10715 SDValue Vec3 = FMAOp1.getOperand(0); 10716 SDValue Vec4 = FMAOp2.getOperand(0); 10717 SDValue Idx2 = FMAOp1.getOperand(1); 10718 10719 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10720 // Idx1 and Idx2 cannot be the same. 10721 Idx1 == Idx2) 10722 return SDValue(); 10723 10724 if (Vec1 == Vec2 || Vec3 == Vec4) 10725 return SDValue(); 10726 10727 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10728 return SDValue(); 10729 10730 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10731 (Vec1 == Vec4 && Vec2 == Vec3)) { 10732 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10733 DAG.getTargetConstant(0, SL, MVT::i1)); 10734 } 10735 } 10736 return SDValue(); 10737 } 10738 10739 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10740 DAGCombinerInfo &DCI) const { 10741 SelectionDAG &DAG = DCI.DAG; 10742 SDLoc SL(N); 10743 10744 SDValue LHS = N->getOperand(0); 10745 SDValue RHS = N->getOperand(1); 10746 EVT VT = LHS.getValueType(); 10747 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10748 10749 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10750 if (!CRHS) { 10751 CRHS = dyn_cast<ConstantSDNode>(LHS); 10752 if (CRHS) { 10753 std::swap(LHS, RHS); 10754 CC = getSetCCSwappedOperands(CC); 10755 } 10756 } 10757 10758 if (CRHS) { 10759 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10760 isBoolSGPR(LHS.getOperand(0))) { 10761 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10762 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10763 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10764 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10765 if ((CRHS->isAllOnes() && 10766 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10767 (CRHS->isZero() && 10768 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10769 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10770 DAG.getConstant(-1, SL, MVT::i1)); 10771 if ((CRHS->isAllOnes() && 10772 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10773 (CRHS->isZero() && 10774 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10775 return LHS.getOperand(0); 10776 } 10777 10778 uint64_t CRHSVal = CRHS->getZExtValue(); 10779 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10780 LHS.getOpcode() == ISD::SELECT && 10781 isa<ConstantSDNode>(LHS.getOperand(1)) && 10782 isa<ConstantSDNode>(LHS.getOperand(2)) && 10783 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10784 isBoolSGPR(LHS.getOperand(0))) { 10785 // Given CT != FT: 10786 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10787 // setcc (select cc, CT, CF), CF, ne => cc 10788 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10789 // setcc (select cc, CT, CF), CT, eq => cc 10790 uint64_t CT = LHS.getConstantOperandVal(1); 10791 uint64_t CF = LHS.getConstantOperandVal(2); 10792 10793 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10794 (CT == CRHSVal && CC == ISD::SETNE)) 10795 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10796 DAG.getConstant(-1, SL, MVT::i1)); 10797 if ((CF == CRHSVal && CC == ISD::SETNE) || 10798 (CT == CRHSVal && CC == ISD::SETEQ)) 10799 return LHS.getOperand(0); 10800 } 10801 } 10802 10803 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10804 VT != MVT::f16)) 10805 return SDValue(); 10806 10807 // Match isinf/isfinite pattern 10808 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10809 // (fcmp one (fabs x), inf) -> (fp_class x, 10810 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10811 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10812 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10813 if (!CRHS) 10814 return SDValue(); 10815 10816 const APFloat &APF = CRHS->getValueAPF(); 10817 if (APF.isInfinity() && !APF.isNegative()) { 10818 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10819 SIInstrFlags::N_INFINITY; 10820 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10821 SIInstrFlags::P_ZERO | 10822 SIInstrFlags::N_NORMAL | 10823 SIInstrFlags::P_NORMAL | 10824 SIInstrFlags::N_SUBNORMAL | 10825 SIInstrFlags::P_SUBNORMAL; 10826 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10827 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10828 DAG.getConstant(Mask, SL, MVT::i32)); 10829 } 10830 } 10831 10832 return SDValue(); 10833 } 10834 10835 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10836 DAGCombinerInfo &DCI) const { 10837 SelectionDAG &DAG = DCI.DAG; 10838 SDLoc SL(N); 10839 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10840 10841 SDValue Src = N->getOperand(0); 10842 SDValue Shift = N->getOperand(0); 10843 10844 // TODO: Extend type shouldn't matter (assuming legal types). 10845 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10846 Shift = Shift.getOperand(0); 10847 10848 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10849 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10850 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10851 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10852 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10853 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10854 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10855 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10856 SDLoc(Shift.getOperand(0)), MVT::i32); 10857 10858 unsigned ShiftOffset = 8 * Offset; 10859 if (Shift.getOpcode() == ISD::SHL) 10860 ShiftOffset -= C->getZExtValue(); 10861 else 10862 ShiftOffset += C->getZExtValue(); 10863 10864 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10865 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10866 MVT::f32, Shift); 10867 } 10868 } 10869 } 10870 10871 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10872 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10873 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10874 // We simplified Src. If this node is not dead, visit it again so it is 10875 // folded properly. 10876 if (N->getOpcode() != ISD::DELETED_NODE) 10877 DCI.AddToWorklist(N); 10878 return SDValue(N, 0); 10879 } 10880 10881 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10882 if (SDValue DemandedSrc = 10883 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10884 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10885 10886 return SDValue(); 10887 } 10888 10889 SDValue SITargetLowering::performClampCombine(SDNode *N, 10890 DAGCombinerInfo &DCI) const { 10891 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10892 if (!CSrc) 10893 return SDValue(); 10894 10895 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10896 const APFloat &F = CSrc->getValueAPF(); 10897 APFloat Zero = APFloat::getZero(F.getSemantics()); 10898 if (F < Zero || 10899 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10900 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10901 } 10902 10903 APFloat One(F.getSemantics(), "1.0"); 10904 if (F > One) 10905 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10906 10907 return SDValue(CSrc, 0); 10908 } 10909 10910 10911 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10912 DAGCombinerInfo &DCI) const { 10913 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10914 return SDValue(); 10915 switch (N->getOpcode()) { 10916 case ISD::ADD: 10917 return performAddCombine(N, DCI); 10918 case ISD::SUB: 10919 return performSubCombine(N, DCI); 10920 case ISD::ADDCARRY: 10921 case ISD::SUBCARRY: 10922 return performAddCarrySubCarryCombine(N, DCI); 10923 case ISD::FADD: 10924 return performFAddCombine(N, DCI); 10925 case ISD::FSUB: 10926 return performFSubCombine(N, DCI); 10927 case ISD::SETCC: 10928 return performSetCCCombine(N, DCI); 10929 case ISD::FMAXNUM: 10930 case ISD::FMINNUM: 10931 case ISD::FMAXNUM_IEEE: 10932 case ISD::FMINNUM_IEEE: 10933 case ISD::SMAX: 10934 case ISD::SMIN: 10935 case ISD::UMAX: 10936 case ISD::UMIN: 10937 case AMDGPUISD::FMIN_LEGACY: 10938 case AMDGPUISD::FMAX_LEGACY: 10939 return performMinMaxCombine(N, DCI); 10940 case ISD::FMA: 10941 return performFMACombine(N, DCI); 10942 case ISD::AND: 10943 return performAndCombine(N, DCI); 10944 case ISD::OR: 10945 return performOrCombine(N, DCI); 10946 case ISD::XOR: 10947 return performXorCombine(N, DCI); 10948 case ISD::ZERO_EXTEND: 10949 return performZeroExtendCombine(N, DCI); 10950 case ISD::SIGN_EXTEND_INREG: 10951 return performSignExtendInRegCombine(N , DCI); 10952 case AMDGPUISD::FP_CLASS: 10953 return performClassCombine(N, DCI); 10954 case ISD::FCANONICALIZE: 10955 return performFCanonicalizeCombine(N, DCI); 10956 case AMDGPUISD::RCP: 10957 return performRcpCombine(N, DCI); 10958 case AMDGPUISD::FRACT: 10959 case AMDGPUISD::RSQ: 10960 case AMDGPUISD::RCP_LEGACY: 10961 case AMDGPUISD::RCP_IFLAG: 10962 case AMDGPUISD::RSQ_CLAMP: 10963 case AMDGPUISD::LDEXP: { 10964 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10965 SDValue Src = N->getOperand(0); 10966 if (Src.isUndef()) 10967 return Src; 10968 break; 10969 } 10970 case ISD::SINT_TO_FP: 10971 case ISD::UINT_TO_FP: 10972 return performUCharToFloatCombine(N, DCI); 10973 case AMDGPUISD::CVT_F32_UBYTE0: 10974 case AMDGPUISD::CVT_F32_UBYTE1: 10975 case AMDGPUISD::CVT_F32_UBYTE2: 10976 case AMDGPUISD::CVT_F32_UBYTE3: 10977 return performCvtF32UByteNCombine(N, DCI); 10978 case AMDGPUISD::FMED3: 10979 return performFMed3Combine(N, DCI); 10980 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10981 return performCvtPkRTZCombine(N, DCI); 10982 case AMDGPUISD::CLAMP: 10983 return performClampCombine(N, DCI); 10984 case ISD::SCALAR_TO_VECTOR: { 10985 SelectionDAG &DAG = DCI.DAG; 10986 EVT VT = N->getValueType(0); 10987 10988 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10989 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10990 SDLoc SL(N); 10991 SDValue Src = N->getOperand(0); 10992 EVT EltVT = Src.getValueType(); 10993 if (EltVT == MVT::f16) 10994 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10995 10996 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10997 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10998 } 10999 11000 break; 11001 } 11002 case ISD::EXTRACT_VECTOR_ELT: 11003 return performExtractVectorEltCombine(N, DCI); 11004 case ISD::INSERT_VECTOR_ELT: 11005 return performInsertVectorEltCombine(N, DCI); 11006 case ISD::LOAD: { 11007 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11008 return Widended; 11009 LLVM_FALLTHROUGH; 11010 } 11011 default: { 11012 if (!DCI.isBeforeLegalize()) { 11013 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11014 return performMemSDNodeCombine(MemNode, DCI); 11015 } 11016 11017 break; 11018 } 11019 } 11020 11021 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11022 } 11023 11024 /// Helper function for adjustWritemask 11025 static unsigned SubIdx2Lane(unsigned Idx) { 11026 switch (Idx) { 11027 default: return ~0u; 11028 case AMDGPU::sub0: return 0; 11029 case AMDGPU::sub1: return 1; 11030 case AMDGPU::sub2: return 2; 11031 case AMDGPU::sub3: return 3; 11032 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11033 } 11034 } 11035 11036 /// Adjust the writemask of MIMG instructions 11037 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11038 SelectionDAG &DAG) const { 11039 unsigned Opcode = Node->getMachineOpcode(); 11040 11041 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11042 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11043 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11044 return Node; // not implemented for D16 11045 11046 SDNode *Users[5] = { nullptr }; 11047 unsigned Lane = 0; 11048 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11049 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11050 unsigned NewDmask = 0; 11051 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11052 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11053 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11054 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 11055 unsigned TFCLane = 0; 11056 bool HasChain = Node->getNumValues() > 1; 11057 11058 if (OldDmask == 0) { 11059 // These are folded out, but on the chance it happens don't assert. 11060 return Node; 11061 } 11062 11063 unsigned OldBitsSet = countPopulation(OldDmask); 11064 // Work out which is the TFE/LWE lane if that is enabled. 11065 if (UsesTFC) { 11066 TFCLane = OldBitsSet; 11067 } 11068 11069 // Try to figure out the used register components 11070 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11071 I != E; ++I) { 11072 11073 // Don't look at users of the chain. 11074 if (I.getUse().getResNo() != 0) 11075 continue; 11076 11077 // Abort if we can't understand the usage 11078 if (!I->isMachineOpcode() || 11079 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11080 return Node; 11081 11082 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11083 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11084 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11085 // set, etc. 11086 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11087 if (Lane == ~0u) 11088 return Node; 11089 11090 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11091 if (UsesTFC && Lane == TFCLane) { 11092 Users[Lane] = *I; 11093 } else { 11094 // Set which texture component corresponds to the lane. 11095 unsigned Comp; 11096 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11097 Comp = countTrailingZeros(Dmask); 11098 Dmask &= ~(1 << Comp); 11099 } 11100 11101 // Abort if we have more than one user per component. 11102 if (Users[Lane]) 11103 return Node; 11104 11105 Users[Lane] = *I; 11106 NewDmask |= 1 << Comp; 11107 } 11108 } 11109 11110 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11111 bool NoChannels = !NewDmask; 11112 if (NoChannels) { 11113 if (!UsesTFC) { 11114 // No uses of the result and not using TFC. Then do nothing. 11115 return Node; 11116 } 11117 // If the original dmask has one channel - then nothing to do 11118 if (OldBitsSet == 1) 11119 return Node; 11120 // Use an arbitrary dmask - required for the instruction to work 11121 NewDmask = 1; 11122 } 11123 // Abort if there's no change 11124 if (NewDmask == OldDmask) 11125 return Node; 11126 11127 unsigned BitsSet = countPopulation(NewDmask); 11128 11129 // Check for TFE or LWE - increase the number of channels by one to account 11130 // for the extra return value 11131 // This will need adjustment for D16 if this is also included in 11132 // adjustWriteMask (this function) but at present D16 are excluded. 11133 unsigned NewChannels = BitsSet + UsesTFC; 11134 11135 int NewOpcode = 11136 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11137 assert(NewOpcode != -1 && 11138 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11139 "failed to find equivalent MIMG op"); 11140 11141 // Adjust the writemask in the node 11142 SmallVector<SDValue, 12> Ops; 11143 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11144 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11145 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11146 11147 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11148 11149 MVT ResultVT = NewChannels == 1 ? 11150 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11151 NewChannels == 5 ? 8 : NewChannels); 11152 SDVTList NewVTList = HasChain ? 11153 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11154 11155 11156 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11157 NewVTList, Ops); 11158 11159 if (HasChain) { 11160 // Update chain. 11161 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11162 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11163 } 11164 11165 if (NewChannels == 1) { 11166 assert(Node->hasNUsesOfValue(1, 0)); 11167 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11168 SDLoc(Node), Users[Lane]->getValueType(0), 11169 SDValue(NewNode, 0)); 11170 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11171 return nullptr; 11172 } 11173 11174 // Update the users of the node with the new indices 11175 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11176 SDNode *User = Users[i]; 11177 if (!User) { 11178 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11179 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11180 if (i || !NoChannels) 11181 continue; 11182 } else { 11183 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11184 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11185 } 11186 11187 switch (Idx) { 11188 default: break; 11189 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11190 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11191 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11192 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11193 } 11194 } 11195 11196 DAG.RemoveDeadNode(Node); 11197 return nullptr; 11198 } 11199 11200 static bool isFrameIndexOp(SDValue Op) { 11201 if (Op.getOpcode() == ISD::AssertZext) 11202 Op = Op.getOperand(0); 11203 11204 return isa<FrameIndexSDNode>(Op); 11205 } 11206 11207 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11208 /// with frame index operands. 11209 /// LLVM assumes that inputs are to these instructions are registers. 11210 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11211 SelectionDAG &DAG) const { 11212 if (Node->getOpcode() == ISD::CopyToReg) { 11213 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11214 SDValue SrcVal = Node->getOperand(2); 11215 11216 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11217 // to try understanding copies to physical registers. 11218 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11219 SDLoc SL(Node); 11220 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11221 SDValue VReg = DAG.getRegister( 11222 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11223 11224 SDNode *Glued = Node->getGluedNode(); 11225 SDValue ToVReg 11226 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11227 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11228 SDValue ToResultReg 11229 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11230 VReg, ToVReg.getValue(1)); 11231 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11232 DAG.RemoveDeadNode(Node); 11233 return ToResultReg.getNode(); 11234 } 11235 } 11236 11237 SmallVector<SDValue, 8> Ops; 11238 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11239 if (!isFrameIndexOp(Node->getOperand(i))) { 11240 Ops.push_back(Node->getOperand(i)); 11241 continue; 11242 } 11243 11244 SDLoc DL(Node); 11245 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11246 Node->getOperand(i).getValueType(), 11247 Node->getOperand(i)), 0)); 11248 } 11249 11250 return DAG.UpdateNodeOperands(Node, Ops); 11251 } 11252 11253 /// Fold the instructions after selecting them. 11254 /// Returns null if users were already updated. 11255 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11256 SelectionDAG &DAG) const { 11257 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11258 unsigned Opcode = Node->getMachineOpcode(); 11259 11260 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11261 !TII->isGather4(Opcode) && 11262 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11263 return adjustWritemask(Node, DAG); 11264 } 11265 11266 if (Opcode == AMDGPU::INSERT_SUBREG || 11267 Opcode == AMDGPU::REG_SEQUENCE) { 11268 legalizeTargetIndependentNode(Node, DAG); 11269 return Node; 11270 } 11271 11272 switch (Opcode) { 11273 case AMDGPU::V_DIV_SCALE_F32_e64: 11274 case AMDGPU::V_DIV_SCALE_F64_e64: { 11275 // Satisfy the operand register constraint when one of the inputs is 11276 // undefined. Ordinarily each undef value will have its own implicit_def of 11277 // a vreg, so force these to use a single register. 11278 SDValue Src0 = Node->getOperand(1); 11279 SDValue Src1 = Node->getOperand(3); 11280 SDValue Src2 = Node->getOperand(5); 11281 11282 if ((Src0.isMachineOpcode() && 11283 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11284 (Src0 == Src1 || Src0 == Src2)) 11285 break; 11286 11287 MVT VT = Src0.getValueType().getSimpleVT(); 11288 const TargetRegisterClass *RC = 11289 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11290 11291 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11292 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11293 11294 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11295 UndefReg, Src0, SDValue()); 11296 11297 // src0 must be the same register as src1 or src2, even if the value is 11298 // undefined, so make sure we don't violate this constraint. 11299 if (Src0.isMachineOpcode() && 11300 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11301 if (Src1.isMachineOpcode() && 11302 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11303 Src0 = Src1; 11304 else if (Src2.isMachineOpcode() && 11305 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11306 Src0 = Src2; 11307 else { 11308 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11309 Src0 = UndefReg; 11310 Src1 = UndefReg; 11311 } 11312 } else 11313 break; 11314 11315 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11316 Ops[1] = Src0; 11317 Ops[3] = Src1; 11318 Ops[5] = Src2; 11319 Ops.push_back(ImpDef.getValue(1)); 11320 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11321 } 11322 default: 11323 break; 11324 } 11325 11326 return Node; 11327 } 11328 11329 // Any MIMG instructions that use tfe or lwe require an initialization of the 11330 // result register that will be written in the case of a memory access failure. 11331 // The required code is also added to tie this init code to the result of the 11332 // img instruction. 11333 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11334 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11335 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11336 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11337 MachineBasicBlock &MBB = *MI.getParent(); 11338 11339 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11340 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11341 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11342 11343 if (!TFE && !LWE) // intersect_ray 11344 return; 11345 11346 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11347 unsigned LWEVal = LWE->getImm(); 11348 unsigned D16Val = D16 ? D16->getImm() : 0; 11349 11350 if (!TFEVal && !LWEVal) 11351 return; 11352 11353 // At least one of TFE or LWE are non-zero 11354 // We have to insert a suitable initialization of the result value and 11355 // tie this to the dest of the image instruction. 11356 11357 const DebugLoc &DL = MI.getDebugLoc(); 11358 11359 int DstIdx = 11360 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11361 11362 // Calculate which dword we have to initialize to 0. 11363 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11364 11365 // check that dmask operand is found. 11366 assert(MO_Dmask && "Expected dmask operand in instruction"); 11367 11368 unsigned dmask = MO_Dmask->getImm(); 11369 // Determine the number of active lanes taking into account the 11370 // Gather4 special case 11371 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11372 11373 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11374 11375 unsigned InitIdx = 11376 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11377 11378 // Abandon attempt if the dst size isn't large enough 11379 // - this is in fact an error but this is picked up elsewhere and 11380 // reported correctly. 11381 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11382 if (DstSize < InitIdx) 11383 return; 11384 11385 // Create a register for the intialization value. 11386 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11387 unsigned NewDst = 0; // Final initialized value will be in here 11388 11389 // If PRTStrictNull feature is enabled (the default) then initialize 11390 // all the result registers to 0, otherwise just the error indication 11391 // register (VGPRn+1) 11392 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11393 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11394 11395 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11396 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11397 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11398 // Initialize dword 11399 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11400 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11401 .addImm(0); 11402 // Insert into the super-reg 11403 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11404 .addReg(PrevDst) 11405 .addReg(SubReg) 11406 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11407 11408 PrevDst = NewDst; 11409 } 11410 11411 // Add as an implicit operand 11412 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11413 11414 // Tie the just added implicit operand to the dst 11415 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11416 } 11417 11418 /// Assign the register class depending on the number of 11419 /// bits set in the writemask 11420 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11421 SDNode *Node) const { 11422 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11423 11424 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11425 11426 if (TII->isVOP3(MI.getOpcode())) { 11427 // Make sure constant bus requirements are respected. 11428 TII->legalizeOperandsVOP3(MRI, MI); 11429 11430 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11431 // This saves a chain-copy of registers and better ballance register 11432 // use between vgpr and agpr as agpr tuples tend to be big. 11433 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11434 unsigned Opc = MI.getOpcode(); 11435 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11436 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11437 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11438 if (I == -1) 11439 break; 11440 MachineOperand &Op = MI.getOperand(I); 11441 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11442 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11443 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11444 continue; 11445 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11446 if (!Src || !Src->isCopy() || 11447 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11448 continue; 11449 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11450 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11451 // All uses of agpr64 and agpr32 can also accept vgpr except for 11452 // v_accvgpr_read, but we do not produce agpr reads during selection, 11453 // so no use checks are needed. 11454 MRI.setRegClass(Op.getReg(), NewRC); 11455 } 11456 } 11457 11458 return; 11459 } 11460 11461 // Replace unused atomics with the no return version. 11462 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11463 if (NoRetAtomicOp != -1) { 11464 if (!Node->hasAnyUseOfValue(0)) { 11465 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11466 AMDGPU::OpName::cpol); 11467 if (CPolIdx != -1) { 11468 MachineOperand &CPol = MI.getOperand(CPolIdx); 11469 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11470 } 11471 MI.RemoveOperand(0); 11472 MI.setDesc(TII->get(NoRetAtomicOp)); 11473 return; 11474 } 11475 11476 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11477 // instruction, because the return type of these instructions is a vec2 of 11478 // the memory type, so it can be tied to the input operand. 11479 // This means these instructions always have a use, so we need to add a 11480 // special case to check if the atomic has only one extract_subreg use, 11481 // which itself has no uses. 11482 if ((Node->hasNUsesOfValue(1, 0) && 11483 Node->use_begin()->isMachineOpcode() && 11484 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11485 !Node->use_begin()->hasAnyUseOfValue(0))) { 11486 Register Def = MI.getOperand(0).getReg(); 11487 11488 // Change this into a noret atomic. 11489 MI.setDesc(TII->get(NoRetAtomicOp)); 11490 MI.RemoveOperand(0); 11491 11492 // If we only remove the def operand from the atomic instruction, the 11493 // extract_subreg will be left with a use of a vreg without a def. 11494 // So we need to insert an implicit_def to avoid machine verifier 11495 // errors. 11496 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11497 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11498 } 11499 return; 11500 } 11501 11502 if (TII->isMIMG(MI) && !MI.mayStore()) 11503 AddIMGInit(MI); 11504 } 11505 11506 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11507 uint64_t Val) { 11508 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11509 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11510 } 11511 11512 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11513 const SDLoc &DL, 11514 SDValue Ptr) const { 11515 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11516 11517 // Build the half of the subregister with the constants before building the 11518 // full 128-bit register. If we are building multiple resource descriptors, 11519 // this will allow CSEing of the 2-component register. 11520 const SDValue Ops0[] = { 11521 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11522 buildSMovImm32(DAG, DL, 0), 11523 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11524 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11525 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11526 }; 11527 11528 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11529 MVT::v2i32, Ops0), 0); 11530 11531 // Combine the constants and the pointer. 11532 const SDValue Ops1[] = { 11533 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11534 Ptr, 11535 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11536 SubRegHi, 11537 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11538 }; 11539 11540 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11541 } 11542 11543 /// Return a resource descriptor with the 'Add TID' bit enabled 11544 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11545 /// of the resource descriptor) to create an offset, which is added to 11546 /// the resource pointer. 11547 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11548 SDValue Ptr, uint32_t RsrcDword1, 11549 uint64_t RsrcDword2And3) const { 11550 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11551 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11552 if (RsrcDword1) { 11553 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11554 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11555 0); 11556 } 11557 11558 SDValue DataLo = buildSMovImm32(DAG, DL, 11559 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11560 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11561 11562 const SDValue Ops[] = { 11563 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11564 PtrLo, 11565 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11566 PtrHi, 11567 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11568 DataLo, 11569 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11570 DataHi, 11571 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11572 }; 11573 11574 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11575 } 11576 11577 //===----------------------------------------------------------------------===// 11578 // SI Inline Assembly Support 11579 //===----------------------------------------------------------------------===// 11580 11581 std::pair<unsigned, const TargetRegisterClass *> 11582 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11583 StringRef Constraint, 11584 MVT VT) const { 11585 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11586 11587 const TargetRegisterClass *RC = nullptr; 11588 if (Constraint.size() == 1) { 11589 const unsigned BitWidth = VT.getSizeInBits(); 11590 switch (Constraint[0]) { 11591 default: 11592 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11593 case 's': 11594 case 'r': 11595 switch (BitWidth) { 11596 case 16: 11597 RC = &AMDGPU::SReg_32RegClass; 11598 break; 11599 case 64: 11600 RC = &AMDGPU::SGPR_64RegClass; 11601 break; 11602 default: 11603 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11604 if (!RC) 11605 return std::make_pair(0U, nullptr); 11606 break; 11607 } 11608 break; 11609 case 'v': 11610 switch (BitWidth) { 11611 case 16: 11612 RC = &AMDGPU::VGPR_32RegClass; 11613 break; 11614 default: 11615 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11616 if (!RC) 11617 return std::make_pair(0U, nullptr); 11618 break; 11619 } 11620 break; 11621 case 'a': 11622 if (!Subtarget->hasMAIInsts()) 11623 break; 11624 switch (BitWidth) { 11625 case 16: 11626 RC = &AMDGPU::AGPR_32RegClass; 11627 break; 11628 default: 11629 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11630 if (!RC) 11631 return std::make_pair(0U, nullptr); 11632 break; 11633 } 11634 break; 11635 } 11636 // We actually support i128, i16 and f16 as inline parameters 11637 // even if they are not reported as legal 11638 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11639 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11640 return std::make_pair(0U, RC); 11641 } 11642 11643 if (Constraint.size() > 1) { 11644 if (Constraint[1] == 'v') { 11645 RC = &AMDGPU::VGPR_32RegClass; 11646 } else if (Constraint[1] == 's') { 11647 RC = &AMDGPU::SGPR_32RegClass; 11648 } else if (Constraint[1] == 'a') { 11649 RC = &AMDGPU::AGPR_32RegClass; 11650 } 11651 11652 if (RC) { 11653 uint32_t Idx; 11654 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11655 if (!Failed && Idx < RC->getNumRegs()) 11656 return std::make_pair(RC->getRegister(Idx), RC); 11657 } 11658 } 11659 11660 // FIXME: Returns VS_32 for physical SGPR constraints 11661 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11662 } 11663 11664 static bool isImmConstraint(StringRef Constraint) { 11665 if (Constraint.size() == 1) { 11666 switch (Constraint[0]) { 11667 default: break; 11668 case 'I': 11669 case 'J': 11670 case 'A': 11671 case 'B': 11672 case 'C': 11673 return true; 11674 } 11675 } else if (Constraint == "DA" || 11676 Constraint == "DB") { 11677 return true; 11678 } 11679 return false; 11680 } 11681 11682 SITargetLowering::ConstraintType 11683 SITargetLowering::getConstraintType(StringRef Constraint) const { 11684 if (Constraint.size() == 1) { 11685 switch (Constraint[0]) { 11686 default: break; 11687 case 's': 11688 case 'v': 11689 case 'a': 11690 return C_RegisterClass; 11691 } 11692 } 11693 if (isImmConstraint(Constraint)) { 11694 return C_Other; 11695 } 11696 return TargetLowering::getConstraintType(Constraint); 11697 } 11698 11699 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11700 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11701 Val = Val & maskTrailingOnes<uint64_t>(Size); 11702 } 11703 return Val; 11704 } 11705 11706 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11707 std::string &Constraint, 11708 std::vector<SDValue> &Ops, 11709 SelectionDAG &DAG) const { 11710 if (isImmConstraint(Constraint)) { 11711 uint64_t Val; 11712 if (getAsmOperandConstVal(Op, Val) && 11713 checkAsmConstraintVal(Op, Constraint, Val)) { 11714 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11715 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11716 } 11717 } else { 11718 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11719 } 11720 } 11721 11722 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11723 unsigned Size = Op.getScalarValueSizeInBits(); 11724 if (Size > 64) 11725 return false; 11726 11727 if (Size == 16 && !Subtarget->has16BitInsts()) 11728 return false; 11729 11730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11731 Val = C->getSExtValue(); 11732 return true; 11733 } 11734 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11735 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11736 return true; 11737 } 11738 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11739 if (Size != 16 || Op.getNumOperands() != 2) 11740 return false; 11741 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11742 return false; 11743 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11744 Val = C->getSExtValue(); 11745 return true; 11746 } 11747 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11748 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11749 return true; 11750 } 11751 } 11752 11753 return false; 11754 } 11755 11756 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11757 const std::string &Constraint, 11758 uint64_t Val) const { 11759 if (Constraint.size() == 1) { 11760 switch (Constraint[0]) { 11761 case 'I': 11762 return AMDGPU::isInlinableIntLiteral(Val); 11763 case 'J': 11764 return isInt<16>(Val); 11765 case 'A': 11766 return checkAsmConstraintValA(Op, Val); 11767 case 'B': 11768 return isInt<32>(Val); 11769 case 'C': 11770 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11771 AMDGPU::isInlinableIntLiteral(Val); 11772 default: 11773 break; 11774 } 11775 } else if (Constraint.size() == 2) { 11776 if (Constraint == "DA") { 11777 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11778 int64_t LoBits = static_cast<int32_t>(Val); 11779 return checkAsmConstraintValA(Op, HiBits, 32) && 11780 checkAsmConstraintValA(Op, LoBits, 32); 11781 } 11782 if (Constraint == "DB") { 11783 return true; 11784 } 11785 } 11786 llvm_unreachable("Invalid asm constraint"); 11787 } 11788 11789 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11790 uint64_t Val, 11791 unsigned MaxSize) const { 11792 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11793 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11794 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11795 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11796 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11797 return true; 11798 } 11799 return false; 11800 } 11801 11802 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11803 switch (UnalignedClassID) { 11804 case AMDGPU::VReg_64RegClassID: 11805 return AMDGPU::VReg_64_Align2RegClassID; 11806 case AMDGPU::VReg_96RegClassID: 11807 return AMDGPU::VReg_96_Align2RegClassID; 11808 case AMDGPU::VReg_128RegClassID: 11809 return AMDGPU::VReg_128_Align2RegClassID; 11810 case AMDGPU::VReg_160RegClassID: 11811 return AMDGPU::VReg_160_Align2RegClassID; 11812 case AMDGPU::VReg_192RegClassID: 11813 return AMDGPU::VReg_192_Align2RegClassID; 11814 case AMDGPU::VReg_224RegClassID: 11815 return AMDGPU::VReg_224_Align2RegClassID; 11816 case AMDGPU::VReg_256RegClassID: 11817 return AMDGPU::VReg_256_Align2RegClassID; 11818 case AMDGPU::VReg_512RegClassID: 11819 return AMDGPU::VReg_512_Align2RegClassID; 11820 case AMDGPU::VReg_1024RegClassID: 11821 return AMDGPU::VReg_1024_Align2RegClassID; 11822 case AMDGPU::AReg_64RegClassID: 11823 return AMDGPU::AReg_64_Align2RegClassID; 11824 case AMDGPU::AReg_96RegClassID: 11825 return AMDGPU::AReg_96_Align2RegClassID; 11826 case AMDGPU::AReg_128RegClassID: 11827 return AMDGPU::AReg_128_Align2RegClassID; 11828 case AMDGPU::AReg_160RegClassID: 11829 return AMDGPU::AReg_160_Align2RegClassID; 11830 case AMDGPU::AReg_192RegClassID: 11831 return AMDGPU::AReg_192_Align2RegClassID; 11832 case AMDGPU::AReg_256RegClassID: 11833 return AMDGPU::AReg_256_Align2RegClassID; 11834 case AMDGPU::AReg_512RegClassID: 11835 return AMDGPU::AReg_512_Align2RegClassID; 11836 case AMDGPU::AReg_1024RegClassID: 11837 return AMDGPU::AReg_1024_Align2RegClassID; 11838 default: 11839 return -1; 11840 } 11841 } 11842 11843 // Figure out which registers should be reserved for stack access. Only after 11844 // the function is legalized do we know all of the non-spill stack objects or if 11845 // calls are present. 11846 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11847 MachineRegisterInfo &MRI = MF.getRegInfo(); 11848 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11849 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11850 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11851 const SIInstrInfo *TII = ST.getInstrInfo(); 11852 11853 if (Info->isEntryFunction()) { 11854 // Callable functions have fixed registers used for stack access. 11855 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11856 } 11857 11858 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11859 Info->getStackPtrOffsetReg())); 11860 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11861 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11862 11863 // We need to worry about replacing the default register with itself in case 11864 // of MIR testcases missing the MFI. 11865 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11866 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11867 11868 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11869 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11870 11871 Info->limitOccupancy(MF); 11872 11873 if (ST.isWave32() && !MF.empty()) { 11874 for (auto &MBB : MF) { 11875 for (auto &MI : MBB) { 11876 TII->fixImplicitOperands(MI); 11877 } 11878 } 11879 } 11880 11881 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11882 // classes if required. Ideally the register class constraints would differ 11883 // per-subtarget, but there's no easy way to achieve that right now. This is 11884 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11885 // from using them as the register class for legal types. 11886 if (ST.needsAlignedVGPRs()) { 11887 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11888 const Register Reg = Register::index2VirtReg(I); 11889 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11890 if (!RC) 11891 continue; 11892 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11893 if (NewClassID != -1) 11894 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11895 } 11896 } 11897 11898 TargetLoweringBase::finalizeLowering(MF); 11899 11900 // Allocate a VGPR for future SGPR Spill if 11901 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11902 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11903 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11904 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11905 Info->reserveVGPRforSGPRSpills(MF); 11906 } 11907 11908 void SITargetLowering::computeKnownBitsForFrameIndex( 11909 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11910 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11911 11912 // Set the high bits to zero based on the maximum allowed scratch size per 11913 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11914 // calculation won't overflow, so assume the sign bit is never set. 11915 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11916 } 11917 11918 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11919 KnownBits &Known, unsigned Dim) { 11920 unsigned MaxValue = 11921 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11922 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11923 } 11924 11925 void SITargetLowering::computeKnownBitsForTargetInstr( 11926 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11927 const MachineRegisterInfo &MRI, unsigned Depth) const { 11928 const MachineInstr *MI = MRI.getVRegDef(R); 11929 switch (MI->getOpcode()) { 11930 case AMDGPU::G_INTRINSIC: { 11931 switch (MI->getIntrinsicID()) { 11932 case Intrinsic::amdgcn_workitem_id_x: 11933 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11934 break; 11935 case Intrinsic::amdgcn_workitem_id_y: 11936 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11937 break; 11938 case Intrinsic::amdgcn_workitem_id_z: 11939 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11940 break; 11941 case Intrinsic::amdgcn_mbcnt_lo: 11942 case Intrinsic::amdgcn_mbcnt_hi: { 11943 // These return at most the wavefront size - 1. 11944 unsigned Size = MRI.getType(R).getSizeInBits(); 11945 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11946 break; 11947 } 11948 case Intrinsic::amdgcn_groupstaticsize: { 11949 // We can report everything over the maximum size as 0. We can't report 11950 // based on the actual size because we don't know if it's accurate or not 11951 // at any given point. 11952 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11953 break; 11954 } 11955 } 11956 break; 11957 } 11958 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11959 Known.Zero.setHighBits(24); 11960 break; 11961 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11962 Known.Zero.setHighBits(16); 11963 break; 11964 } 11965 } 11966 11967 Align SITargetLowering::computeKnownAlignForTargetInstr( 11968 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11969 unsigned Depth) const { 11970 const MachineInstr *MI = MRI.getVRegDef(R); 11971 switch (MI->getOpcode()) { 11972 case AMDGPU::G_INTRINSIC: 11973 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11974 // FIXME: Can this move to generic code? What about the case where the call 11975 // site specifies a lower alignment? 11976 Intrinsic::ID IID = MI->getIntrinsicID(); 11977 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11978 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11979 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11980 return *RetAlign; 11981 return Align(1); 11982 } 11983 default: 11984 return Align(1); 11985 } 11986 } 11987 11988 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11989 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11990 const Align CacheLineAlign = Align(64); 11991 11992 // Pre-GFX10 target did not benefit from loop alignment 11993 if (!ML || DisableLoopAlignment || 11994 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11995 getSubtarget()->hasInstFwdPrefetchBug()) 11996 return PrefAlign; 11997 11998 // On GFX10 I$ is 4 x 64 bytes cache lines. 11999 // By default prefetcher keeps one cache line behind and reads two ahead. 12000 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12001 // behind and one ahead. 12002 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12003 // If loop fits 64 bytes it always spans no more than two cache lines and 12004 // does not need an alignment. 12005 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12006 // Else if loop is less or equal 192 bytes we need two lines behind. 12007 12008 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12009 const MachineBasicBlock *Header = ML->getHeader(); 12010 if (Header->getAlignment() != PrefAlign) 12011 return Header->getAlignment(); // Already processed. 12012 12013 unsigned LoopSize = 0; 12014 for (const MachineBasicBlock *MBB : ML->blocks()) { 12015 // If inner loop block is aligned assume in average half of the alignment 12016 // size to be added as nops. 12017 if (MBB != Header) 12018 LoopSize += MBB->getAlignment().value() / 2; 12019 12020 for (const MachineInstr &MI : *MBB) { 12021 LoopSize += TII->getInstSizeInBytes(MI); 12022 if (LoopSize > 192) 12023 return PrefAlign; 12024 } 12025 } 12026 12027 if (LoopSize <= 64) 12028 return PrefAlign; 12029 12030 if (LoopSize <= 128) 12031 return CacheLineAlign; 12032 12033 // If any of parent loops is surrounded by prefetch instructions do not 12034 // insert new for inner loop, which would reset parent's settings. 12035 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12036 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12037 auto I = Exit->getFirstNonDebugInstr(); 12038 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12039 return CacheLineAlign; 12040 } 12041 } 12042 12043 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12044 MachineBasicBlock *Exit = ML->getExitBlock(); 12045 12046 if (Pre && Exit) { 12047 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12048 TII->get(AMDGPU::S_INST_PREFETCH)) 12049 .addImm(1); // prefetch 2 lines behind PC 12050 12051 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12052 TII->get(AMDGPU::S_INST_PREFETCH)) 12053 .addImm(2); // prefetch 1 line behind PC 12054 } 12055 12056 return CacheLineAlign; 12057 } 12058 12059 LLVM_ATTRIBUTE_UNUSED 12060 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12061 assert(N->getOpcode() == ISD::CopyFromReg); 12062 do { 12063 // Follow the chain until we find an INLINEASM node. 12064 N = N->getOperand(0).getNode(); 12065 if (N->getOpcode() == ISD::INLINEASM || 12066 N->getOpcode() == ISD::INLINEASM_BR) 12067 return true; 12068 } while (N->getOpcode() == ISD::CopyFromReg); 12069 return false; 12070 } 12071 12072 bool SITargetLowering::isSDNodeSourceOfDivergence( 12073 const SDNode *N, FunctionLoweringInfo *FLI, 12074 LegacyDivergenceAnalysis *KDA) const { 12075 switch (N->getOpcode()) { 12076 case ISD::CopyFromReg: { 12077 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12078 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12079 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12080 Register Reg = R->getReg(); 12081 12082 // FIXME: Why does this need to consider isLiveIn? 12083 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12084 return !TRI->isSGPRReg(MRI, Reg); 12085 12086 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12087 return KDA->isDivergent(V); 12088 12089 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12090 return !TRI->isSGPRReg(MRI, Reg); 12091 } 12092 case ISD::LOAD: { 12093 const LoadSDNode *L = cast<LoadSDNode>(N); 12094 unsigned AS = L->getAddressSpace(); 12095 // A flat load may access private memory. 12096 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12097 } 12098 case ISD::CALLSEQ_END: 12099 return true; 12100 case ISD::INTRINSIC_WO_CHAIN: 12101 return AMDGPU::isIntrinsicSourceOfDivergence( 12102 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12103 case ISD::INTRINSIC_W_CHAIN: 12104 return AMDGPU::isIntrinsicSourceOfDivergence( 12105 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12106 case AMDGPUISD::ATOMIC_CMP_SWAP: 12107 case AMDGPUISD::ATOMIC_INC: 12108 case AMDGPUISD::ATOMIC_DEC: 12109 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12110 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12111 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12112 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12113 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12114 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12115 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12116 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12117 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12118 case AMDGPUISD::BUFFER_ATOMIC_AND: 12119 case AMDGPUISD::BUFFER_ATOMIC_OR: 12120 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12121 case AMDGPUISD::BUFFER_ATOMIC_INC: 12122 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12123 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12124 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12125 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12126 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12127 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12128 // Target-specific read-modify-write atomics are sources of divergence. 12129 return true; 12130 default: 12131 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12132 // Generic read-modify-write atomics are sources of divergence. 12133 return A->readMem() && A->writeMem(); 12134 } 12135 return false; 12136 } 12137 } 12138 12139 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12140 EVT VT) const { 12141 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12142 case MVT::f32: 12143 return hasFP32Denormals(DAG.getMachineFunction()); 12144 case MVT::f64: 12145 case MVT::f16: 12146 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12147 default: 12148 return false; 12149 } 12150 } 12151 12152 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12153 MachineFunction &MF) const { 12154 switch (Ty.getScalarSizeInBits()) { 12155 case 32: 12156 return hasFP32Denormals(MF); 12157 case 64: 12158 case 16: 12159 return hasFP64FP16Denormals(MF); 12160 default: 12161 return false; 12162 } 12163 } 12164 12165 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12166 const SelectionDAG &DAG, 12167 bool SNaN, 12168 unsigned Depth) const { 12169 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12170 const MachineFunction &MF = DAG.getMachineFunction(); 12171 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12172 12173 if (Info->getMode().DX10Clamp) 12174 return true; // Clamped to 0. 12175 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12176 } 12177 12178 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12179 SNaN, Depth); 12180 } 12181 12182 // Global FP atomic instructions have a hardcoded FP mode and do not support 12183 // FP32 denormals, and only support v2f16 denormals. 12184 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12185 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12186 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12187 if (&Flt == &APFloat::IEEEsingle()) 12188 return DenormMode == DenormalMode::getPreserveSign(); 12189 return DenormMode == DenormalMode::getIEEE(); 12190 } 12191 12192 TargetLowering::AtomicExpansionKind 12193 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12194 12195 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12196 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12197 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12198 SmallVector<StringRef> SSNs; 12199 Ctx.getSyncScopeNames(SSNs); 12200 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12201 ? "system" 12202 : SSNs[RMW->getSyncScopeID()]; 12203 ORE.emit([&]() { 12204 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12205 << "Hardware instruction generated for atomic " 12206 << RMW->getOperationName(RMW->getOperation()) 12207 << " operation at memory scope " << MemScope 12208 << " due to an unsafe request."; 12209 }); 12210 return Kind; 12211 }; 12212 12213 switch (RMW->getOperation()) { 12214 case AtomicRMWInst::FAdd: { 12215 Type *Ty = RMW->getType(); 12216 12217 // We don't have a way to support 16-bit atomics now, so just leave them 12218 // as-is. 12219 if (Ty->isHalfTy()) 12220 return AtomicExpansionKind::None; 12221 12222 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12223 return AtomicExpansionKind::CmpXChg; 12224 12225 unsigned AS = RMW->getPointerAddressSpace(); 12226 12227 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12228 Subtarget->hasAtomicFaddInsts()) { 12229 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12230 // floating point atomic instructions. May generate more efficient code, 12231 // but may not respect rounding and denormal modes, and may give incorrect 12232 // results for certain memory destinations. 12233 if (RMW->getFunction() 12234 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12235 .getValueAsString() != "true") 12236 return AtomicExpansionKind::CmpXChg; 12237 12238 if (Subtarget->hasGFX90AInsts()) { 12239 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12240 return AtomicExpansionKind::CmpXChg; 12241 12242 auto SSID = RMW->getSyncScopeID(); 12243 if (SSID == SyncScope::System || 12244 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12245 return AtomicExpansionKind::CmpXChg; 12246 12247 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12248 } 12249 12250 if (AS == AMDGPUAS::FLAT_ADDRESS) 12251 return AtomicExpansionKind::CmpXChg; 12252 12253 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12254 : AtomicExpansionKind::CmpXChg; 12255 } 12256 12257 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12258 // to round-to-nearest-even. 12259 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12260 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12261 if (!Ty->isDoubleTy()) 12262 return AtomicExpansionKind::None; 12263 12264 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12265 return AtomicExpansionKind::None; 12266 12267 return RMW->getFunction() 12268 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12269 .getValueAsString() == "true" 12270 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12271 : AtomicExpansionKind::CmpXChg; 12272 } 12273 12274 return AtomicExpansionKind::CmpXChg; 12275 } 12276 default: 12277 break; 12278 } 12279 12280 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12281 } 12282 12283 const TargetRegisterClass * 12284 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12285 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12286 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12287 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12288 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12289 : &AMDGPU::SReg_32RegClass; 12290 if (!TRI->isSGPRClass(RC) && !isDivergent) 12291 return TRI->getEquivalentSGPRClass(RC); 12292 else if (TRI->isSGPRClass(RC) && isDivergent) 12293 return TRI->getEquivalentVGPRClass(RC); 12294 12295 return RC; 12296 } 12297 12298 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12299 // uniform values (as produced by the mask results of control flow intrinsics) 12300 // used outside of divergent blocks. The phi users need to also be treated as 12301 // always uniform. 12302 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12303 unsigned WaveSize) { 12304 // FIXME: We asssume we never cast the mask results of a control flow 12305 // intrinsic. 12306 // Early exit if the type won't be consistent as a compile time hack. 12307 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12308 if (!IT || IT->getBitWidth() != WaveSize) 12309 return false; 12310 12311 if (!isa<Instruction>(V)) 12312 return false; 12313 if (!Visited.insert(V).second) 12314 return false; 12315 bool Result = false; 12316 for (auto U : V->users()) { 12317 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12318 if (V == U->getOperand(1)) { 12319 switch (Intrinsic->getIntrinsicID()) { 12320 default: 12321 Result = false; 12322 break; 12323 case Intrinsic::amdgcn_if_break: 12324 case Intrinsic::amdgcn_if: 12325 case Intrinsic::amdgcn_else: 12326 Result = true; 12327 break; 12328 } 12329 } 12330 if (V == U->getOperand(0)) { 12331 switch (Intrinsic->getIntrinsicID()) { 12332 default: 12333 Result = false; 12334 break; 12335 case Intrinsic::amdgcn_end_cf: 12336 case Intrinsic::amdgcn_loop: 12337 Result = true; 12338 break; 12339 } 12340 } 12341 } else { 12342 Result = hasCFUser(U, Visited, WaveSize); 12343 } 12344 if (Result) 12345 break; 12346 } 12347 return Result; 12348 } 12349 12350 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12351 const Value *V) const { 12352 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12353 if (CI->isInlineAsm()) { 12354 // FIXME: This cannot give a correct answer. This should only trigger in 12355 // the case where inline asm returns mixed SGPR and VGPR results, used 12356 // outside the defining block. We don't have a specific result to 12357 // consider, so this assumes if any value is SGPR, the overall register 12358 // also needs to be SGPR. 12359 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12360 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12361 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12362 for (auto &TC : TargetConstraints) { 12363 if (TC.Type == InlineAsm::isOutput) { 12364 ComputeConstraintToUse(TC, SDValue()); 12365 unsigned AssignedReg; 12366 const TargetRegisterClass *RC; 12367 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12368 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12369 if (RC) { 12370 MachineRegisterInfo &MRI = MF.getRegInfo(); 12371 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12372 return true; 12373 else if (SIRI->isSGPRClass(RC)) 12374 return true; 12375 } 12376 } 12377 } 12378 } 12379 } 12380 SmallPtrSet<const Value *, 16> Visited; 12381 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12382 } 12383 12384 std::pair<InstructionCost, MVT> 12385 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12386 Type *Ty) const { 12387 std::pair<InstructionCost, MVT> Cost = 12388 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12389 auto Size = DL.getTypeSizeInBits(Ty); 12390 // Maximum load or store can handle 8 dwords for scalar and 4 for 12391 // vector ALU. Let's assume anything above 8 dwords is expensive 12392 // even if legal. 12393 if (Size <= 256) 12394 return Cost; 12395 12396 Cost.first = (Size + 255) / 256; 12397 return Cost; 12398 } 12399