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/BinaryFormat/ELF.h" 23 #include "llvm/CodeGen/Analysis.h" 24 #include "llvm/CodeGen/FunctionLoweringInfo.h" 25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 26 #include "llvm/CodeGen/MachineLoopInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/IntrinsicsAMDGPU.h" 30 #include "llvm/IR/IntrinsicsR600.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/KnownBits.h" 33 34 using namespace llvm; 35 36 #define DEBUG_TYPE "si-lower" 37 38 STATISTIC(NumTailCalls, "Number of tail calls"); 39 40 static cl::opt<bool> DisableLoopAlignment( 41 "amdgpu-disable-loop-alignment", 42 cl::desc("Do not align and prefetch loops"), 43 cl::init(false)); 44 45 static cl::opt<bool> VGPRReserveforSGPRSpill( 46 "amdgpu-reserve-vgpr-for-sgpr-spill", 47 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 48 49 static cl::opt<bool> UseDivergentRegisterIndexing( 50 "amdgpu-use-divergent-register-indexing", 51 cl::Hidden, 52 cl::desc("Use indirect register addressing for divergent indexes"), 53 cl::init(false)); 54 55 static bool hasFP32Denormals(const MachineFunction &MF) { 56 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 57 return Info->getMode().allFP32Denormals(); 58 } 59 60 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 61 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 62 return Info->getMode().allFP64FP16Denormals(); 63 } 64 65 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 66 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 67 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 68 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 69 return AMDGPU::SGPR0 + Reg; 70 } 71 } 72 llvm_unreachable("Cannot allocate sgpr"); 73 } 74 75 SITargetLowering::SITargetLowering(const TargetMachine &TM, 76 const GCNSubtarget &STI) 77 : AMDGPUTargetLowering(TM, STI), 78 Subtarget(&STI) { 79 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 80 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 81 82 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 83 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 84 85 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 86 87 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 88 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 89 90 addRegisterClass(MVT::f64, V64RegClass); 91 addRegisterClass(MVT::v2f32, V64RegClass); 92 93 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 94 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 95 96 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 97 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 98 99 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 100 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 101 102 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 103 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 104 105 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 106 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 107 108 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 109 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 110 111 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 112 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 113 114 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 115 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 116 117 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 118 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 119 120 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 121 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 122 123 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 124 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 125 126 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 127 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 128 129 if (Subtarget->has16BitInsts()) { 130 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 132 133 // Unless there are also VOP3P operations, not operations are really legal. 134 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 135 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 137 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 138 } 139 140 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 141 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 142 143 computeRegisterProperties(Subtarget->getRegisterInfo()); 144 145 // The boolean content concept here is too inflexible. Compares only ever 146 // really produce a 1-bit result. Any copy/extend from these will turn into a 147 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 148 // it's what most targets use. 149 setBooleanContents(ZeroOrOneBooleanContent); 150 setBooleanVectorContents(ZeroOrOneBooleanContent); 151 152 // We need to custom lower vector stores from local memory 153 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::i1, Custom); 162 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 163 164 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 165 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 166 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 172 setOperationAction(ISD::STORE, MVT::i1, Custom); 173 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 174 175 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 176 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 177 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 178 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 179 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 180 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 181 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 182 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 183 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 184 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 185 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 186 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 187 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 188 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 189 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 190 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 191 192 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 193 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 194 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 195 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 196 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 198 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 199 200 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 201 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 202 203 setOperationAction(ISD::SELECT, MVT::i1, Promote); 204 setOperationAction(ISD::SELECT, MVT::i64, Custom); 205 setOperationAction(ISD::SELECT, MVT::f64, Promote); 206 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 207 208 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 209 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 210 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 213 214 setOperationAction(ISD::SETCC, MVT::i1, Promote); 215 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 216 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 217 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 218 219 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 220 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 221 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 235 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 244 245 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 246 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 247 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 248 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 249 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 251 252 setOperationAction(ISD::UADDO, MVT::i32, Legal); 253 setOperationAction(ISD::USUBO, MVT::i32, Legal); 254 255 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 257 258 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 259 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 260 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 261 262 #if 0 263 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 264 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 265 #endif 266 267 // We only support LOAD/STORE and vector manipulation ops for vectors 268 // with > 4 elements. 269 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 270 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 271 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 272 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 273 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 274 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 275 switch (Op) { 276 case ISD::LOAD: 277 case ISD::STORE: 278 case ISD::BUILD_VECTOR: 279 case ISD::BITCAST: 280 case ISD::EXTRACT_VECTOR_ELT: 281 case ISD::INSERT_VECTOR_ELT: 282 case ISD::INSERT_SUBVECTOR: 283 case ISD::EXTRACT_SUBVECTOR: 284 case ISD::SCALAR_TO_VECTOR: 285 break; 286 case ISD::CONCAT_VECTORS: 287 setOperationAction(Op, VT, Custom); 288 break; 289 default: 290 setOperationAction(Op, VT, Expand); 291 break; 292 } 293 } 294 } 295 296 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 297 298 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 299 // is expanded to avoid having two separate loops in case the index is a VGPR. 300 301 // Most operations are naturally 32-bit vector operations. We only support 302 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 303 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 304 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 305 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 306 307 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 308 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 309 310 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 311 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 312 313 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 314 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 315 } 316 317 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 318 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 319 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 320 321 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 322 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 323 324 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 325 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 326 327 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 328 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 329 } 330 331 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 332 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 333 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 334 335 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 336 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 337 338 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 339 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 342 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 343 } 344 345 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 346 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 347 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 348 349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 350 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 351 352 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 353 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 356 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 357 } 358 359 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 360 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 361 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 362 363 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 364 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 365 366 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 367 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 370 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 371 } 372 373 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 377 378 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 379 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 380 381 // Avoid stack access for these. 382 // TODO: Generalize to more vector types. 383 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 384 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 386 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 387 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 390 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 393 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 394 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 396 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 398 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 399 400 // Deal with vec3 vector operations when widened to vec4. 401 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 402 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 405 406 // Deal with vec5/6/7 vector operations when widened to vec8. 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 415 416 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 417 // and output demarshalling 418 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 419 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 420 421 // We can't return success/failure, only the old value, 422 // let LLVM add the comparison 423 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 424 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 425 426 if (Subtarget->hasFlatAddressSpace()) { 427 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 428 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 429 } 430 431 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 432 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 433 434 // FIXME: This should be narrowed to i32, but that only happens if i64 is 435 // illegal. 436 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 437 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 438 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 439 440 // On SI this is s_memtime and s_memrealtime on VI. 441 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 442 setOperationAction(ISD::TRAP, MVT::Other, Custom); 443 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 444 445 if (Subtarget->has16BitInsts()) { 446 setOperationAction(ISD::FPOW, MVT::f16, Promote); 447 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 448 setOperationAction(ISD::FLOG, MVT::f16, Custom); 449 setOperationAction(ISD::FEXP, MVT::f16, Custom); 450 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 451 } 452 453 if (Subtarget->hasMadMacF32Insts()) 454 setOperationAction(ISD::FMAD, MVT::f32, Legal); 455 456 if (!Subtarget->hasBFI()) { 457 // fcopysign can be done in a single instruction with BFI. 458 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 459 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 460 } 461 462 if (!Subtarget->hasBCNT(32)) 463 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 464 465 if (!Subtarget->hasBCNT(64)) 466 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 467 468 if (Subtarget->hasFFBH()) 469 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 470 471 if (Subtarget->hasFFBL()) 472 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 473 474 // We only really have 32-bit BFE instructions (and 16-bit on VI). 475 // 476 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 477 // effort to match them now. We want this to be false for i64 cases when the 478 // extraction isn't restricted to the upper or lower half. Ideally we would 479 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 480 // span the midpoint are probably relatively rare, so don't worry about them 481 // for now. 482 if (Subtarget->hasBFE()) 483 setHasExtractBitsInsn(true); 484 485 // Clamp modifier on add/sub 486 if (Subtarget->hasIntClamp()) { 487 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 488 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 489 } 490 491 if (Subtarget->hasAddNoCarry()) { 492 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 493 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 494 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 495 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 496 } 497 498 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 499 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 500 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 501 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 502 503 504 // These are really only legal for ieee_mode functions. We should be avoiding 505 // them for functions that don't have ieee_mode enabled, so just say they are 506 // legal. 507 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 508 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 509 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 510 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 511 512 513 if (Subtarget->haveRoundOpsF64()) { 514 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 515 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 516 setOperationAction(ISD::FRINT, MVT::f64, Legal); 517 } else { 518 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 519 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 520 setOperationAction(ISD::FRINT, MVT::f64, Custom); 521 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 522 } 523 524 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 525 526 setOperationAction(ISD::FSIN, MVT::f32, Custom); 527 setOperationAction(ISD::FCOS, MVT::f32, Custom); 528 setOperationAction(ISD::FDIV, MVT::f32, Custom); 529 setOperationAction(ISD::FDIV, MVT::f64, Custom); 530 531 if (Subtarget->has16BitInsts()) { 532 setOperationAction(ISD::Constant, MVT::i16, Legal); 533 534 setOperationAction(ISD::SMIN, MVT::i16, Legal); 535 setOperationAction(ISD::SMAX, MVT::i16, Legal); 536 537 setOperationAction(ISD::UMIN, MVT::i16, Legal); 538 setOperationAction(ISD::UMAX, MVT::i16, Legal); 539 540 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 541 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 542 543 setOperationAction(ISD::ROTR, MVT::i16, Expand); 544 setOperationAction(ISD::ROTL, MVT::i16, Expand); 545 546 setOperationAction(ISD::SDIV, MVT::i16, Promote); 547 setOperationAction(ISD::UDIV, MVT::i16, Promote); 548 setOperationAction(ISD::SREM, MVT::i16, Promote); 549 setOperationAction(ISD::UREM, MVT::i16, Promote); 550 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 551 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 552 553 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 554 555 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 557 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 558 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 559 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 560 561 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 562 563 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 564 565 setOperationAction(ISD::LOAD, MVT::i16, Custom); 566 567 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 568 569 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 570 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 571 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 572 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 573 574 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 575 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 576 577 // F16 - Constant Actions. 578 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 579 580 // F16 - Load/Store Actions. 581 setOperationAction(ISD::LOAD, MVT::f16, Promote); 582 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 583 setOperationAction(ISD::STORE, MVT::f16, Promote); 584 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 585 586 // F16 - VOP1 Actions. 587 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 588 setOperationAction(ISD::FCOS, MVT::f16, Custom); 589 setOperationAction(ISD::FSIN, MVT::f16, Custom); 590 591 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 592 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 593 594 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 595 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 596 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 597 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 598 setOperationAction(ISD::FROUND, MVT::f16, Custom); 599 600 // F16 - VOP2 Actions. 601 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 602 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 603 604 setOperationAction(ISD::FDIV, MVT::f16, Custom); 605 606 // F16 - VOP3 Actions. 607 setOperationAction(ISD::FMA, MVT::f16, Legal); 608 if (STI.hasMadF16()) 609 setOperationAction(ISD::FMAD, MVT::f16, Legal); 610 611 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 612 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 613 switch (Op) { 614 case ISD::LOAD: 615 case ISD::STORE: 616 case ISD::BUILD_VECTOR: 617 case ISD::BITCAST: 618 case ISD::EXTRACT_VECTOR_ELT: 619 case ISD::INSERT_VECTOR_ELT: 620 case ISD::INSERT_SUBVECTOR: 621 case ISD::EXTRACT_SUBVECTOR: 622 case ISD::SCALAR_TO_VECTOR: 623 break; 624 case ISD::CONCAT_VECTORS: 625 setOperationAction(Op, VT, Custom); 626 break; 627 default: 628 setOperationAction(Op, VT, Expand); 629 break; 630 } 631 } 632 } 633 634 // v_perm_b32 can handle either of these. 635 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 636 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 637 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 638 639 // XXX - Do these do anything? Vector constants turn into build_vector. 640 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 641 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 644 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 647 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 648 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 649 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 650 651 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 652 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 653 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 654 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 655 656 setOperationAction(ISD::AND, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::OR, MVT::v2i16, Promote); 659 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 660 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 661 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 662 663 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 664 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 665 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 666 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 667 668 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 669 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 670 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 671 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 672 673 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 674 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 675 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 676 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 677 678 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 679 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 680 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 681 682 if (!Subtarget->hasVOP3PInsts()) { 683 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 684 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 685 } 686 687 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 688 // This isn't really legal, but this avoids the legalizer unrolling it (and 689 // allows matching fneg (fabs x) patterns) 690 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 691 692 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 693 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 694 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 695 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 696 697 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 698 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 699 700 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 701 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 702 } 703 704 if (Subtarget->hasVOP3PInsts()) { 705 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 706 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 707 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 708 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 709 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 710 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 711 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 712 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 713 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 714 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 715 716 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 717 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 718 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 719 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 720 721 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 722 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 723 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 724 725 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 726 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 727 728 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 729 730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 731 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 732 733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 735 736 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 737 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 738 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 739 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 740 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 741 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 742 743 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 744 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 745 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 746 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 747 748 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 749 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 750 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 751 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 752 753 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 754 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 755 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 756 757 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 758 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 759 760 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 761 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 762 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 763 764 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 765 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 766 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 767 768 if (Subtarget->hasPackedFP32Ops()) { 769 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 770 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 771 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 772 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 773 774 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 775 setOperationAction(ISD::FADD, VT, Custom); 776 setOperationAction(ISD::FMUL, VT, Custom); 777 setOperationAction(ISD::FMA, VT, Custom); 778 } 779 } 780 } 781 782 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 783 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 784 785 if (Subtarget->has16BitInsts()) { 786 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 787 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 788 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 789 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 790 } else { 791 // Legalization hack. 792 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 793 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 794 795 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 796 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 797 } 798 799 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 800 setOperationAction(ISD::SELECT, VT, Custom); 801 } 802 803 setOperationAction(ISD::SMULO, MVT::i64, Custom); 804 setOperationAction(ISD::UMULO, MVT::i64, Custom); 805 806 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 807 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 808 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 809 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 810 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 811 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 812 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 813 814 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 815 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 816 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 817 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 818 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 819 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 820 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 821 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 825 826 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 827 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 828 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 829 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 830 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 831 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 832 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 833 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 836 837 setTargetDAGCombine(ISD::ADD); 838 setTargetDAGCombine(ISD::ADDCARRY); 839 setTargetDAGCombine(ISD::SUB); 840 setTargetDAGCombine(ISD::SUBCARRY); 841 setTargetDAGCombine(ISD::FADD); 842 setTargetDAGCombine(ISD::FSUB); 843 setTargetDAGCombine(ISD::FMINNUM); 844 setTargetDAGCombine(ISD::FMAXNUM); 845 setTargetDAGCombine(ISD::FMINNUM_IEEE); 846 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 847 setTargetDAGCombine(ISD::FMA); 848 setTargetDAGCombine(ISD::SMIN); 849 setTargetDAGCombine(ISD::SMAX); 850 setTargetDAGCombine(ISD::UMIN); 851 setTargetDAGCombine(ISD::UMAX); 852 setTargetDAGCombine(ISD::SETCC); 853 setTargetDAGCombine(ISD::AND); 854 setTargetDAGCombine(ISD::OR); 855 setTargetDAGCombine(ISD::XOR); 856 setTargetDAGCombine(ISD::SINT_TO_FP); 857 setTargetDAGCombine(ISD::UINT_TO_FP); 858 setTargetDAGCombine(ISD::FCANONICALIZE); 859 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 860 setTargetDAGCombine(ISD::ZERO_EXTEND); 861 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 862 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 863 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 864 865 // All memory operations. Some folding on the pointer operand is done to help 866 // matching the constant offsets in the addressing modes. 867 setTargetDAGCombine(ISD::LOAD); 868 setTargetDAGCombine(ISD::STORE); 869 setTargetDAGCombine(ISD::ATOMIC_LOAD); 870 setTargetDAGCombine(ISD::ATOMIC_STORE); 871 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 872 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 873 setTargetDAGCombine(ISD::ATOMIC_SWAP); 874 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 875 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 876 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 878 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 879 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 880 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 881 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 885 setTargetDAGCombine(ISD::INTRINSIC_VOID); 886 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 887 888 // FIXME: In other contexts we pretend this is a per-function property. 889 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 890 891 setSchedulingPreference(Sched::RegPressure); 892 } 893 894 const GCNSubtarget *SITargetLowering::getSubtarget() const { 895 return Subtarget; 896 } 897 898 //===----------------------------------------------------------------------===// 899 // TargetLowering queries 900 //===----------------------------------------------------------------------===// 901 902 // v_mad_mix* support a conversion from f16 to f32. 903 // 904 // There is only one special case when denormals are enabled we don't currently, 905 // where this is OK to use. 906 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 907 EVT DestVT, EVT SrcVT) const { 908 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 909 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 910 DestVT.getScalarType() == MVT::f32 && 911 SrcVT.getScalarType() == MVT::f16 && 912 // TODO: This probably only requires no input flushing? 913 !hasFP32Denormals(DAG.getMachineFunction()); 914 } 915 916 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 917 // SI has some legal vector types, but no legal vector operations. Say no 918 // shuffles are legal in order to prefer scalarizing some vector operations. 919 return false; 920 } 921 922 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 923 CallingConv::ID CC, 924 EVT VT) const { 925 if (CC == CallingConv::AMDGPU_KERNEL) 926 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 927 928 if (VT.isVector()) { 929 EVT ScalarVT = VT.getScalarType(); 930 unsigned Size = ScalarVT.getSizeInBits(); 931 if (Size == 16) { 932 if (Subtarget->has16BitInsts()) 933 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 934 return VT.isInteger() ? MVT::i32 : MVT::f32; 935 } 936 937 if (Size < 16) 938 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 939 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 940 } 941 942 if (VT.getSizeInBits() > 32) 943 return MVT::i32; 944 945 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 946 } 947 948 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 949 CallingConv::ID CC, 950 EVT VT) const { 951 if (CC == CallingConv::AMDGPU_KERNEL) 952 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 953 954 if (VT.isVector()) { 955 unsigned NumElts = VT.getVectorNumElements(); 956 EVT ScalarVT = VT.getScalarType(); 957 unsigned Size = ScalarVT.getSizeInBits(); 958 959 // FIXME: Should probably promote 8-bit vectors to i16. 960 if (Size == 16 && Subtarget->has16BitInsts()) 961 return (NumElts + 1) / 2; 962 963 if (Size <= 32) 964 return NumElts; 965 966 if (Size > 32) 967 return NumElts * ((Size + 31) / 32); 968 } else if (VT.getSizeInBits() > 32) 969 return (VT.getSizeInBits() + 31) / 32; 970 971 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 972 } 973 974 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 975 LLVMContext &Context, CallingConv::ID CC, 976 EVT VT, EVT &IntermediateVT, 977 unsigned &NumIntermediates, MVT &RegisterVT) const { 978 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 979 unsigned NumElts = VT.getVectorNumElements(); 980 EVT ScalarVT = VT.getScalarType(); 981 unsigned Size = ScalarVT.getSizeInBits(); 982 // FIXME: We should fix the ABI to be the same on targets without 16-bit 983 // support, but unless we can properly handle 3-vectors, it will be still be 984 // inconsistent. 985 if (Size == 16 && Subtarget->has16BitInsts()) { 986 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 987 IntermediateVT = RegisterVT; 988 NumIntermediates = (NumElts + 1) / 2; 989 return NumIntermediates; 990 } 991 992 if (Size == 32) { 993 RegisterVT = ScalarVT.getSimpleVT(); 994 IntermediateVT = RegisterVT; 995 NumIntermediates = NumElts; 996 return NumIntermediates; 997 } 998 999 if (Size < 16 && Subtarget->has16BitInsts()) { 1000 // FIXME: Should probably form v2i16 pieces 1001 RegisterVT = MVT::i16; 1002 IntermediateVT = ScalarVT; 1003 NumIntermediates = NumElts; 1004 return NumIntermediates; 1005 } 1006 1007 1008 if (Size != 16 && Size <= 32) { 1009 RegisterVT = MVT::i32; 1010 IntermediateVT = ScalarVT; 1011 NumIntermediates = NumElts; 1012 return NumIntermediates; 1013 } 1014 1015 if (Size > 32) { 1016 RegisterVT = MVT::i32; 1017 IntermediateVT = RegisterVT; 1018 NumIntermediates = NumElts * ((Size + 31) / 32); 1019 return NumIntermediates; 1020 } 1021 } 1022 1023 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1024 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1025 } 1026 1027 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1028 assert(DMaskLanes != 0); 1029 1030 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1031 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1032 return EVT::getVectorVT(Ty->getContext(), 1033 EVT::getEVT(VT->getElementType()), 1034 NumElts); 1035 } 1036 1037 return EVT::getEVT(Ty); 1038 } 1039 1040 // Peek through TFE struct returns to only use the data size. 1041 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1042 auto *ST = dyn_cast<StructType>(Ty); 1043 if (!ST) 1044 return memVTFromImageData(Ty, DMaskLanes); 1045 1046 // Some intrinsics return an aggregate type - special case to work out the 1047 // correct memVT. 1048 // 1049 // Only limited forms of aggregate type currently expected. 1050 if (ST->getNumContainedTypes() != 2 || 1051 !ST->getContainedType(1)->isIntegerTy(32)) 1052 return EVT(); 1053 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1054 } 1055 1056 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1057 const CallInst &CI, 1058 MachineFunction &MF, 1059 unsigned IntrID) const { 1060 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1061 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1062 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1063 (Intrinsic::ID)IntrID); 1064 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1065 return false; 1066 1067 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1068 1069 if (RsrcIntr->IsImage) { 1070 Info.ptrVal = 1071 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1072 Info.align.reset(); 1073 } else { 1074 Info.ptrVal = 1075 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1076 } 1077 1078 Info.flags = MachineMemOperand::MODereferenceable; 1079 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1080 unsigned DMaskLanes = 4; 1081 1082 if (RsrcIntr->IsImage) { 1083 const AMDGPU::ImageDimIntrinsicInfo *Intr 1084 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1085 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1086 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1087 1088 if (!BaseOpcode->Gather4) { 1089 // If this isn't a gather, we may have excess loaded elements in the 1090 // IR type. Check the dmask for the real number of elements loaded. 1091 unsigned DMask 1092 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1093 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1094 } 1095 1096 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1097 } else 1098 Info.memVT = EVT::getEVT(CI.getType()); 1099 1100 // FIXME: What does alignment mean for an image? 1101 Info.opc = ISD::INTRINSIC_W_CHAIN; 1102 Info.flags |= MachineMemOperand::MOLoad; 1103 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1104 Info.opc = ISD::INTRINSIC_VOID; 1105 1106 Type *DataTy = CI.getArgOperand(0)->getType(); 1107 if (RsrcIntr->IsImage) { 1108 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1109 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1110 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1111 } else 1112 Info.memVT = EVT::getEVT(DataTy); 1113 1114 Info.flags |= MachineMemOperand::MOStore; 1115 } else { 1116 // Atomic 1117 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1118 ISD::INTRINSIC_W_CHAIN; 1119 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1120 Info.flags = MachineMemOperand::MOLoad | 1121 MachineMemOperand::MOStore | 1122 MachineMemOperand::MODereferenceable; 1123 1124 // XXX - Should this be volatile without known ordering? 1125 Info.flags |= MachineMemOperand::MOVolatile; 1126 } 1127 return true; 1128 } 1129 1130 switch (IntrID) { 1131 case Intrinsic::amdgcn_atomic_inc: 1132 case Intrinsic::amdgcn_atomic_dec: 1133 case Intrinsic::amdgcn_ds_ordered_add: 1134 case Intrinsic::amdgcn_ds_ordered_swap: 1135 case Intrinsic::amdgcn_ds_fadd: 1136 case Intrinsic::amdgcn_ds_fmin: 1137 case Intrinsic::amdgcn_ds_fmax: { 1138 Info.opc = ISD::INTRINSIC_W_CHAIN; 1139 Info.memVT = MVT::getVT(CI.getType()); 1140 Info.ptrVal = CI.getOperand(0); 1141 Info.align.reset(); 1142 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1143 1144 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1145 if (!Vol->isZero()) 1146 Info.flags |= MachineMemOperand::MOVolatile; 1147 1148 return true; 1149 } 1150 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1151 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1152 1153 Info.opc = ISD::INTRINSIC_W_CHAIN; 1154 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1155 Info.ptrVal = 1156 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1157 Info.align.reset(); 1158 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1159 1160 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1161 if (!Vol || !Vol->isZero()) 1162 Info.flags |= MachineMemOperand::MOVolatile; 1163 1164 return true; 1165 } 1166 case Intrinsic::amdgcn_ds_append: 1167 case Intrinsic::amdgcn_ds_consume: { 1168 Info.opc = ISD::INTRINSIC_W_CHAIN; 1169 Info.memVT = MVT::getVT(CI.getType()); 1170 Info.ptrVal = CI.getOperand(0); 1171 Info.align.reset(); 1172 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1173 1174 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1175 if (!Vol->isZero()) 1176 Info.flags |= MachineMemOperand::MOVolatile; 1177 1178 return true; 1179 } 1180 case Intrinsic::amdgcn_global_atomic_csub: { 1181 Info.opc = ISD::INTRINSIC_W_CHAIN; 1182 Info.memVT = MVT::getVT(CI.getType()); 1183 Info.ptrVal = CI.getOperand(0); 1184 Info.align.reset(); 1185 Info.flags = MachineMemOperand::MOLoad | 1186 MachineMemOperand::MOStore | 1187 MachineMemOperand::MOVolatile; 1188 return true; 1189 } 1190 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1191 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1192 Info.opc = ISD::INTRINSIC_W_CHAIN; 1193 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1194 Info.ptrVal = 1195 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1196 Info.align.reset(); 1197 Info.flags = MachineMemOperand::MOLoad | 1198 MachineMemOperand::MODereferenceable; 1199 return true; 1200 } 1201 case Intrinsic::amdgcn_global_atomic_fadd: 1202 case Intrinsic::amdgcn_global_atomic_fmin: 1203 case Intrinsic::amdgcn_global_atomic_fmax: 1204 case Intrinsic::amdgcn_flat_atomic_fadd: 1205 case Intrinsic::amdgcn_flat_atomic_fmin: 1206 case Intrinsic::amdgcn_flat_atomic_fmax: { 1207 Info.opc = ISD::INTRINSIC_W_CHAIN; 1208 Info.memVT = MVT::getVT(CI.getType()); 1209 Info.ptrVal = CI.getOperand(0); 1210 Info.align.reset(); 1211 Info.flags = MachineMemOperand::MOLoad | 1212 MachineMemOperand::MOStore | 1213 MachineMemOperand::MODereferenceable | 1214 MachineMemOperand::MOVolatile; 1215 return true; 1216 } 1217 case Intrinsic::amdgcn_ds_gws_init: 1218 case Intrinsic::amdgcn_ds_gws_barrier: 1219 case Intrinsic::amdgcn_ds_gws_sema_v: 1220 case Intrinsic::amdgcn_ds_gws_sema_br: 1221 case Intrinsic::amdgcn_ds_gws_sema_p: 1222 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1223 Info.opc = ISD::INTRINSIC_VOID; 1224 1225 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1226 Info.ptrVal = 1227 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1228 1229 // This is an abstract access, but we need to specify a type and size. 1230 Info.memVT = MVT::i32; 1231 Info.size = 4; 1232 Info.align = Align(4); 1233 1234 Info.flags = MachineMemOperand::MOStore; 1235 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1236 Info.flags = MachineMemOperand::MOLoad; 1237 return true; 1238 } 1239 default: 1240 return false; 1241 } 1242 } 1243 1244 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1245 SmallVectorImpl<Value*> &Ops, 1246 Type *&AccessTy) const { 1247 switch (II->getIntrinsicID()) { 1248 case Intrinsic::amdgcn_atomic_inc: 1249 case Intrinsic::amdgcn_atomic_dec: 1250 case Intrinsic::amdgcn_ds_ordered_add: 1251 case Intrinsic::amdgcn_ds_ordered_swap: 1252 case Intrinsic::amdgcn_ds_append: 1253 case Intrinsic::amdgcn_ds_consume: 1254 case Intrinsic::amdgcn_ds_fadd: 1255 case Intrinsic::amdgcn_ds_fmin: 1256 case Intrinsic::amdgcn_ds_fmax: 1257 case Intrinsic::amdgcn_global_atomic_fadd: 1258 case Intrinsic::amdgcn_flat_atomic_fadd: 1259 case Intrinsic::amdgcn_flat_atomic_fmin: 1260 case Intrinsic::amdgcn_flat_atomic_fmax: 1261 case Intrinsic::amdgcn_global_atomic_csub: { 1262 Value *Ptr = II->getArgOperand(0); 1263 AccessTy = II->getType(); 1264 Ops.push_back(Ptr); 1265 return true; 1266 } 1267 default: 1268 return false; 1269 } 1270 } 1271 1272 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1273 if (!Subtarget->hasFlatInstOffsets()) { 1274 // Flat instructions do not have offsets, and only have the register 1275 // address. 1276 return AM.BaseOffs == 0 && AM.Scale == 0; 1277 } 1278 1279 return AM.Scale == 0 && 1280 (AM.BaseOffs == 0 || 1281 Subtarget->getInstrInfo()->isLegalFLATOffset( 1282 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1283 } 1284 1285 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1286 if (Subtarget->hasFlatGlobalInsts()) 1287 return AM.Scale == 0 && 1288 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1289 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1290 SIInstrFlags::FlatGlobal)); 1291 1292 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1293 // Assume the we will use FLAT for all global memory accesses 1294 // on VI. 1295 // FIXME: This assumption is currently wrong. On VI we still use 1296 // MUBUF instructions for the r + i addressing mode. As currently 1297 // implemented, the MUBUF instructions only work on buffer < 4GB. 1298 // It may be possible to support > 4GB buffers with MUBUF instructions, 1299 // by setting the stride value in the resource descriptor which would 1300 // increase the size limit to (stride * 4GB). However, this is risky, 1301 // because it has never been validated. 1302 return isLegalFlatAddressingMode(AM); 1303 } 1304 1305 return isLegalMUBUFAddressingMode(AM); 1306 } 1307 1308 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1309 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1310 // additionally can do r + r + i with addr64. 32-bit has more addressing 1311 // mode options. Depending on the resource constant, it can also do 1312 // (i64 r0) + (i32 r1) * (i14 i). 1313 // 1314 // Private arrays end up using a scratch buffer most of the time, so also 1315 // assume those use MUBUF instructions. Scratch loads / stores are currently 1316 // implemented as mubuf instructions with offen bit set, so slightly 1317 // different than the normal addr64. 1318 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1319 return false; 1320 1321 // FIXME: Since we can split immediate into soffset and immediate offset, 1322 // would it make sense to allow any immediate? 1323 1324 switch (AM.Scale) { 1325 case 0: // r + i or just i, depending on HasBaseReg. 1326 return true; 1327 case 1: 1328 return true; // We have r + r or r + i. 1329 case 2: 1330 if (AM.HasBaseReg) { 1331 // Reject 2 * r + r. 1332 return false; 1333 } 1334 1335 // Allow 2 * r as r + r 1336 // Or 2 * r + i is allowed as r + r + i. 1337 return true; 1338 default: // Don't allow n * r 1339 return false; 1340 } 1341 } 1342 1343 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1344 const AddrMode &AM, Type *Ty, 1345 unsigned AS, Instruction *I) const { 1346 // No global is ever allowed as a base. 1347 if (AM.BaseGV) 1348 return false; 1349 1350 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1351 return isLegalGlobalAddressingMode(AM); 1352 1353 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1354 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1355 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1356 // If the offset isn't a multiple of 4, it probably isn't going to be 1357 // correctly aligned. 1358 // FIXME: Can we get the real alignment here? 1359 if (AM.BaseOffs % 4 != 0) 1360 return isLegalMUBUFAddressingMode(AM); 1361 1362 // There are no SMRD extloads, so if we have to do a small type access we 1363 // will use a MUBUF load. 1364 // FIXME?: We also need to do this if unaligned, but we don't know the 1365 // alignment here. 1366 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1367 return isLegalGlobalAddressingMode(AM); 1368 1369 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1370 // SMRD instructions have an 8-bit, dword offset on SI. 1371 if (!isUInt<8>(AM.BaseOffs / 4)) 1372 return false; 1373 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1374 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1375 // in 8-bits, it can use a smaller encoding. 1376 if (!isUInt<32>(AM.BaseOffs / 4)) 1377 return false; 1378 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1379 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1380 if (!isUInt<20>(AM.BaseOffs)) 1381 return false; 1382 } else 1383 llvm_unreachable("unhandled generation"); 1384 1385 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1386 return true; 1387 1388 if (AM.Scale == 1 && AM.HasBaseReg) 1389 return true; 1390 1391 return false; 1392 1393 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1394 return isLegalMUBUFAddressingMode(AM); 1395 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1396 AS == AMDGPUAS::REGION_ADDRESS) { 1397 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1398 // field. 1399 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1400 // an 8-bit dword offset but we don't know the alignment here. 1401 if (!isUInt<16>(AM.BaseOffs)) 1402 return false; 1403 1404 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1405 return true; 1406 1407 if (AM.Scale == 1 && AM.HasBaseReg) 1408 return true; 1409 1410 return false; 1411 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1412 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1413 // For an unknown address space, this usually means that this is for some 1414 // reason being used for pure arithmetic, and not based on some addressing 1415 // computation. We don't have instructions that compute pointers with any 1416 // addressing modes, so treat them as having no offset like flat 1417 // instructions. 1418 return isLegalFlatAddressingMode(AM); 1419 } 1420 1421 // Assume a user alias of global for unknown address spaces. 1422 return isLegalGlobalAddressingMode(AM); 1423 } 1424 1425 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1426 const SelectionDAG &DAG) const { 1427 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1428 return (MemVT.getSizeInBits() <= 4 * 32); 1429 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1430 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1431 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1432 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1433 return (MemVT.getSizeInBits() <= 2 * 32); 1434 } 1435 return true; 1436 } 1437 1438 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1439 unsigned Size, unsigned AddrSpace, Align Alignment, 1440 MachineMemOperand::Flags Flags, bool *IsFast) const { 1441 if (IsFast) 1442 *IsFast = false; 1443 1444 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1445 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1446 // Check if alignment requirements for ds_read/write instructions are 1447 // disabled. 1448 if (Subtarget->hasUnalignedDSAccessEnabled() && 1449 !Subtarget->hasLDSMisalignedBug()) { 1450 if (IsFast) 1451 *IsFast = Alignment != Align(2); 1452 return true; 1453 } 1454 1455 // Either, the alignment requirements are "enabled", or there is an 1456 // unaligned LDS access related hardware bug though alignment requirements 1457 // are "disabled". In either case, we need to check for proper alignment 1458 // requirements. 1459 // 1460 if (Size == 64) { 1461 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1462 // can do a 4 byte aligned, 8 byte access in a single operation using 1463 // ds_read2/write2_b32 with adjacent offsets. 1464 bool AlignedBy4 = Alignment >= Align(4); 1465 if (IsFast) 1466 *IsFast = AlignedBy4; 1467 1468 return AlignedBy4; 1469 } 1470 if (Size == 96) { 1471 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1472 // gfx8 and older. 1473 bool AlignedBy16 = Alignment >= Align(16); 1474 if (IsFast) 1475 *IsFast = AlignedBy16; 1476 1477 return AlignedBy16; 1478 } 1479 if (Size == 128) { 1480 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1481 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1482 // single operation using ds_read2/write2_b64. 1483 bool AlignedBy8 = Alignment >= Align(8); 1484 if (IsFast) 1485 *IsFast = AlignedBy8; 1486 1487 return AlignedBy8; 1488 } 1489 } 1490 1491 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1492 bool AlignedBy4 = Alignment >= Align(4); 1493 if (IsFast) 1494 *IsFast = AlignedBy4; 1495 1496 return AlignedBy4 || 1497 Subtarget->enableFlatScratch() || 1498 Subtarget->hasUnalignedScratchAccess(); 1499 } 1500 1501 // FIXME: We have to be conservative here and assume that flat operations 1502 // will access scratch. If we had access to the IR function, then we 1503 // could determine if any private memory was used in the function. 1504 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1505 !Subtarget->hasUnalignedScratchAccess()) { 1506 bool AlignedBy4 = Alignment >= Align(4); 1507 if (IsFast) 1508 *IsFast = AlignedBy4; 1509 1510 return AlignedBy4; 1511 } 1512 1513 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1514 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1515 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1516 // If we have an uniform constant load, it still requires using a slow 1517 // buffer instruction if unaligned. 1518 if (IsFast) { 1519 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1520 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1521 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1522 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1523 Alignment >= Align(4) : Alignment != Align(2); 1524 } 1525 1526 return true; 1527 } 1528 1529 // Smaller than dword value must be aligned. 1530 if (Size < 32) 1531 return false; 1532 1533 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1534 // byte-address are ignored, thus forcing Dword alignment. 1535 // This applies to private, global, and constant memory. 1536 if (IsFast) 1537 *IsFast = true; 1538 1539 return Size >= 32 && Alignment >= Align(4); 1540 } 1541 1542 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1543 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1544 bool *IsFast) const { 1545 if (IsFast) 1546 *IsFast = false; 1547 1548 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1549 // which isn't a simple VT. 1550 // Until MVT is extended to handle this, simply check for the size and 1551 // rely on the condition below: allow accesses if the size is a multiple of 4. 1552 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1553 VT.getStoreSize() > 16)) { 1554 return false; 1555 } 1556 1557 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1558 Alignment, Flags, IsFast); 1559 } 1560 1561 EVT SITargetLowering::getOptimalMemOpType( 1562 const MemOp &Op, const AttributeList &FuncAttributes) const { 1563 // FIXME: Should account for address space here. 1564 1565 // The default fallback uses the private pointer size as a guess for a type to 1566 // use. Make sure we switch these to 64-bit accesses. 1567 1568 if (Op.size() >= 16 && 1569 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1570 return MVT::v4i32; 1571 1572 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1573 return MVT::v2i32; 1574 1575 // Use the default. 1576 return MVT::Other; 1577 } 1578 1579 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1580 const MemSDNode *MemNode = cast<MemSDNode>(N); 1581 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1582 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1583 return I && I->getMetadata("amdgpu.noclobber"); 1584 } 1585 1586 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1587 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1588 AS == AMDGPUAS::PRIVATE_ADDRESS; 1589 } 1590 1591 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1592 unsigned DestAS) const { 1593 // Flat -> private/local is a simple truncate. 1594 // Flat -> global is no-op 1595 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1596 return true; 1597 1598 const GCNTargetMachine &TM = 1599 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1600 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1601 } 1602 1603 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1604 const MemSDNode *MemNode = cast<MemSDNode>(N); 1605 1606 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1607 } 1608 1609 TargetLoweringBase::LegalizeTypeAction 1610 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1611 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1612 VT.getScalarType().bitsLE(MVT::i16)) 1613 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1614 return TargetLoweringBase::getPreferredVectorAction(VT); 1615 } 1616 1617 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1618 Type *Ty) const { 1619 // FIXME: Could be smarter if called for vector constants. 1620 return true; 1621 } 1622 1623 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1624 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1625 switch (Op) { 1626 case ISD::LOAD: 1627 case ISD::STORE: 1628 1629 // These operations are done with 32-bit instructions anyway. 1630 case ISD::AND: 1631 case ISD::OR: 1632 case ISD::XOR: 1633 case ISD::SELECT: 1634 // TODO: Extensions? 1635 return true; 1636 default: 1637 return false; 1638 } 1639 } 1640 1641 // SimplifySetCC uses this function to determine whether or not it should 1642 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1643 if (VT == MVT::i1 && Op == ISD::SETCC) 1644 return false; 1645 1646 return TargetLowering::isTypeDesirableForOp(Op, VT); 1647 } 1648 1649 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1650 const SDLoc &SL, 1651 SDValue Chain, 1652 uint64_t Offset) const { 1653 const DataLayout &DL = DAG.getDataLayout(); 1654 MachineFunction &MF = DAG.getMachineFunction(); 1655 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1656 1657 const ArgDescriptor *InputPtrReg; 1658 const TargetRegisterClass *RC; 1659 LLT ArgTy; 1660 1661 std::tie(InputPtrReg, RC, ArgTy) = 1662 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1663 1664 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1665 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1666 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1667 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1668 1669 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1670 } 1671 1672 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1673 const SDLoc &SL) const { 1674 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1675 FIRST_IMPLICIT); 1676 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1677 } 1678 1679 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1680 const SDLoc &SL, SDValue Val, 1681 bool Signed, 1682 const ISD::InputArg *Arg) const { 1683 // First, if it is a widened vector, narrow it. 1684 if (VT.isVector() && 1685 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1686 EVT NarrowedVT = 1687 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1688 VT.getVectorNumElements()); 1689 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1690 DAG.getConstant(0, SL, MVT::i32)); 1691 } 1692 1693 // Then convert the vector elements or scalar value. 1694 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1695 VT.bitsLT(MemVT)) { 1696 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1697 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1698 } 1699 1700 if (MemVT.isFloatingPoint()) 1701 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1702 else if (Signed) 1703 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1704 else 1705 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1706 1707 return Val; 1708 } 1709 1710 SDValue SITargetLowering::lowerKernargMemParameter( 1711 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1712 uint64_t Offset, Align Alignment, bool Signed, 1713 const ISD::InputArg *Arg) const { 1714 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1715 1716 // Try to avoid using an extload by loading earlier than the argument address, 1717 // and extracting the relevant bits. The load should hopefully be merged with 1718 // the previous argument. 1719 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1720 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1721 int64_t AlignDownOffset = alignDown(Offset, 4); 1722 int64_t OffsetDiff = Offset - AlignDownOffset; 1723 1724 EVT IntVT = MemVT.changeTypeToInteger(); 1725 1726 // TODO: If we passed in the base kernel offset we could have a better 1727 // alignment than 4, but we don't really need it. 1728 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1729 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1730 MachineMemOperand::MODereferenceable | 1731 MachineMemOperand::MOInvariant); 1732 1733 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1734 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1735 1736 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1737 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1738 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1739 1740 1741 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1742 } 1743 1744 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1745 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1746 MachineMemOperand::MODereferenceable | 1747 MachineMemOperand::MOInvariant); 1748 1749 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1750 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1751 } 1752 1753 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1754 const SDLoc &SL, SDValue Chain, 1755 const ISD::InputArg &Arg) const { 1756 MachineFunction &MF = DAG.getMachineFunction(); 1757 MachineFrameInfo &MFI = MF.getFrameInfo(); 1758 1759 if (Arg.Flags.isByVal()) { 1760 unsigned Size = Arg.Flags.getByValSize(); 1761 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1762 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1763 } 1764 1765 unsigned ArgOffset = VA.getLocMemOffset(); 1766 unsigned ArgSize = VA.getValVT().getStoreSize(); 1767 1768 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1769 1770 // Create load nodes to retrieve arguments from the stack. 1771 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1772 SDValue ArgValue; 1773 1774 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1775 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1776 MVT MemVT = VA.getValVT(); 1777 1778 switch (VA.getLocInfo()) { 1779 default: 1780 break; 1781 case CCValAssign::BCvt: 1782 MemVT = VA.getLocVT(); 1783 break; 1784 case CCValAssign::SExt: 1785 ExtType = ISD::SEXTLOAD; 1786 break; 1787 case CCValAssign::ZExt: 1788 ExtType = ISD::ZEXTLOAD; 1789 break; 1790 case CCValAssign::AExt: 1791 ExtType = ISD::EXTLOAD; 1792 break; 1793 } 1794 1795 ArgValue = DAG.getExtLoad( 1796 ExtType, SL, VA.getLocVT(), Chain, FIN, 1797 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1798 MemVT); 1799 return ArgValue; 1800 } 1801 1802 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1803 const SIMachineFunctionInfo &MFI, 1804 EVT VT, 1805 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1806 const ArgDescriptor *Reg; 1807 const TargetRegisterClass *RC; 1808 LLT Ty; 1809 1810 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1811 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1812 } 1813 1814 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1815 CallingConv::ID CallConv, 1816 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1817 FunctionType *FType, 1818 SIMachineFunctionInfo *Info) { 1819 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1820 const ISD::InputArg *Arg = &Ins[I]; 1821 1822 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1823 "vector type argument should have been split"); 1824 1825 // First check if it's a PS input addr. 1826 if (CallConv == CallingConv::AMDGPU_PS && 1827 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1828 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1829 1830 // Inconveniently only the first part of the split is marked as isSplit, 1831 // so skip to the end. We only want to increment PSInputNum once for the 1832 // entire split argument. 1833 if (Arg->Flags.isSplit()) { 1834 while (!Arg->Flags.isSplitEnd()) { 1835 assert((!Arg->VT.isVector() || 1836 Arg->VT.getScalarSizeInBits() == 16) && 1837 "unexpected vector split in ps argument type"); 1838 if (!SkipArg) 1839 Splits.push_back(*Arg); 1840 Arg = &Ins[++I]; 1841 } 1842 } 1843 1844 if (SkipArg) { 1845 // We can safely skip PS inputs. 1846 Skipped.set(Arg->getOrigArgIndex()); 1847 ++PSInputNum; 1848 continue; 1849 } 1850 1851 Info->markPSInputAllocated(PSInputNum); 1852 if (Arg->Used) 1853 Info->markPSInputEnabled(PSInputNum); 1854 1855 ++PSInputNum; 1856 } 1857 1858 Splits.push_back(*Arg); 1859 } 1860 } 1861 1862 // Allocate special inputs passed in VGPRs. 1863 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1864 MachineFunction &MF, 1865 const SIRegisterInfo &TRI, 1866 SIMachineFunctionInfo &Info) const { 1867 const LLT S32 = LLT::scalar(32); 1868 MachineRegisterInfo &MRI = MF.getRegInfo(); 1869 1870 if (Info.hasWorkItemIDX()) { 1871 Register Reg = AMDGPU::VGPR0; 1872 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1873 1874 CCInfo.AllocateReg(Reg); 1875 unsigned Mask = (Subtarget->hasPackedTID() && 1876 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1877 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1878 } 1879 1880 if (Info.hasWorkItemIDY()) { 1881 assert(Info.hasWorkItemIDX()); 1882 if (Subtarget->hasPackedTID()) { 1883 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1884 0x3ff << 10)); 1885 } else { 1886 unsigned Reg = AMDGPU::VGPR1; 1887 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1888 1889 CCInfo.AllocateReg(Reg); 1890 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1891 } 1892 } 1893 1894 if (Info.hasWorkItemIDZ()) { 1895 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1896 if (Subtarget->hasPackedTID()) { 1897 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1898 0x3ff << 20)); 1899 } else { 1900 unsigned Reg = AMDGPU::VGPR2; 1901 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1902 1903 CCInfo.AllocateReg(Reg); 1904 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1905 } 1906 } 1907 } 1908 1909 // Try to allocate a VGPR at the end of the argument list, or if no argument 1910 // VGPRs are left allocating a stack slot. 1911 // If \p Mask is is given it indicates bitfield position in the register. 1912 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1913 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1914 ArgDescriptor Arg = ArgDescriptor()) { 1915 if (Arg.isSet()) 1916 return ArgDescriptor::createArg(Arg, Mask); 1917 1918 ArrayRef<MCPhysReg> ArgVGPRs 1919 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1920 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1921 if (RegIdx == ArgVGPRs.size()) { 1922 // Spill to stack required. 1923 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1924 1925 return ArgDescriptor::createStack(Offset, Mask); 1926 } 1927 1928 unsigned Reg = ArgVGPRs[RegIdx]; 1929 Reg = CCInfo.AllocateReg(Reg); 1930 assert(Reg != AMDGPU::NoRegister); 1931 1932 MachineFunction &MF = CCInfo.getMachineFunction(); 1933 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1934 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1935 return ArgDescriptor::createRegister(Reg, Mask); 1936 } 1937 1938 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1939 const TargetRegisterClass *RC, 1940 unsigned NumArgRegs) { 1941 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1942 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1943 if (RegIdx == ArgSGPRs.size()) 1944 report_fatal_error("ran out of SGPRs for arguments"); 1945 1946 unsigned Reg = ArgSGPRs[RegIdx]; 1947 Reg = CCInfo.AllocateReg(Reg); 1948 assert(Reg != AMDGPU::NoRegister); 1949 1950 MachineFunction &MF = CCInfo.getMachineFunction(); 1951 MF.addLiveIn(Reg, RC); 1952 return ArgDescriptor::createRegister(Reg); 1953 } 1954 1955 // If this has a fixed position, we still should allocate the register in the 1956 // CCInfo state. Technically we could get away with this for values passed 1957 // outside of the normal argument range. 1958 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1959 const TargetRegisterClass *RC, 1960 MCRegister Reg) { 1961 Reg = CCInfo.AllocateReg(Reg); 1962 assert(Reg != AMDGPU::NoRegister); 1963 MachineFunction &MF = CCInfo.getMachineFunction(); 1964 MF.addLiveIn(Reg, RC); 1965 } 1966 1967 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1968 if (Arg) { 1969 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1970 Arg.getRegister()); 1971 } else 1972 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1973 } 1974 1975 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1976 if (Arg) { 1977 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1978 Arg.getRegister()); 1979 } else 1980 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1981 } 1982 1983 /// Allocate implicit function VGPR arguments at the end of allocated user 1984 /// arguments. 1985 void SITargetLowering::allocateSpecialInputVGPRs( 1986 CCState &CCInfo, MachineFunction &MF, 1987 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1988 const unsigned Mask = 0x3ff; 1989 ArgDescriptor Arg; 1990 1991 if (Info.hasWorkItemIDX()) { 1992 Arg = allocateVGPR32Input(CCInfo, Mask); 1993 Info.setWorkItemIDX(Arg); 1994 } 1995 1996 if (Info.hasWorkItemIDY()) { 1997 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1998 Info.setWorkItemIDY(Arg); 1999 } 2000 2001 if (Info.hasWorkItemIDZ()) 2002 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2003 } 2004 2005 /// Allocate implicit function VGPR arguments in fixed registers. 2006 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2007 CCState &CCInfo, MachineFunction &MF, 2008 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2009 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2010 if (!Reg) 2011 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2012 2013 const unsigned Mask = 0x3ff; 2014 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2015 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2016 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2017 } 2018 2019 void SITargetLowering::allocateSpecialInputSGPRs( 2020 CCState &CCInfo, 2021 MachineFunction &MF, 2022 const SIRegisterInfo &TRI, 2023 SIMachineFunctionInfo &Info) const { 2024 auto &ArgInfo = Info.getArgInfo(); 2025 2026 // TODO: Unify handling with private memory pointers. 2027 2028 if (Info.hasDispatchPtr()) 2029 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2030 2031 if (Info.hasQueuePtr()) 2032 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2033 2034 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2035 // constant offset from the kernarg segment. 2036 if (Info.hasImplicitArgPtr()) 2037 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2038 2039 if (Info.hasDispatchID()) 2040 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2041 2042 // flat_scratch_init is not applicable for non-kernel functions. 2043 2044 if (Info.hasWorkGroupIDX()) 2045 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2046 2047 if (Info.hasWorkGroupIDY()) 2048 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2049 2050 if (Info.hasWorkGroupIDZ()) 2051 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2052 } 2053 2054 // Allocate special inputs passed in user SGPRs. 2055 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2056 MachineFunction &MF, 2057 const SIRegisterInfo &TRI, 2058 SIMachineFunctionInfo &Info) const { 2059 if (Info.hasImplicitBufferPtr()) { 2060 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2061 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2062 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2063 } 2064 2065 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2066 if (Info.hasPrivateSegmentBuffer()) { 2067 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2068 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2069 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2070 } 2071 2072 if (Info.hasDispatchPtr()) { 2073 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2074 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2075 CCInfo.AllocateReg(DispatchPtrReg); 2076 } 2077 2078 if (Info.hasQueuePtr()) { 2079 Register QueuePtrReg = Info.addQueuePtr(TRI); 2080 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2081 CCInfo.AllocateReg(QueuePtrReg); 2082 } 2083 2084 if (Info.hasKernargSegmentPtr()) { 2085 MachineRegisterInfo &MRI = MF.getRegInfo(); 2086 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2087 CCInfo.AllocateReg(InputPtrReg); 2088 2089 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2090 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2091 } 2092 2093 if (Info.hasDispatchID()) { 2094 Register DispatchIDReg = Info.addDispatchID(TRI); 2095 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2096 CCInfo.AllocateReg(DispatchIDReg); 2097 } 2098 2099 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2100 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2101 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2102 CCInfo.AllocateReg(FlatScratchInitReg); 2103 } 2104 2105 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2106 // these from the dispatch pointer. 2107 } 2108 2109 // Allocate special input registers that are initialized per-wave. 2110 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2111 MachineFunction &MF, 2112 SIMachineFunctionInfo &Info, 2113 CallingConv::ID CallConv, 2114 bool IsShader) const { 2115 if (Info.hasWorkGroupIDX()) { 2116 Register Reg = Info.addWorkGroupIDX(); 2117 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2118 CCInfo.AllocateReg(Reg); 2119 } 2120 2121 if (Info.hasWorkGroupIDY()) { 2122 Register Reg = Info.addWorkGroupIDY(); 2123 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2124 CCInfo.AllocateReg(Reg); 2125 } 2126 2127 if (Info.hasWorkGroupIDZ()) { 2128 Register Reg = Info.addWorkGroupIDZ(); 2129 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2130 CCInfo.AllocateReg(Reg); 2131 } 2132 2133 if (Info.hasWorkGroupInfo()) { 2134 Register Reg = Info.addWorkGroupInfo(); 2135 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2136 CCInfo.AllocateReg(Reg); 2137 } 2138 2139 if (Info.hasPrivateSegmentWaveByteOffset()) { 2140 // Scratch wave offset passed in system SGPR. 2141 unsigned PrivateSegmentWaveByteOffsetReg; 2142 2143 if (IsShader) { 2144 PrivateSegmentWaveByteOffsetReg = 2145 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2146 2147 // This is true if the scratch wave byte offset doesn't have a fixed 2148 // location. 2149 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2150 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2151 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2152 } 2153 } else 2154 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2155 2156 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2157 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2158 } 2159 } 2160 2161 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2162 MachineFunction &MF, 2163 const SIRegisterInfo &TRI, 2164 SIMachineFunctionInfo &Info) { 2165 // Now that we've figured out where the scratch register inputs are, see if 2166 // should reserve the arguments and use them directly. 2167 MachineFrameInfo &MFI = MF.getFrameInfo(); 2168 bool HasStackObjects = MFI.hasStackObjects(); 2169 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2170 2171 // Record that we know we have non-spill stack objects so we don't need to 2172 // check all stack objects later. 2173 if (HasStackObjects) 2174 Info.setHasNonSpillStackObjects(true); 2175 2176 // Everything live out of a block is spilled with fast regalloc, so it's 2177 // almost certain that spilling will be required. 2178 if (TM.getOptLevel() == CodeGenOpt::None) 2179 HasStackObjects = true; 2180 2181 // For now assume stack access is needed in any callee functions, so we need 2182 // the scratch registers to pass in. 2183 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2184 2185 if (!ST.enableFlatScratch()) { 2186 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2187 // If we have stack objects, we unquestionably need the private buffer 2188 // resource. For the Code Object V2 ABI, this will be the first 4 user 2189 // SGPR inputs. We can reserve those and use them directly. 2190 2191 Register PrivateSegmentBufferReg = 2192 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2193 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2194 } else { 2195 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2196 // We tentatively reserve the last registers (skipping the last registers 2197 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2198 // we'll replace these with the ones immediately after those which were 2199 // really allocated. In the prologue copies will be inserted from the 2200 // argument to these reserved registers. 2201 2202 // Without HSA, relocations are used for the scratch pointer and the 2203 // buffer resource setup is always inserted in the prologue. Scratch wave 2204 // offset is still in an input SGPR. 2205 Info.setScratchRSrcReg(ReservedBufferReg); 2206 } 2207 } 2208 2209 MachineRegisterInfo &MRI = MF.getRegInfo(); 2210 2211 // For entry functions we have to set up the stack pointer if we use it, 2212 // whereas non-entry functions get this "for free". This means there is no 2213 // intrinsic advantage to using S32 over S34 in cases where we do not have 2214 // calls but do need a frame pointer (i.e. if we are requested to have one 2215 // because frame pointer elimination is disabled). To keep things simple we 2216 // only ever use S32 as the call ABI stack pointer, and so using it does not 2217 // imply we need a separate frame pointer. 2218 // 2219 // Try to use s32 as the SP, but move it if it would interfere with input 2220 // arguments. This won't work with calls though. 2221 // 2222 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2223 // registers. 2224 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2225 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2226 } else { 2227 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2228 2229 if (MFI.hasCalls()) 2230 report_fatal_error("call in graphics shader with too many input SGPRs"); 2231 2232 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2233 if (!MRI.isLiveIn(Reg)) { 2234 Info.setStackPtrOffsetReg(Reg); 2235 break; 2236 } 2237 } 2238 2239 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2240 report_fatal_error("failed to find register for SP"); 2241 } 2242 2243 // hasFP should be accurate for entry functions even before the frame is 2244 // finalized, because it does not rely on the known stack size, only 2245 // properties like whether variable sized objects are present. 2246 if (ST.getFrameLowering()->hasFP(MF)) { 2247 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2248 } 2249 } 2250 2251 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2252 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2253 return !Info->isEntryFunction(); 2254 } 2255 2256 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2257 2258 } 2259 2260 void SITargetLowering::insertCopiesSplitCSR( 2261 MachineBasicBlock *Entry, 2262 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2263 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2264 2265 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2266 if (!IStart) 2267 return; 2268 2269 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2270 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2271 MachineBasicBlock::iterator MBBI = Entry->begin(); 2272 for (const MCPhysReg *I = IStart; *I; ++I) { 2273 const TargetRegisterClass *RC = nullptr; 2274 if (AMDGPU::SReg_64RegClass.contains(*I)) 2275 RC = &AMDGPU::SGPR_64RegClass; 2276 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2277 RC = &AMDGPU::SGPR_32RegClass; 2278 else 2279 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2280 2281 Register NewVR = MRI->createVirtualRegister(RC); 2282 // Create copy from CSR to a virtual register. 2283 Entry->addLiveIn(*I); 2284 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2285 .addReg(*I); 2286 2287 // Insert the copy-back instructions right before the terminator. 2288 for (auto *Exit : Exits) 2289 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2290 TII->get(TargetOpcode::COPY), *I) 2291 .addReg(NewVR); 2292 } 2293 } 2294 2295 SDValue SITargetLowering::LowerFormalArguments( 2296 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2297 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2298 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2299 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2300 2301 MachineFunction &MF = DAG.getMachineFunction(); 2302 const Function &Fn = MF.getFunction(); 2303 FunctionType *FType = MF.getFunction().getFunctionType(); 2304 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2305 2306 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2307 DiagnosticInfoUnsupported NoGraphicsHSA( 2308 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2309 DAG.getContext()->diagnose(NoGraphicsHSA); 2310 return DAG.getEntryNode(); 2311 } 2312 2313 Info->allocateModuleLDSGlobal(Fn.getParent()); 2314 2315 SmallVector<ISD::InputArg, 16> Splits; 2316 SmallVector<CCValAssign, 16> ArgLocs; 2317 BitVector Skipped(Ins.size()); 2318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2319 *DAG.getContext()); 2320 2321 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2322 bool IsKernel = AMDGPU::isKernel(CallConv); 2323 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2324 2325 if (IsGraphics) { 2326 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2327 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2328 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2329 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2330 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2331 !Info->hasWorkItemIDZ()); 2332 } 2333 2334 if (CallConv == CallingConv::AMDGPU_PS) { 2335 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2336 2337 // At least one interpolation mode must be enabled or else the GPU will 2338 // hang. 2339 // 2340 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2341 // set PSInputAddr, the user wants to enable some bits after the compilation 2342 // based on run-time states. Since we can't know what the final PSInputEna 2343 // will look like, so we shouldn't do anything here and the user should take 2344 // responsibility for the correct programming. 2345 // 2346 // Otherwise, the following restrictions apply: 2347 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2348 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2349 // enabled too. 2350 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2351 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2352 CCInfo.AllocateReg(AMDGPU::VGPR0); 2353 CCInfo.AllocateReg(AMDGPU::VGPR1); 2354 Info->markPSInputAllocated(0); 2355 Info->markPSInputEnabled(0); 2356 } 2357 if (Subtarget->isAmdPalOS()) { 2358 // For isAmdPalOS, the user does not enable some bits after compilation 2359 // based on run-time states; the register values being generated here are 2360 // the final ones set in hardware. Therefore we need to apply the 2361 // workaround to PSInputAddr and PSInputEnable together. (The case where 2362 // a bit is set in PSInputAddr but not PSInputEnable is where the 2363 // frontend set up an input arg for a particular interpolation mode, but 2364 // nothing uses that input arg. Really we should have an earlier pass 2365 // that removes such an arg.) 2366 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2367 if ((PsInputBits & 0x7F) == 0 || 2368 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2369 Info->markPSInputEnabled( 2370 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2371 } 2372 } else if (IsKernel) { 2373 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2374 } else { 2375 Splits.append(Ins.begin(), Ins.end()); 2376 } 2377 2378 if (IsEntryFunc) { 2379 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2380 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2381 } else { 2382 // For the fixed ABI, pass workitem IDs in the last argument register. 2383 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2384 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2385 } 2386 2387 if (IsKernel) { 2388 analyzeFormalArgumentsCompute(CCInfo, Ins); 2389 } else { 2390 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2391 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2392 } 2393 2394 SmallVector<SDValue, 16> Chains; 2395 2396 // FIXME: This is the minimum kernel argument alignment. We should improve 2397 // this to the maximum alignment of the arguments. 2398 // 2399 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2400 // kern arg offset. 2401 const Align KernelArgBaseAlign = Align(16); 2402 2403 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2404 const ISD::InputArg &Arg = Ins[i]; 2405 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2406 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2407 continue; 2408 } 2409 2410 CCValAssign &VA = ArgLocs[ArgIdx++]; 2411 MVT VT = VA.getLocVT(); 2412 2413 if (IsEntryFunc && VA.isMemLoc()) { 2414 VT = Ins[i].VT; 2415 EVT MemVT = VA.getLocVT(); 2416 2417 const uint64_t Offset = VA.getLocMemOffset(); 2418 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2419 2420 if (Arg.Flags.isByRef()) { 2421 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2422 2423 const GCNTargetMachine &TM = 2424 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2425 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2426 Arg.Flags.getPointerAddrSpace())) { 2427 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2428 Arg.Flags.getPointerAddrSpace()); 2429 } 2430 2431 InVals.push_back(Ptr); 2432 continue; 2433 } 2434 2435 SDValue Arg = lowerKernargMemParameter( 2436 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2437 Chains.push_back(Arg.getValue(1)); 2438 2439 auto *ParamTy = 2440 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2441 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2442 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2443 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2444 // On SI local pointers are just offsets into LDS, so they are always 2445 // less than 16-bits. On CI and newer they could potentially be 2446 // real pointers, so we can't guarantee their size. 2447 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2448 DAG.getValueType(MVT::i16)); 2449 } 2450 2451 InVals.push_back(Arg); 2452 continue; 2453 } else if (!IsEntryFunc && VA.isMemLoc()) { 2454 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2455 InVals.push_back(Val); 2456 if (!Arg.Flags.isByVal()) 2457 Chains.push_back(Val.getValue(1)); 2458 continue; 2459 } 2460 2461 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2462 2463 Register Reg = VA.getLocReg(); 2464 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2465 EVT ValVT = VA.getValVT(); 2466 2467 Reg = MF.addLiveIn(Reg, RC); 2468 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2469 2470 if (Arg.Flags.isSRet()) { 2471 // The return object should be reasonably addressable. 2472 2473 // FIXME: This helps when the return is a real sret. If it is a 2474 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2475 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2476 unsigned NumBits 2477 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2478 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2479 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2480 } 2481 2482 // If this is an 8 or 16-bit value, it is really passed promoted 2483 // to 32 bits. Insert an assert[sz]ext to capture this, then 2484 // truncate to the right size. 2485 switch (VA.getLocInfo()) { 2486 case CCValAssign::Full: 2487 break; 2488 case CCValAssign::BCvt: 2489 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2490 break; 2491 case CCValAssign::SExt: 2492 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2493 DAG.getValueType(ValVT)); 2494 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2495 break; 2496 case CCValAssign::ZExt: 2497 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2498 DAG.getValueType(ValVT)); 2499 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2500 break; 2501 case CCValAssign::AExt: 2502 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2503 break; 2504 default: 2505 llvm_unreachable("Unknown loc info!"); 2506 } 2507 2508 InVals.push_back(Val); 2509 } 2510 2511 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2512 // Special inputs come after user arguments. 2513 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2514 } 2515 2516 // Start adding system SGPRs. 2517 if (IsEntryFunc) { 2518 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2519 } else { 2520 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2521 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2522 } 2523 2524 auto &ArgUsageInfo = 2525 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2526 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2527 2528 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2529 Info->setBytesInStackArgArea(StackArgSize); 2530 2531 return Chains.empty() ? Chain : 2532 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2533 } 2534 2535 // TODO: If return values can't fit in registers, we should return as many as 2536 // possible in registers before passing on stack. 2537 bool SITargetLowering::CanLowerReturn( 2538 CallingConv::ID CallConv, 2539 MachineFunction &MF, bool IsVarArg, 2540 const SmallVectorImpl<ISD::OutputArg> &Outs, 2541 LLVMContext &Context) const { 2542 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2543 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2544 // for shaders. Vector types should be explicitly handled by CC. 2545 if (AMDGPU::isEntryFunctionCC(CallConv)) 2546 return true; 2547 2548 SmallVector<CCValAssign, 16> RVLocs; 2549 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2550 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2551 } 2552 2553 SDValue 2554 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2555 bool isVarArg, 2556 const SmallVectorImpl<ISD::OutputArg> &Outs, 2557 const SmallVectorImpl<SDValue> &OutVals, 2558 const SDLoc &DL, SelectionDAG &DAG) const { 2559 MachineFunction &MF = DAG.getMachineFunction(); 2560 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2561 2562 if (AMDGPU::isKernel(CallConv)) { 2563 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2564 OutVals, DL, DAG); 2565 } 2566 2567 bool IsShader = AMDGPU::isShader(CallConv); 2568 2569 Info->setIfReturnsVoid(Outs.empty()); 2570 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2571 2572 // CCValAssign - represent the assignment of the return value to a location. 2573 SmallVector<CCValAssign, 48> RVLocs; 2574 SmallVector<ISD::OutputArg, 48> Splits; 2575 2576 // CCState - Info about the registers and stack slots. 2577 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2578 *DAG.getContext()); 2579 2580 // Analyze outgoing return values. 2581 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2582 2583 SDValue Flag; 2584 SmallVector<SDValue, 48> RetOps; 2585 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2586 2587 // Add return address for callable functions. 2588 if (!Info->isEntryFunction()) { 2589 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2590 SDValue ReturnAddrReg = CreateLiveInRegister( 2591 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2592 2593 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2594 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2595 MVT::i64); 2596 Chain = 2597 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2598 Flag = Chain.getValue(1); 2599 RetOps.push_back(ReturnAddrVirtualReg); 2600 } 2601 2602 // Copy the result values into the output registers. 2603 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2604 ++I, ++RealRVLocIdx) { 2605 CCValAssign &VA = RVLocs[I]; 2606 assert(VA.isRegLoc() && "Can only return in registers!"); 2607 // TODO: Partially return in registers if return values don't fit. 2608 SDValue Arg = OutVals[RealRVLocIdx]; 2609 2610 // Copied from other backends. 2611 switch (VA.getLocInfo()) { 2612 case CCValAssign::Full: 2613 break; 2614 case CCValAssign::BCvt: 2615 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2616 break; 2617 case CCValAssign::SExt: 2618 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2619 break; 2620 case CCValAssign::ZExt: 2621 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2622 break; 2623 case CCValAssign::AExt: 2624 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2625 break; 2626 default: 2627 llvm_unreachable("Unknown loc info!"); 2628 } 2629 2630 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2631 Flag = Chain.getValue(1); 2632 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2633 } 2634 2635 // FIXME: Does sret work properly? 2636 if (!Info->isEntryFunction()) { 2637 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2638 const MCPhysReg *I = 2639 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2640 if (I) { 2641 for (; *I; ++I) { 2642 if (AMDGPU::SReg_64RegClass.contains(*I)) 2643 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2644 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2645 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2646 else 2647 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2648 } 2649 } 2650 } 2651 2652 // Update chain and glue. 2653 RetOps[0] = Chain; 2654 if (Flag.getNode()) 2655 RetOps.push_back(Flag); 2656 2657 unsigned Opc = AMDGPUISD::ENDPGM; 2658 if (!IsWaveEnd) 2659 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2660 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2661 } 2662 2663 SDValue SITargetLowering::LowerCallResult( 2664 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2665 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2666 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2667 SDValue ThisVal) const { 2668 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2669 2670 // Assign locations to each value returned by this call. 2671 SmallVector<CCValAssign, 16> RVLocs; 2672 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2673 *DAG.getContext()); 2674 CCInfo.AnalyzeCallResult(Ins, RetCC); 2675 2676 // Copy all of the result registers out of their specified physreg. 2677 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2678 CCValAssign VA = RVLocs[i]; 2679 SDValue Val; 2680 2681 if (VA.isRegLoc()) { 2682 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2683 Chain = Val.getValue(1); 2684 InFlag = Val.getValue(2); 2685 } else if (VA.isMemLoc()) { 2686 report_fatal_error("TODO: return values in memory"); 2687 } else 2688 llvm_unreachable("unknown argument location type"); 2689 2690 switch (VA.getLocInfo()) { 2691 case CCValAssign::Full: 2692 break; 2693 case CCValAssign::BCvt: 2694 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2695 break; 2696 case CCValAssign::ZExt: 2697 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2698 DAG.getValueType(VA.getValVT())); 2699 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2700 break; 2701 case CCValAssign::SExt: 2702 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2703 DAG.getValueType(VA.getValVT())); 2704 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2705 break; 2706 case CCValAssign::AExt: 2707 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2708 break; 2709 default: 2710 llvm_unreachable("Unknown loc info!"); 2711 } 2712 2713 InVals.push_back(Val); 2714 } 2715 2716 return Chain; 2717 } 2718 2719 // Add code to pass special inputs required depending on used features separate 2720 // from the explicit user arguments present in the IR. 2721 void SITargetLowering::passSpecialInputs( 2722 CallLoweringInfo &CLI, 2723 CCState &CCInfo, 2724 const SIMachineFunctionInfo &Info, 2725 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2726 SmallVectorImpl<SDValue> &MemOpChains, 2727 SDValue Chain) const { 2728 // If we don't have a call site, this was a call inserted by 2729 // legalization. These can never use special inputs. 2730 if (!CLI.CB) 2731 return; 2732 2733 SelectionDAG &DAG = CLI.DAG; 2734 const SDLoc &DL = CLI.DL; 2735 2736 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2737 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2738 2739 const AMDGPUFunctionArgInfo *CalleeArgInfo 2740 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2741 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2742 auto &ArgUsageInfo = 2743 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2744 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2745 } 2746 2747 // TODO: Unify with private memory register handling. This is complicated by 2748 // the fact that at least in kernels, the input argument is not necessarily 2749 // in the same location as the input. 2750 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2751 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2752 AMDGPUFunctionArgInfo::QUEUE_PTR, 2753 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2754 AMDGPUFunctionArgInfo::DISPATCH_ID, 2755 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2756 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2757 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2758 }; 2759 2760 for (auto InputID : InputRegs) { 2761 const ArgDescriptor *OutgoingArg; 2762 const TargetRegisterClass *ArgRC; 2763 LLT ArgTy; 2764 2765 std::tie(OutgoingArg, ArgRC, ArgTy) = 2766 CalleeArgInfo->getPreloadedValue(InputID); 2767 if (!OutgoingArg) 2768 continue; 2769 2770 const ArgDescriptor *IncomingArg; 2771 const TargetRegisterClass *IncomingArgRC; 2772 LLT Ty; 2773 std::tie(IncomingArg, IncomingArgRC, Ty) = 2774 CallerArgInfo.getPreloadedValue(InputID); 2775 assert(IncomingArgRC == ArgRC); 2776 2777 // All special arguments are ints for now. 2778 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2779 SDValue InputReg; 2780 2781 if (IncomingArg) { 2782 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2783 } else { 2784 // The implicit arg ptr is special because it doesn't have a corresponding 2785 // input for kernels, and is computed from the kernarg segment pointer. 2786 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2787 InputReg = getImplicitArgPtr(DAG, DL); 2788 } 2789 2790 if (OutgoingArg->isRegister()) { 2791 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2792 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2793 report_fatal_error("failed to allocate implicit input argument"); 2794 } else { 2795 unsigned SpecialArgOffset = 2796 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2797 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2798 SpecialArgOffset); 2799 MemOpChains.push_back(ArgStore); 2800 } 2801 } 2802 2803 // Pack workitem IDs into a single register or pass it as is if already 2804 // packed. 2805 const ArgDescriptor *OutgoingArg; 2806 const TargetRegisterClass *ArgRC; 2807 LLT Ty; 2808 2809 std::tie(OutgoingArg, ArgRC, Ty) = 2810 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2811 if (!OutgoingArg) 2812 std::tie(OutgoingArg, ArgRC, Ty) = 2813 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2814 if (!OutgoingArg) 2815 std::tie(OutgoingArg, ArgRC, Ty) = 2816 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2817 if (!OutgoingArg) 2818 return; 2819 2820 const ArgDescriptor *IncomingArgX = std::get<0>( 2821 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2822 const ArgDescriptor *IncomingArgY = std::get<0>( 2823 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2824 const ArgDescriptor *IncomingArgZ = std::get<0>( 2825 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2826 2827 SDValue InputReg; 2828 SDLoc SL; 2829 2830 // If incoming ids are not packed we need to pack them. 2831 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2832 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2833 2834 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2835 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2836 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2837 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2838 InputReg = InputReg.getNode() ? 2839 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2840 } 2841 2842 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2843 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2844 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2845 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2846 InputReg = InputReg.getNode() ? 2847 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2848 } 2849 2850 if (!InputReg.getNode()) { 2851 // Workitem ids are already packed, any of present incoming arguments 2852 // will carry all required fields. 2853 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2854 IncomingArgX ? *IncomingArgX : 2855 IncomingArgY ? *IncomingArgY : 2856 *IncomingArgZ, ~0u); 2857 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2858 } 2859 2860 if (OutgoingArg->isRegister()) { 2861 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2862 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2863 } else { 2864 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2865 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2866 SpecialArgOffset); 2867 MemOpChains.push_back(ArgStore); 2868 } 2869 } 2870 2871 static bool canGuaranteeTCO(CallingConv::ID CC) { 2872 return CC == CallingConv::Fast; 2873 } 2874 2875 /// Return true if we might ever do TCO for calls with this calling convention. 2876 static bool mayTailCallThisCC(CallingConv::ID CC) { 2877 switch (CC) { 2878 case CallingConv::C: 2879 case CallingConv::AMDGPU_Gfx: 2880 return true; 2881 default: 2882 return canGuaranteeTCO(CC); 2883 } 2884 } 2885 2886 bool SITargetLowering::isEligibleForTailCallOptimization( 2887 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2888 const SmallVectorImpl<ISD::OutputArg> &Outs, 2889 const SmallVectorImpl<SDValue> &OutVals, 2890 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2891 if (!mayTailCallThisCC(CalleeCC)) 2892 return false; 2893 2894 // For a divergent call target, we need to do a waterfall loop over the 2895 // possible callees which precludes us from using a simple jump. 2896 if (Callee->isDivergent()) 2897 return false; 2898 2899 MachineFunction &MF = DAG.getMachineFunction(); 2900 const Function &CallerF = MF.getFunction(); 2901 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2902 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2903 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2904 2905 // Kernels aren't callable, and don't have a live in return address so it 2906 // doesn't make sense to do a tail call with entry functions. 2907 if (!CallerPreserved) 2908 return false; 2909 2910 bool CCMatch = CallerCC == CalleeCC; 2911 2912 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2913 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2914 return true; 2915 return false; 2916 } 2917 2918 // TODO: Can we handle var args? 2919 if (IsVarArg) 2920 return false; 2921 2922 for (const Argument &Arg : CallerF.args()) { 2923 if (Arg.hasByValAttr()) 2924 return false; 2925 } 2926 2927 LLVMContext &Ctx = *DAG.getContext(); 2928 2929 // Check that the call results are passed in the same way. 2930 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2931 CCAssignFnForCall(CalleeCC, IsVarArg), 2932 CCAssignFnForCall(CallerCC, IsVarArg))) 2933 return false; 2934 2935 // The callee has to preserve all registers the caller needs to preserve. 2936 if (!CCMatch) { 2937 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2938 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2939 return false; 2940 } 2941 2942 // Nothing more to check if the callee is taking no arguments. 2943 if (Outs.empty()) 2944 return true; 2945 2946 SmallVector<CCValAssign, 16> ArgLocs; 2947 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2948 2949 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2950 2951 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2952 // If the stack arguments for this call do not fit into our own save area then 2953 // the call cannot be made tail. 2954 // TODO: Is this really necessary? 2955 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2956 return false; 2957 2958 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2959 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2960 } 2961 2962 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2963 if (!CI->isTailCall()) 2964 return false; 2965 2966 const Function *ParentFn = CI->getParent()->getParent(); 2967 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2968 return false; 2969 return true; 2970 } 2971 2972 // The wave scratch offset register is used as the global base pointer. 2973 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2974 SmallVectorImpl<SDValue> &InVals) const { 2975 SelectionDAG &DAG = CLI.DAG; 2976 const SDLoc &DL = CLI.DL; 2977 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2978 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2979 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2980 SDValue Chain = CLI.Chain; 2981 SDValue Callee = CLI.Callee; 2982 bool &IsTailCall = CLI.IsTailCall; 2983 CallingConv::ID CallConv = CLI.CallConv; 2984 bool IsVarArg = CLI.IsVarArg; 2985 bool IsSibCall = false; 2986 bool IsThisReturn = false; 2987 MachineFunction &MF = DAG.getMachineFunction(); 2988 2989 if (Callee.isUndef() || isNullConstant(Callee)) { 2990 if (!CLI.IsTailCall) { 2991 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2992 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2993 } 2994 2995 return Chain; 2996 } 2997 2998 if (IsVarArg) { 2999 return lowerUnhandledCall(CLI, InVals, 3000 "unsupported call to variadic function "); 3001 } 3002 3003 if (!CLI.CB) 3004 report_fatal_error("unsupported libcall legalization"); 3005 3006 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3007 return lowerUnhandledCall(CLI, InVals, 3008 "unsupported required tail call to function "); 3009 } 3010 3011 if (AMDGPU::isShader(CallConv)) { 3012 // Note the issue is with the CC of the called function, not of the call 3013 // itself. 3014 return lowerUnhandledCall(CLI, InVals, 3015 "unsupported call to a shader function "); 3016 } 3017 3018 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3019 CallConv != CallingConv::AMDGPU_Gfx) { 3020 // Only allow calls with specific calling conventions. 3021 return lowerUnhandledCall(CLI, InVals, 3022 "unsupported calling convention for call from " 3023 "graphics shader of function "); 3024 } 3025 3026 if (IsTailCall) { 3027 IsTailCall = isEligibleForTailCallOptimization( 3028 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3029 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3030 report_fatal_error("failed to perform tail call elimination on a call " 3031 "site marked musttail"); 3032 } 3033 3034 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3035 3036 // A sibling call is one where we're under the usual C ABI and not planning 3037 // to change that but can still do a tail call: 3038 if (!TailCallOpt && IsTailCall) 3039 IsSibCall = true; 3040 3041 if (IsTailCall) 3042 ++NumTailCalls; 3043 } 3044 3045 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3046 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3047 SmallVector<SDValue, 8> MemOpChains; 3048 3049 // Analyze operands of the call, assigning locations to each operand. 3050 SmallVector<CCValAssign, 16> ArgLocs; 3051 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3052 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3053 3054 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3055 CallConv != CallingConv::AMDGPU_Gfx) { 3056 // With a fixed ABI, allocate fixed registers before user arguments. 3057 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3058 } 3059 3060 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3061 3062 // Get a count of how many bytes are to be pushed on the stack. 3063 unsigned NumBytes = CCInfo.getNextStackOffset(); 3064 3065 if (IsSibCall) { 3066 // Since we're not changing the ABI to make this a tail call, the memory 3067 // operands are already available in the caller's incoming argument space. 3068 NumBytes = 0; 3069 } 3070 3071 // FPDiff is the byte offset of the call's argument area from the callee's. 3072 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3073 // by this amount for a tail call. In a sibling call it must be 0 because the 3074 // caller will deallocate the entire stack and the callee still expects its 3075 // arguments to begin at SP+0. Completely unused for non-tail calls. 3076 int32_t FPDiff = 0; 3077 MachineFrameInfo &MFI = MF.getFrameInfo(); 3078 3079 // Adjust the stack pointer for the new arguments... 3080 // These operations are automatically eliminated by the prolog/epilog pass 3081 if (!IsSibCall) { 3082 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3083 3084 if (!Subtarget->enableFlatScratch()) { 3085 SmallVector<SDValue, 4> CopyFromChains; 3086 3087 // In the HSA case, this should be an identity copy. 3088 SDValue ScratchRSrcReg 3089 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3090 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3091 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3092 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3093 } 3094 } 3095 3096 MVT PtrVT = MVT::i32; 3097 3098 // Walk the register/memloc assignments, inserting copies/loads. 3099 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3100 CCValAssign &VA = ArgLocs[i]; 3101 SDValue Arg = OutVals[i]; 3102 3103 // Promote the value if needed. 3104 switch (VA.getLocInfo()) { 3105 case CCValAssign::Full: 3106 break; 3107 case CCValAssign::BCvt: 3108 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3109 break; 3110 case CCValAssign::ZExt: 3111 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3112 break; 3113 case CCValAssign::SExt: 3114 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3115 break; 3116 case CCValAssign::AExt: 3117 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3118 break; 3119 case CCValAssign::FPExt: 3120 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3121 break; 3122 default: 3123 llvm_unreachable("Unknown loc info!"); 3124 } 3125 3126 if (VA.isRegLoc()) { 3127 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3128 } else { 3129 assert(VA.isMemLoc()); 3130 3131 SDValue DstAddr; 3132 MachinePointerInfo DstInfo; 3133 3134 unsigned LocMemOffset = VA.getLocMemOffset(); 3135 int32_t Offset = LocMemOffset; 3136 3137 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3138 MaybeAlign Alignment; 3139 3140 if (IsTailCall) { 3141 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3142 unsigned OpSize = Flags.isByVal() ? 3143 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3144 3145 // FIXME: We can have better than the minimum byval required alignment. 3146 Alignment = 3147 Flags.isByVal() 3148 ? Flags.getNonZeroByValAlign() 3149 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3150 3151 Offset = Offset + FPDiff; 3152 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3153 3154 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3155 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3156 3157 // Make sure any stack arguments overlapping with where we're storing 3158 // are loaded before this eventual operation. Otherwise they'll be 3159 // clobbered. 3160 3161 // FIXME: Why is this really necessary? This seems to just result in a 3162 // lot of code to copy the stack and write them back to the same 3163 // locations, which are supposed to be immutable? 3164 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3165 } else { 3166 // Stores to the argument stack area are relative to the stack pointer. 3167 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3168 MVT::i32); 3169 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3170 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3171 Alignment = 3172 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3173 } 3174 3175 if (Outs[i].Flags.isByVal()) { 3176 SDValue SizeNode = 3177 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3178 SDValue Cpy = 3179 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3180 Outs[i].Flags.getNonZeroByValAlign(), 3181 /*isVol = */ false, /*AlwaysInline = */ true, 3182 /*isTailCall = */ false, DstInfo, 3183 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3184 3185 MemOpChains.push_back(Cpy); 3186 } else { 3187 SDValue Store = 3188 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3189 MemOpChains.push_back(Store); 3190 } 3191 } 3192 } 3193 3194 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3195 CallConv != CallingConv::AMDGPU_Gfx) { 3196 // Copy special input registers after user input arguments. 3197 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3198 } 3199 3200 if (!MemOpChains.empty()) 3201 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3202 3203 // Build a sequence of copy-to-reg nodes chained together with token chain 3204 // and flag operands which copy the outgoing args into the appropriate regs. 3205 SDValue InFlag; 3206 for (auto &RegToPass : RegsToPass) { 3207 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3208 RegToPass.second, InFlag); 3209 InFlag = Chain.getValue(1); 3210 } 3211 3212 3213 SDValue PhysReturnAddrReg; 3214 if (IsTailCall) { 3215 // Since the return is being combined with the call, we need to pass on the 3216 // return address. 3217 3218 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3219 SDValue ReturnAddrReg = CreateLiveInRegister( 3220 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3221 3222 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3223 MVT::i64); 3224 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3225 InFlag = Chain.getValue(1); 3226 } 3227 3228 // We don't usually want to end the call-sequence here because we would tidy 3229 // the frame up *after* the call, however in the ABI-changing tail-call case 3230 // we've carefully laid out the parameters so that when sp is reset they'll be 3231 // in the correct location. 3232 if (IsTailCall && !IsSibCall) { 3233 Chain = DAG.getCALLSEQ_END(Chain, 3234 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3235 DAG.getTargetConstant(0, DL, MVT::i32), 3236 InFlag, DL); 3237 InFlag = Chain.getValue(1); 3238 } 3239 3240 std::vector<SDValue> Ops; 3241 Ops.push_back(Chain); 3242 Ops.push_back(Callee); 3243 // Add a redundant copy of the callee global which will not be legalized, as 3244 // we need direct access to the callee later. 3245 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3246 const GlobalValue *GV = GSD->getGlobal(); 3247 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3248 } else { 3249 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3250 } 3251 3252 if (IsTailCall) { 3253 // Each tail call may have to adjust the stack by a different amount, so 3254 // this information must travel along with the operation for eventual 3255 // consumption by emitEpilogue. 3256 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3257 3258 Ops.push_back(PhysReturnAddrReg); 3259 } 3260 3261 // Add argument registers to the end of the list so that they are known live 3262 // into the call. 3263 for (auto &RegToPass : RegsToPass) { 3264 Ops.push_back(DAG.getRegister(RegToPass.first, 3265 RegToPass.second.getValueType())); 3266 } 3267 3268 // Add a register mask operand representing the call-preserved registers. 3269 3270 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3271 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3272 assert(Mask && "Missing call preserved mask for calling convention"); 3273 Ops.push_back(DAG.getRegisterMask(Mask)); 3274 3275 if (InFlag.getNode()) 3276 Ops.push_back(InFlag); 3277 3278 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3279 3280 // If we're doing a tall call, use a TC_RETURN here rather than an 3281 // actual call instruction. 3282 if (IsTailCall) { 3283 MFI.setHasTailCall(); 3284 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3285 } 3286 3287 // Returns a chain and a flag for retval copy to use. 3288 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3289 Chain = Call.getValue(0); 3290 InFlag = Call.getValue(1); 3291 3292 uint64_t CalleePopBytes = NumBytes; 3293 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3294 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3295 InFlag, DL); 3296 if (!Ins.empty()) 3297 InFlag = Chain.getValue(1); 3298 3299 // Handle result values, copying them out of physregs into vregs that we 3300 // return. 3301 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3302 InVals, IsThisReturn, 3303 IsThisReturn ? OutVals[0] : SDValue()); 3304 } 3305 3306 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3307 // except for applying the wave size scale to the increment amount. 3308 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3309 SDValue Op, SelectionDAG &DAG) const { 3310 const MachineFunction &MF = DAG.getMachineFunction(); 3311 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3312 3313 SDLoc dl(Op); 3314 EVT VT = Op.getValueType(); 3315 SDValue Tmp1 = Op; 3316 SDValue Tmp2 = Op.getValue(1); 3317 SDValue Tmp3 = Op.getOperand(2); 3318 SDValue Chain = Tmp1.getOperand(0); 3319 3320 Register SPReg = Info->getStackPtrOffsetReg(); 3321 3322 // Chain the dynamic stack allocation so that it doesn't modify the stack 3323 // pointer when other instructions are using the stack. 3324 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3325 3326 SDValue Size = Tmp2.getOperand(1); 3327 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3328 Chain = SP.getValue(1); 3329 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3330 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3331 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3332 unsigned Opc = 3333 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3334 ISD::ADD : ISD::SUB; 3335 3336 SDValue ScaledSize = DAG.getNode( 3337 ISD::SHL, dl, VT, Size, 3338 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3339 3340 Align StackAlign = TFL->getStackAlign(); 3341 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3342 if (Alignment && *Alignment > StackAlign) { 3343 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3344 DAG.getConstant(-(uint64_t)Alignment->value() 3345 << ST.getWavefrontSizeLog2(), 3346 dl, VT)); 3347 } 3348 3349 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3350 Tmp2 = DAG.getCALLSEQ_END( 3351 Chain, DAG.getIntPtrConstant(0, dl, true), 3352 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3353 3354 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3355 } 3356 3357 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3358 SelectionDAG &DAG) const { 3359 // We only handle constant sizes here to allow non-entry block, static sized 3360 // allocas. A truly dynamic value is more difficult to support because we 3361 // don't know if the size value is uniform or not. If the size isn't uniform, 3362 // we would need to do a wave reduction to get the maximum size to know how 3363 // much to increment the uniform stack pointer. 3364 SDValue Size = Op.getOperand(1); 3365 if (isa<ConstantSDNode>(Size)) 3366 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3367 3368 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3369 } 3370 3371 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3372 const MachineFunction &MF) const { 3373 Register Reg = StringSwitch<Register>(RegName) 3374 .Case("m0", AMDGPU::M0) 3375 .Case("exec", AMDGPU::EXEC) 3376 .Case("exec_lo", AMDGPU::EXEC_LO) 3377 .Case("exec_hi", AMDGPU::EXEC_HI) 3378 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3379 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3380 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3381 .Default(Register()); 3382 3383 if (Reg == AMDGPU::NoRegister) { 3384 report_fatal_error(Twine("invalid register name \"" 3385 + StringRef(RegName) + "\".")); 3386 3387 } 3388 3389 if (!Subtarget->hasFlatScrRegister() && 3390 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3391 report_fatal_error(Twine("invalid register \"" 3392 + StringRef(RegName) + "\" for subtarget.")); 3393 } 3394 3395 switch (Reg) { 3396 case AMDGPU::M0: 3397 case AMDGPU::EXEC_LO: 3398 case AMDGPU::EXEC_HI: 3399 case AMDGPU::FLAT_SCR_LO: 3400 case AMDGPU::FLAT_SCR_HI: 3401 if (VT.getSizeInBits() == 32) 3402 return Reg; 3403 break; 3404 case AMDGPU::EXEC: 3405 case AMDGPU::FLAT_SCR: 3406 if (VT.getSizeInBits() == 64) 3407 return Reg; 3408 break; 3409 default: 3410 llvm_unreachable("missing register type checking"); 3411 } 3412 3413 report_fatal_error(Twine("invalid type for register \"" 3414 + StringRef(RegName) + "\".")); 3415 } 3416 3417 // If kill is not the last instruction, split the block so kill is always a 3418 // proper terminator. 3419 MachineBasicBlock * 3420 SITargetLowering::splitKillBlock(MachineInstr &MI, 3421 MachineBasicBlock *BB) const { 3422 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3423 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3424 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3425 return SplitBB; 3426 } 3427 3428 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3429 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3430 // be the first instruction in the remainder block. 3431 // 3432 /// \returns { LoopBody, Remainder } 3433 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3434 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3435 MachineFunction *MF = MBB.getParent(); 3436 MachineBasicBlock::iterator I(&MI); 3437 3438 // To insert the loop we need to split the block. Move everything after this 3439 // point to a new block, and insert a new empty block between the two. 3440 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3441 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3442 MachineFunction::iterator MBBI(MBB); 3443 ++MBBI; 3444 3445 MF->insert(MBBI, LoopBB); 3446 MF->insert(MBBI, RemainderBB); 3447 3448 LoopBB->addSuccessor(LoopBB); 3449 LoopBB->addSuccessor(RemainderBB); 3450 3451 // Move the rest of the block into a new block. 3452 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3453 3454 if (InstInLoop) { 3455 auto Next = std::next(I); 3456 3457 // Move instruction to loop body. 3458 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3459 3460 // Move the rest of the block. 3461 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3462 } else { 3463 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3464 } 3465 3466 MBB.addSuccessor(LoopBB); 3467 3468 return std::make_pair(LoopBB, RemainderBB); 3469 } 3470 3471 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3472 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3473 MachineBasicBlock *MBB = MI.getParent(); 3474 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3475 auto I = MI.getIterator(); 3476 auto E = std::next(I); 3477 3478 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3479 .addImm(0); 3480 3481 MIBundleBuilder Bundler(*MBB, I, E); 3482 finalizeBundle(*MBB, Bundler.begin()); 3483 } 3484 3485 MachineBasicBlock * 3486 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3487 MachineBasicBlock *BB) const { 3488 const DebugLoc &DL = MI.getDebugLoc(); 3489 3490 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3491 3492 MachineBasicBlock *LoopBB; 3493 MachineBasicBlock *RemainderBB; 3494 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3495 3496 // Apparently kill flags are only valid if the def is in the same block? 3497 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3498 Src->setIsKill(false); 3499 3500 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3501 3502 MachineBasicBlock::iterator I = LoopBB->end(); 3503 3504 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3505 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3506 3507 // Clear TRAP_STS.MEM_VIOL 3508 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3509 .addImm(0) 3510 .addImm(EncodedReg); 3511 3512 bundleInstWithWaitcnt(MI); 3513 3514 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3515 3516 // Load and check TRAP_STS.MEM_VIOL 3517 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3518 .addImm(EncodedReg); 3519 3520 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3521 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3522 .addReg(Reg, RegState::Kill) 3523 .addImm(0); 3524 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3525 .addMBB(LoopBB); 3526 3527 return RemainderBB; 3528 } 3529 3530 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3531 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3532 // will only do one iteration. In the worst case, this will loop 64 times. 3533 // 3534 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3535 static MachineBasicBlock::iterator 3536 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3537 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3538 const DebugLoc &DL, const MachineOperand &Idx, 3539 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3540 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3541 Register &SGPRIdxReg) { 3542 3543 MachineFunction *MF = OrigBB.getParent(); 3544 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3545 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3546 MachineBasicBlock::iterator I = LoopBB.begin(); 3547 3548 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3549 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3550 Register NewExec = MRI.createVirtualRegister(BoolRC); 3551 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3552 Register CondReg = MRI.createVirtualRegister(BoolRC); 3553 3554 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3555 .addReg(InitReg) 3556 .addMBB(&OrigBB) 3557 .addReg(ResultReg) 3558 .addMBB(&LoopBB); 3559 3560 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3561 .addReg(InitSaveExecReg) 3562 .addMBB(&OrigBB) 3563 .addReg(NewExec) 3564 .addMBB(&LoopBB); 3565 3566 // Read the next variant <- also loop target. 3567 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3568 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3569 3570 // Compare the just read M0 value to all possible Idx values. 3571 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3572 .addReg(CurrentIdxReg) 3573 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3574 3575 // Update EXEC, save the original EXEC value to VCC. 3576 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3577 : AMDGPU::S_AND_SAVEEXEC_B64), 3578 NewExec) 3579 .addReg(CondReg, RegState::Kill); 3580 3581 MRI.setSimpleHint(NewExec, CondReg); 3582 3583 if (UseGPRIdxMode) { 3584 if (Offset == 0) { 3585 SGPRIdxReg = CurrentIdxReg; 3586 } else { 3587 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3588 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3589 .addReg(CurrentIdxReg, RegState::Kill) 3590 .addImm(Offset); 3591 } 3592 } else { 3593 // Move index from VCC into M0 3594 if (Offset == 0) { 3595 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3596 .addReg(CurrentIdxReg, RegState::Kill); 3597 } else { 3598 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3599 .addReg(CurrentIdxReg, RegState::Kill) 3600 .addImm(Offset); 3601 } 3602 } 3603 3604 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3605 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3606 MachineInstr *InsertPt = 3607 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3608 : AMDGPU::S_XOR_B64_term), Exec) 3609 .addReg(Exec) 3610 .addReg(NewExec); 3611 3612 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3613 // s_cbranch_scc0? 3614 3615 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3616 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3617 .addMBB(&LoopBB); 3618 3619 return InsertPt->getIterator(); 3620 } 3621 3622 // This has slightly sub-optimal regalloc when the source vector is killed by 3623 // the read. The register allocator does not understand that the kill is 3624 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3625 // subregister from it, using 1 more VGPR than necessary. This was saved when 3626 // this was expanded after register allocation. 3627 static MachineBasicBlock::iterator 3628 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3629 unsigned InitResultReg, unsigned PhiReg, int Offset, 3630 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3631 MachineFunction *MF = MBB.getParent(); 3632 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3633 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3634 MachineRegisterInfo &MRI = MF->getRegInfo(); 3635 const DebugLoc &DL = MI.getDebugLoc(); 3636 MachineBasicBlock::iterator I(&MI); 3637 3638 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3639 Register DstReg = MI.getOperand(0).getReg(); 3640 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3641 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3642 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3643 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3644 3645 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3646 3647 // Save the EXEC mask 3648 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3649 .addReg(Exec); 3650 3651 MachineBasicBlock *LoopBB; 3652 MachineBasicBlock *RemainderBB; 3653 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3654 3655 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3656 3657 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3658 InitResultReg, DstReg, PhiReg, TmpExec, 3659 Offset, UseGPRIdxMode, SGPRIdxReg); 3660 3661 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3662 MachineFunction::iterator MBBI(LoopBB); 3663 ++MBBI; 3664 MF->insert(MBBI, LandingPad); 3665 LoopBB->removeSuccessor(RemainderBB); 3666 LandingPad->addSuccessor(RemainderBB); 3667 LoopBB->addSuccessor(LandingPad); 3668 MachineBasicBlock::iterator First = LandingPad->begin(); 3669 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3670 .addReg(SaveExec); 3671 3672 return InsPt; 3673 } 3674 3675 // Returns subreg index, offset 3676 static std::pair<unsigned, int> 3677 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3678 const TargetRegisterClass *SuperRC, 3679 unsigned VecReg, 3680 int Offset) { 3681 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3682 3683 // Skip out of bounds offsets, or else we would end up using an undefined 3684 // register. 3685 if (Offset >= NumElts || Offset < 0) 3686 return std::make_pair(AMDGPU::sub0, Offset); 3687 3688 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3689 } 3690 3691 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3692 MachineRegisterInfo &MRI, MachineInstr &MI, 3693 int Offset) { 3694 MachineBasicBlock *MBB = MI.getParent(); 3695 const DebugLoc &DL = MI.getDebugLoc(); 3696 MachineBasicBlock::iterator I(&MI); 3697 3698 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3699 3700 assert(Idx->getReg() != AMDGPU::NoRegister); 3701 3702 if (Offset == 0) { 3703 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3704 } else { 3705 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3706 .add(*Idx) 3707 .addImm(Offset); 3708 } 3709 } 3710 3711 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3712 MachineRegisterInfo &MRI, MachineInstr &MI, 3713 int Offset) { 3714 MachineBasicBlock *MBB = MI.getParent(); 3715 const DebugLoc &DL = MI.getDebugLoc(); 3716 MachineBasicBlock::iterator I(&MI); 3717 3718 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3719 3720 if (Offset == 0) 3721 return Idx->getReg(); 3722 3723 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3724 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3725 .add(*Idx) 3726 .addImm(Offset); 3727 return Tmp; 3728 } 3729 3730 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3731 MachineBasicBlock &MBB, 3732 const GCNSubtarget &ST) { 3733 const SIInstrInfo *TII = ST.getInstrInfo(); 3734 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3735 MachineFunction *MF = MBB.getParent(); 3736 MachineRegisterInfo &MRI = MF->getRegInfo(); 3737 3738 Register Dst = MI.getOperand(0).getReg(); 3739 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3740 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3741 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3742 3743 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3744 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3745 3746 unsigned SubReg; 3747 std::tie(SubReg, Offset) 3748 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3749 3750 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3751 3752 // Check for a SGPR index. 3753 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3754 MachineBasicBlock::iterator I(&MI); 3755 const DebugLoc &DL = MI.getDebugLoc(); 3756 3757 if (UseGPRIdxMode) { 3758 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3759 // to avoid interfering with other uses, so probably requires a new 3760 // optimization pass. 3761 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3762 3763 const MCInstrDesc &GPRIDXDesc = 3764 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3765 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3766 .addReg(SrcReg) 3767 .addReg(Idx) 3768 .addImm(SubReg); 3769 } else { 3770 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3771 3772 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3773 .addReg(SrcReg, 0, SubReg) 3774 .addReg(SrcReg, RegState::Implicit); 3775 } 3776 3777 MI.eraseFromParent(); 3778 3779 return &MBB; 3780 } 3781 3782 // Control flow needs to be inserted if indexing with a VGPR. 3783 const DebugLoc &DL = MI.getDebugLoc(); 3784 MachineBasicBlock::iterator I(&MI); 3785 3786 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3787 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3788 3789 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3790 3791 Register SGPRIdxReg; 3792 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3793 UseGPRIdxMode, SGPRIdxReg); 3794 3795 MachineBasicBlock *LoopBB = InsPt->getParent(); 3796 3797 if (UseGPRIdxMode) { 3798 const MCInstrDesc &GPRIDXDesc = 3799 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3800 3801 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3802 .addReg(SrcReg) 3803 .addReg(SGPRIdxReg) 3804 .addImm(SubReg); 3805 } else { 3806 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3807 .addReg(SrcReg, 0, SubReg) 3808 .addReg(SrcReg, RegState::Implicit); 3809 } 3810 3811 MI.eraseFromParent(); 3812 3813 return LoopBB; 3814 } 3815 3816 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3817 MachineBasicBlock &MBB, 3818 const GCNSubtarget &ST) { 3819 const SIInstrInfo *TII = ST.getInstrInfo(); 3820 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3821 MachineFunction *MF = MBB.getParent(); 3822 MachineRegisterInfo &MRI = MF->getRegInfo(); 3823 3824 Register Dst = MI.getOperand(0).getReg(); 3825 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3826 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3827 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3828 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3829 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3830 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3831 3832 // This can be an immediate, but will be folded later. 3833 assert(Val->getReg()); 3834 3835 unsigned SubReg; 3836 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3837 SrcVec->getReg(), 3838 Offset); 3839 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3840 3841 if (Idx->getReg() == AMDGPU::NoRegister) { 3842 MachineBasicBlock::iterator I(&MI); 3843 const DebugLoc &DL = MI.getDebugLoc(); 3844 3845 assert(Offset == 0); 3846 3847 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3848 .add(*SrcVec) 3849 .add(*Val) 3850 .addImm(SubReg); 3851 3852 MI.eraseFromParent(); 3853 return &MBB; 3854 } 3855 3856 // Check for a SGPR index. 3857 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3858 MachineBasicBlock::iterator I(&MI); 3859 const DebugLoc &DL = MI.getDebugLoc(); 3860 3861 if (UseGPRIdxMode) { 3862 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3863 3864 const MCInstrDesc &GPRIDXDesc = 3865 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3866 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3867 .addReg(SrcVec->getReg()) 3868 .add(*Val) 3869 .addReg(Idx) 3870 .addImm(SubReg); 3871 } else { 3872 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3873 3874 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3875 TRI.getRegSizeInBits(*VecRC), 32, false); 3876 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3877 .addReg(SrcVec->getReg()) 3878 .add(*Val) 3879 .addImm(SubReg); 3880 } 3881 MI.eraseFromParent(); 3882 return &MBB; 3883 } 3884 3885 // Control flow needs to be inserted if indexing with a VGPR. 3886 if (Val->isReg()) 3887 MRI.clearKillFlags(Val->getReg()); 3888 3889 const DebugLoc &DL = MI.getDebugLoc(); 3890 3891 Register PhiReg = MRI.createVirtualRegister(VecRC); 3892 3893 Register SGPRIdxReg; 3894 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3895 UseGPRIdxMode, SGPRIdxReg); 3896 MachineBasicBlock *LoopBB = InsPt->getParent(); 3897 3898 if (UseGPRIdxMode) { 3899 const MCInstrDesc &GPRIDXDesc = 3900 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3901 3902 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3903 .addReg(PhiReg) 3904 .add(*Val) 3905 .addReg(SGPRIdxReg) 3906 .addImm(AMDGPU::sub0); 3907 } else { 3908 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3909 TRI.getRegSizeInBits(*VecRC), 32, false); 3910 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3911 .addReg(PhiReg) 3912 .add(*Val) 3913 .addImm(AMDGPU::sub0); 3914 } 3915 3916 MI.eraseFromParent(); 3917 return LoopBB; 3918 } 3919 3920 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3921 MachineInstr &MI, MachineBasicBlock *BB) const { 3922 3923 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3924 MachineFunction *MF = BB->getParent(); 3925 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3926 3927 switch (MI.getOpcode()) { 3928 case AMDGPU::S_UADDO_PSEUDO: 3929 case AMDGPU::S_USUBO_PSEUDO: { 3930 const DebugLoc &DL = MI.getDebugLoc(); 3931 MachineOperand &Dest0 = MI.getOperand(0); 3932 MachineOperand &Dest1 = MI.getOperand(1); 3933 MachineOperand &Src0 = MI.getOperand(2); 3934 MachineOperand &Src1 = MI.getOperand(3); 3935 3936 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3937 ? AMDGPU::S_ADD_I32 3938 : AMDGPU::S_SUB_I32; 3939 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3940 3941 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3942 .addImm(1) 3943 .addImm(0); 3944 3945 MI.eraseFromParent(); 3946 return BB; 3947 } 3948 case AMDGPU::S_ADD_U64_PSEUDO: 3949 case AMDGPU::S_SUB_U64_PSEUDO: { 3950 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3951 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3952 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3953 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3954 const DebugLoc &DL = MI.getDebugLoc(); 3955 3956 MachineOperand &Dest = MI.getOperand(0); 3957 MachineOperand &Src0 = MI.getOperand(1); 3958 MachineOperand &Src1 = MI.getOperand(2); 3959 3960 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3961 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3962 3963 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3964 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3965 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3966 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3967 3968 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3969 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3970 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3971 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3972 3973 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3974 3975 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3976 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3977 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3978 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3979 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3980 .addReg(DestSub0) 3981 .addImm(AMDGPU::sub0) 3982 .addReg(DestSub1) 3983 .addImm(AMDGPU::sub1); 3984 MI.eraseFromParent(); 3985 return BB; 3986 } 3987 case AMDGPU::V_ADD_U64_PSEUDO: 3988 case AMDGPU::V_SUB_U64_PSEUDO: { 3989 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3990 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3991 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3992 const DebugLoc &DL = MI.getDebugLoc(); 3993 3994 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3995 3996 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3997 3998 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3999 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4000 4001 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4002 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4003 4004 MachineOperand &Dest = MI.getOperand(0); 4005 MachineOperand &Src0 = MI.getOperand(1); 4006 MachineOperand &Src1 = MI.getOperand(2); 4007 4008 const TargetRegisterClass *Src0RC = Src0.isReg() 4009 ? MRI.getRegClass(Src0.getReg()) 4010 : &AMDGPU::VReg_64RegClass; 4011 const TargetRegisterClass *Src1RC = Src1.isReg() 4012 ? MRI.getRegClass(Src1.getReg()) 4013 : &AMDGPU::VReg_64RegClass; 4014 4015 const TargetRegisterClass *Src0SubRC = 4016 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4017 const TargetRegisterClass *Src1SubRC = 4018 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4019 4020 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4021 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4022 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4023 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4024 4025 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4026 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4027 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4028 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4029 4030 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4031 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4032 .addReg(CarryReg, RegState::Define) 4033 .add(SrcReg0Sub0) 4034 .add(SrcReg1Sub0) 4035 .addImm(0); // clamp bit 4036 4037 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4038 MachineInstr *HiHalf = 4039 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4040 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4041 .add(SrcReg0Sub1) 4042 .add(SrcReg1Sub1) 4043 .addReg(CarryReg, RegState::Kill) 4044 .addImm(0); // clamp bit 4045 4046 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4047 .addReg(DestSub0) 4048 .addImm(AMDGPU::sub0) 4049 .addReg(DestSub1) 4050 .addImm(AMDGPU::sub1); 4051 TII->legalizeOperands(*LoHalf); 4052 TII->legalizeOperands(*HiHalf); 4053 MI.eraseFromParent(); 4054 return BB; 4055 } 4056 case AMDGPU::S_ADD_CO_PSEUDO: 4057 case AMDGPU::S_SUB_CO_PSEUDO: { 4058 // This pseudo has a chance to be selected 4059 // only from uniform add/subcarry node. All the VGPR operands 4060 // therefore assumed to be splat vectors. 4061 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4062 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4063 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4064 MachineBasicBlock::iterator MII = MI; 4065 const DebugLoc &DL = MI.getDebugLoc(); 4066 MachineOperand &Dest = MI.getOperand(0); 4067 MachineOperand &CarryDest = MI.getOperand(1); 4068 MachineOperand &Src0 = MI.getOperand(2); 4069 MachineOperand &Src1 = MI.getOperand(3); 4070 MachineOperand &Src2 = MI.getOperand(4); 4071 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4072 ? AMDGPU::S_ADDC_U32 4073 : AMDGPU::S_SUBB_U32; 4074 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4075 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4076 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4077 .addReg(Src0.getReg()); 4078 Src0.setReg(RegOp0); 4079 } 4080 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4081 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4082 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4083 .addReg(Src1.getReg()); 4084 Src1.setReg(RegOp1); 4085 } 4086 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4087 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4088 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4089 .addReg(Src2.getReg()); 4090 Src2.setReg(RegOp2); 4091 } 4092 4093 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4094 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4095 if (ST.hasScalarCompareEq64()) { 4096 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4097 .addReg(Src2.getReg()) 4098 .addImm(0); 4099 } else { 4100 const TargetRegisterClass *SubRC = 4101 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4102 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4103 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4104 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4105 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4106 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4107 4108 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4109 .add(Src2Sub0) 4110 .add(Src2Sub1); 4111 4112 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4113 .addReg(Src2_32, RegState::Kill) 4114 .addImm(0); 4115 } 4116 } else { 4117 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4118 .addReg(Src2.getReg()) 4119 .addImm(0); 4120 } 4121 4122 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4123 4124 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4125 .addReg(AMDGPU::SCC); 4126 MI.eraseFromParent(); 4127 return BB; 4128 } 4129 case AMDGPU::SI_INIT_M0: { 4130 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4131 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4132 .add(MI.getOperand(0)); 4133 MI.eraseFromParent(); 4134 return BB; 4135 } 4136 case AMDGPU::GET_GROUPSTATICSIZE: { 4137 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4138 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4139 DebugLoc DL = MI.getDebugLoc(); 4140 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4141 .add(MI.getOperand(0)) 4142 .addImm(MFI->getLDSSize()); 4143 MI.eraseFromParent(); 4144 return BB; 4145 } 4146 case AMDGPU::SI_INDIRECT_SRC_V1: 4147 case AMDGPU::SI_INDIRECT_SRC_V2: 4148 case AMDGPU::SI_INDIRECT_SRC_V4: 4149 case AMDGPU::SI_INDIRECT_SRC_V8: 4150 case AMDGPU::SI_INDIRECT_SRC_V16: 4151 case AMDGPU::SI_INDIRECT_SRC_V32: 4152 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4153 case AMDGPU::SI_INDIRECT_DST_V1: 4154 case AMDGPU::SI_INDIRECT_DST_V2: 4155 case AMDGPU::SI_INDIRECT_DST_V4: 4156 case AMDGPU::SI_INDIRECT_DST_V8: 4157 case AMDGPU::SI_INDIRECT_DST_V16: 4158 case AMDGPU::SI_INDIRECT_DST_V32: 4159 return emitIndirectDst(MI, *BB, *getSubtarget()); 4160 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4161 case AMDGPU::SI_KILL_I1_PSEUDO: 4162 return splitKillBlock(MI, BB); 4163 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4164 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4165 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4166 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4167 4168 Register Dst = MI.getOperand(0).getReg(); 4169 Register Src0 = MI.getOperand(1).getReg(); 4170 Register Src1 = MI.getOperand(2).getReg(); 4171 const DebugLoc &DL = MI.getDebugLoc(); 4172 Register SrcCond = MI.getOperand(3).getReg(); 4173 4174 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4175 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4176 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4177 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4178 4179 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4180 .addReg(SrcCond); 4181 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4182 .addImm(0) 4183 .addReg(Src0, 0, AMDGPU::sub0) 4184 .addImm(0) 4185 .addReg(Src1, 0, AMDGPU::sub0) 4186 .addReg(SrcCondCopy); 4187 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4188 .addImm(0) 4189 .addReg(Src0, 0, AMDGPU::sub1) 4190 .addImm(0) 4191 .addReg(Src1, 0, AMDGPU::sub1) 4192 .addReg(SrcCondCopy); 4193 4194 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4195 .addReg(DstLo) 4196 .addImm(AMDGPU::sub0) 4197 .addReg(DstHi) 4198 .addImm(AMDGPU::sub1); 4199 MI.eraseFromParent(); 4200 return BB; 4201 } 4202 case AMDGPU::SI_BR_UNDEF: { 4203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4204 const DebugLoc &DL = MI.getDebugLoc(); 4205 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4206 .add(MI.getOperand(0)); 4207 Br->getOperand(1).setIsUndef(true); // read undef SCC 4208 MI.eraseFromParent(); 4209 return BB; 4210 } 4211 case AMDGPU::ADJCALLSTACKUP: 4212 case AMDGPU::ADJCALLSTACKDOWN: { 4213 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4214 MachineInstrBuilder MIB(*MF, &MI); 4215 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4216 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4217 return BB; 4218 } 4219 case AMDGPU::SI_CALL_ISEL: { 4220 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4221 const DebugLoc &DL = MI.getDebugLoc(); 4222 4223 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4224 4225 MachineInstrBuilder MIB; 4226 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4227 4228 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4229 MIB.add(MI.getOperand(I)); 4230 4231 MIB.cloneMemRefs(MI); 4232 MI.eraseFromParent(); 4233 return BB; 4234 } 4235 case AMDGPU::V_ADD_CO_U32_e32: 4236 case AMDGPU::V_SUB_CO_U32_e32: 4237 case AMDGPU::V_SUBREV_CO_U32_e32: { 4238 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4239 const DebugLoc &DL = MI.getDebugLoc(); 4240 unsigned Opc = MI.getOpcode(); 4241 4242 bool NeedClampOperand = false; 4243 if (TII->pseudoToMCOpcode(Opc) == -1) { 4244 Opc = AMDGPU::getVOPe64(Opc); 4245 NeedClampOperand = true; 4246 } 4247 4248 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4249 if (TII->isVOP3(*I)) { 4250 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4251 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4252 I.addReg(TRI->getVCC(), RegState::Define); 4253 } 4254 I.add(MI.getOperand(1)) 4255 .add(MI.getOperand(2)); 4256 if (NeedClampOperand) 4257 I.addImm(0); // clamp bit for e64 encoding 4258 4259 TII->legalizeOperands(*I); 4260 4261 MI.eraseFromParent(); 4262 return BB; 4263 } 4264 case AMDGPU::DS_GWS_INIT: 4265 case AMDGPU::DS_GWS_SEMA_BR: 4266 case AMDGPU::DS_GWS_BARRIER: 4267 if (Subtarget->needsAlignedVGPRs()) { 4268 // Add implicit aligned super-reg to force alignment on the data operand. 4269 const DebugLoc &DL = MI.getDebugLoc(); 4270 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4271 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4272 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4273 Register DataReg = Op->getReg(); 4274 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4275 Register Undef = MRI.createVirtualRegister( 4276 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4277 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4278 Register NewVR = 4279 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4280 : &AMDGPU::VReg_64_Align2RegClass); 4281 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4282 .addReg(DataReg, 0, Op->getSubReg()) 4283 .addImm(AMDGPU::sub0) 4284 .addReg(Undef) 4285 .addImm(AMDGPU::sub1); 4286 Op->setReg(NewVR); 4287 Op->setSubReg(AMDGPU::sub0); 4288 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4289 } 4290 LLVM_FALLTHROUGH; 4291 case AMDGPU::DS_GWS_SEMA_V: 4292 case AMDGPU::DS_GWS_SEMA_P: 4293 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4294 // A s_waitcnt 0 is required to be the instruction immediately following. 4295 if (getSubtarget()->hasGWSAutoReplay()) { 4296 bundleInstWithWaitcnt(MI); 4297 return BB; 4298 } 4299 4300 return emitGWSMemViolTestLoop(MI, BB); 4301 case AMDGPU::S_SETREG_B32: { 4302 // Try to optimize cases that only set the denormal mode or rounding mode. 4303 // 4304 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4305 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4306 // instead. 4307 // 4308 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4309 // allow you to have a no side effect instruction in the output of a 4310 // sideeffecting pattern. 4311 unsigned ID, Offset, Width; 4312 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4313 if (ID != AMDGPU::Hwreg::ID_MODE) 4314 return BB; 4315 4316 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4317 const unsigned SetMask = WidthMask << Offset; 4318 4319 if (getSubtarget()->hasDenormModeInst()) { 4320 unsigned SetDenormOp = 0; 4321 unsigned SetRoundOp = 0; 4322 4323 // The dedicated instructions can only set the whole denorm or round mode 4324 // at once, not a subset of bits in either. 4325 if (SetMask == 4326 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4327 // If this fully sets both the round and denorm mode, emit the two 4328 // dedicated instructions for these. 4329 SetRoundOp = AMDGPU::S_ROUND_MODE; 4330 SetDenormOp = AMDGPU::S_DENORM_MODE; 4331 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4332 SetRoundOp = AMDGPU::S_ROUND_MODE; 4333 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4334 SetDenormOp = AMDGPU::S_DENORM_MODE; 4335 } 4336 4337 if (SetRoundOp || SetDenormOp) { 4338 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4339 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4340 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4341 unsigned ImmVal = Def->getOperand(1).getImm(); 4342 if (SetRoundOp) { 4343 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4344 .addImm(ImmVal & 0xf); 4345 4346 // If we also have the denorm mode, get just the denorm mode bits. 4347 ImmVal >>= 4; 4348 } 4349 4350 if (SetDenormOp) { 4351 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4352 .addImm(ImmVal & 0xf); 4353 } 4354 4355 MI.eraseFromParent(); 4356 return BB; 4357 } 4358 } 4359 } 4360 4361 // If only FP bits are touched, used the no side effects pseudo. 4362 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4363 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4364 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4365 4366 return BB; 4367 } 4368 default: 4369 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4370 } 4371 } 4372 4373 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4374 return isTypeLegal(VT.getScalarType()); 4375 } 4376 4377 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4378 // This currently forces unfolding various combinations of fsub into fma with 4379 // free fneg'd operands. As long as we have fast FMA (controlled by 4380 // isFMAFasterThanFMulAndFAdd), we should perform these. 4381 4382 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4383 // most of these combines appear to be cycle neutral but save on instruction 4384 // count / code size. 4385 return true; 4386 } 4387 4388 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4389 EVT VT) const { 4390 if (!VT.isVector()) { 4391 return MVT::i1; 4392 } 4393 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4394 } 4395 4396 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4397 // TODO: Should i16 be used always if legal? For now it would force VALU 4398 // shifts. 4399 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4400 } 4401 4402 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4403 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4404 ? Ty.changeElementSize(16) 4405 : Ty.changeElementSize(32); 4406 } 4407 4408 // Answering this is somewhat tricky and depends on the specific device which 4409 // have different rates for fma or all f64 operations. 4410 // 4411 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4412 // regardless of which device (although the number of cycles differs between 4413 // devices), so it is always profitable for f64. 4414 // 4415 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4416 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4417 // which we can always do even without fused FP ops since it returns the same 4418 // result as the separate operations and since it is always full 4419 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4420 // however does not support denormals, so we do report fma as faster if we have 4421 // a fast fma device and require denormals. 4422 // 4423 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4424 EVT VT) const { 4425 VT = VT.getScalarType(); 4426 4427 switch (VT.getSimpleVT().SimpleTy) { 4428 case MVT::f32: { 4429 // If mad is not available this depends only on if f32 fma is full rate. 4430 if (!Subtarget->hasMadMacF32Insts()) 4431 return Subtarget->hasFastFMAF32(); 4432 4433 // Otherwise f32 mad is always full rate and returns the same result as 4434 // the separate operations so should be preferred over fma. 4435 // However does not support denomals. 4436 if (hasFP32Denormals(MF)) 4437 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4438 4439 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4440 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4441 } 4442 case MVT::f64: 4443 return true; 4444 case MVT::f16: 4445 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4446 default: 4447 break; 4448 } 4449 4450 return false; 4451 } 4452 4453 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4454 const SDNode *N) const { 4455 // TODO: Check future ftz flag 4456 // v_mad_f32/v_mac_f32 do not support denormals. 4457 EVT VT = N->getValueType(0); 4458 if (VT == MVT::f32) 4459 return Subtarget->hasMadMacF32Insts() && 4460 !hasFP32Denormals(DAG.getMachineFunction()); 4461 if (VT == MVT::f16) { 4462 return Subtarget->hasMadF16() && 4463 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4464 } 4465 4466 return false; 4467 } 4468 4469 //===----------------------------------------------------------------------===// 4470 // Custom DAG Lowering Operations 4471 //===----------------------------------------------------------------------===// 4472 4473 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4474 // wider vector type is legal. 4475 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4476 SelectionDAG &DAG) const { 4477 unsigned Opc = Op.getOpcode(); 4478 EVT VT = Op.getValueType(); 4479 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4480 4481 SDValue Lo, Hi; 4482 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4483 4484 SDLoc SL(Op); 4485 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4486 Op->getFlags()); 4487 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4488 Op->getFlags()); 4489 4490 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4491 } 4492 4493 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4494 // wider vector type is legal. 4495 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4496 SelectionDAG &DAG) const { 4497 unsigned Opc = Op.getOpcode(); 4498 EVT VT = Op.getValueType(); 4499 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4500 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4501 4502 SDValue Lo0, Hi0; 4503 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4504 SDValue Lo1, Hi1; 4505 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4506 4507 SDLoc SL(Op); 4508 4509 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4510 Op->getFlags()); 4511 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4512 Op->getFlags()); 4513 4514 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4515 } 4516 4517 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4518 SelectionDAG &DAG) const { 4519 unsigned Opc = Op.getOpcode(); 4520 EVT VT = Op.getValueType(); 4521 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4522 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4523 4524 SDValue Lo0, Hi0; 4525 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4526 SDValue Lo1, Hi1; 4527 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4528 SDValue Lo2, Hi2; 4529 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4530 4531 SDLoc SL(Op); 4532 4533 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4534 Op->getFlags()); 4535 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4536 Op->getFlags()); 4537 4538 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4539 } 4540 4541 4542 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4543 switch (Op.getOpcode()) { 4544 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4545 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4546 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4547 case ISD::LOAD: { 4548 SDValue Result = LowerLOAD(Op, DAG); 4549 assert((!Result.getNode() || 4550 Result.getNode()->getNumValues() == 2) && 4551 "Load should return a value and a chain"); 4552 return Result; 4553 } 4554 4555 case ISD::FSIN: 4556 case ISD::FCOS: 4557 return LowerTrig(Op, DAG); 4558 case ISD::SELECT: return LowerSELECT(Op, DAG); 4559 case ISD::FDIV: return LowerFDIV(Op, DAG); 4560 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4561 case ISD::STORE: return LowerSTORE(Op, DAG); 4562 case ISD::GlobalAddress: { 4563 MachineFunction &MF = DAG.getMachineFunction(); 4564 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4565 return LowerGlobalAddress(MFI, Op, DAG); 4566 } 4567 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4568 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4569 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4570 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4571 case ISD::INSERT_SUBVECTOR: 4572 return lowerINSERT_SUBVECTOR(Op, DAG); 4573 case ISD::INSERT_VECTOR_ELT: 4574 return lowerINSERT_VECTOR_ELT(Op, DAG); 4575 case ISD::EXTRACT_VECTOR_ELT: 4576 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4577 case ISD::VECTOR_SHUFFLE: 4578 return lowerVECTOR_SHUFFLE(Op, DAG); 4579 case ISD::BUILD_VECTOR: 4580 return lowerBUILD_VECTOR(Op, DAG); 4581 case ISD::FP_ROUND: 4582 return lowerFP_ROUND(Op, DAG); 4583 case ISD::TRAP: 4584 return lowerTRAP(Op, DAG); 4585 case ISD::DEBUGTRAP: 4586 return lowerDEBUGTRAP(Op, DAG); 4587 case ISD::FABS: 4588 case ISD::FNEG: 4589 case ISD::FCANONICALIZE: 4590 case ISD::BSWAP: 4591 return splitUnaryVectorOp(Op, DAG); 4592 case ISD::FMINNUM: 4593 case ISD::FMAXNUM: 4594 return lowerFMINNUM_FMAXNUM(Op, DAG); 4595 case ISD::FMA: 4596 return splitTernaryVectorOp(Op, DAG); 4597 case ISD::FP_TO_SINT: 4598 case ISD::FP_TO_UINT: 4599 return LowerFP_TO_INT(Op, DAG); 4600 case ISD::SHL: 4601 case ISD::SRA: 4602 case ISD::SRL: 4603 case ISD::ADD: 4604 case ISD::SUB: 4605 case ISD::MUL: 4606 case ISD::SMIN: 4607 case ISD::SMAX: 4608 case ISD::UMIN: 4609 case ISD::UMAX: 4610 case ISD::FADD: 4611 case ISD::FMUL: 4612 case ISD::FMINNUM_IEEE: 4613 case ISD::FMAXNUM_IEEE: 4614 case ISD::UADDSAT: 4615 case ISD::USUBSAT: 4616 case ISD::SADDSAT: 4617 case ISD::SSUBSAT: 4618 return splitBinaryVectorOp(Op, DAG); 4619 case ISD::SMULO: 4620 case ISD::UMULO: 4621 return lowerXMULO(Op, DAG); 4622 case ISD::DYNAMIC_STACKALLOC: 4623 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4624 } 4625 return SDValue(); 4626 } 4627 4628 // Used for D16: Casts the result of an instruction into the right vector, 4629 // packs values if loads return unpacked values. 4630 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4631 const SDLoc &DL, 4632 SelectionDAG &DAG, bool Unpacked) { 4633 if (!LoadVT.isVector()) 4634 return Result; 4635 4636 // Cast back to the original packed type or to a larger type that is a 4637 // multiple of 32 bit for D16. Widening the return type is a required for 4638 // legalization. 4639 EVT FittingLoadVT = LoadVT; 4640 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4641 FittingLoadVT = 4642 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4643 LoadVT.getVectorNumElements() + 1); 4644 } 4645 4646 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4647 // Truncate to v2i16/v4i16. 4648 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4649 4650 // Workaround legalizer not scalarizing truncate after vector op 4651 // legalization but not creating intermediate vector trunc. 4652 SmallVector<SDValue, 4> Elts; 4653 DAG.ExtractVectorElements(Result, Elts); 4654 for (SDValue &Elt : Elts) 4655 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4656 4657 // Pad illegal v1i16/v3fi6 to v4i16 4658 if ((LoadVT.getVectorNumElements() % 2) == 1) 4659 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4660 4661 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4662 4663 // Bitcast to original type (v2f16/v4f16). 4664 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4665 } 4666 4667 // Cast back to the original packed type. 4668 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4669 } 4670 4671 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4672 MemSDNode *M, 4673 SelectionDAG &DAG, 4674 ArrayRef<SDValue> Ops, 4675 bool IsIntrinsic) const { 4676 SDLoc DL(M); 4677 4678 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4679 EVT LoadVT = M->getValueType(0); 4680 4681 EVT EquivLoadVT = LoadVT; 4682 if (LoadVT.isVector()) { 4683 if (Unpacked) { 4684 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4685 LoadVT.getVectorNumElements()); 4686 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4687 // Widen v3f16 to legal type 4688 EquivLoadVT = 4689 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4690 LoadVT.getVectorNumElements() + 1); 4691 } 4692 } 4693 4694 // Change from v4f16/v2f16 to EquivLoadVT. 4695 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4696 4697 SDValue Load 4698 = DAG.getMemIntrinsicNode( 4699 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4700 VTList, Ops, M->getMemoryVT(), 4701 M->getMemOperand()); 4702 4703 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4704 4705 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4706 } 4707 4708 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4709 SelectionDAG &DAG, 4710 ArrayRef<SDValue> Ops) const { 4711 SDLoc DL(M); 4712 EVT LoadVT = M->getValueType(0); 4713 EVT EltType = LoadVT.getScalarType(); 4714 EVT IntVT = LoadVT.changeTypeToInteger(); 4715 4716 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4717 4718 unsigned Opc = 4719 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4720 4721 if (IsD16) { 4722 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4723 } 4724 4725 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4726 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4727 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4728 4729 if (isTypeLegal(LoadVT)) { 4730 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4731 M->getMemOperand(), DAG); 4732 } 4733 4734 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4735 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4736 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4737 M->getMemOperand(), DAG); 4738 return DAG.getMergeValues( 4739 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4740 DL); 4741 } 4742 4743 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4744 SDNode *N, SelectionDAG &DAG) { 4745 EVT VT = N->getValueType(0); 4746 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4747 unsigned CondCode = CD->getZExtValue(); 4748 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4749 return DAG.getUNDEF(VT); 4750 4751 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4752 4753 SDValue LHS = N->getOperand(1); 4754 SDValue RHS = N->getOperand(2); 4755 4756 SDLoc DL(N); 4757 4758 EVT CmpVT = LHS.getValueType(); 4759 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4760 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4761 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4762 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4763 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4764 } 4765 4766 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4767 4768 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4769 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4770 4771 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4772 DAG.getCondCode(CCOpcode)); 4773 if (VT.bitsEq(CCVT)) 4774 return SetCC; 4775 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4776 } 4777 4778 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4779 SDNode *N, SelectionDAG &DAG) { 4780 EVT VT = N->getValueType(0); 4781 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4782 4783 unsigned CondCode = CD->getZExtValue(); 4784 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4785 return DAG.getUNDEF(VT); 4786 4787 SDValue Src0 = N->getOperand(1); 4788 SDValue Src1 = N->getOperand(2); 4789 EVT CmpVT = Src0.getValueType(); 4790 SDLoc SL(N); 4791 4792 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4793 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4794 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4795 } 4796 4797 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4798 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4799 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4800 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4801 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4802 Src1, DAG.getCondCode(CCOpcode)); 4803 if (VT.bitsEq(CCVT)) 4804 return SetCC; 4805 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4806 } 4807 4808 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4809 SelectionDAG &DAG) { 4810 EVT VT = N->getValueType(0); 4811 SDValue Src = N->getOperand(1); 4812 SDLoc SL(N); 4813 4814 if (Src.getOpcode() == ISD::SETCC) { 4815 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4816 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4817 Src.getOperand(1), Src.getOperand(2)); 4818 } 4819 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4820 // (ballot 0) -> 0 4821 if (Arg->isNullValue()) 4822 return DAG.getConstant(0, SL, VT); 4823 4824 // (ballot 1) -> EXEC/EXEC_LO 4825 if (Arg->isOne()) { 4826 Register Exec; 4827 if (VT.getScalarSizeInBits() == 32) 4828 Exec = AMDGPU::EXEC_LO; 4829 else if (VT.getScalarSizeInBits() == 64) 4830 Exec = AMDGPU::EXEC; 4831 else 4832 return SDValue(); 4833 4834 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4835 } 4836 } 4837 4838 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4839 // ISD::SETNE) 4840 return DAG.getNode( 4841 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4842 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4843 } 4844 4845 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4846 SmallVectorImpl<SDValue> &Results, 4847 SelectionDAG &DAG) const { 4848 switch (N->getOpcode()) { 4849 case ISD::INSERT_VECTOR_ELT: { 4850 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4851 Results.push_back(Res); 4852 return; 4853 } 4854 case ISD::EXTRACT_VECTOR_ELT: { 4855 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4856 Results.push_back(Res); 4857 return; 4858 } 4859 case ISD::INTRINSIC_WO_CHAIN: { 4860 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4861 switch (IID) { 4862 case Intrinsic::amdgcn_cvt_pkrtz: { 4863 SDValue Src0 = N->getOperand(1); 4864 SDValue Src1 = N->getOperand(2); 4865 SDLoc SL(N); 4866 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4867 Src0, Src1); 4868 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4869 return; 4870 } 4871 case Intrinsic::amdgcn_cvt_pknorm_i16: 4872 case Intrinsic::amdgcn_cvt_pknorm_u16: 4873 case Intrinsic::amdgcn_cvt_pk_i16: 4874 case Intrinsic::amdgcn_cvt_pk_u16: { 4875 SDValue Src0 = N->getOperand(1); 4876 SDValue Src1 = N->getOperand(2); 4877 SDLoc SL(N); 4878 unsigned Opcode; 4879 4880 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4881 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4882 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4883 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4884 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4885 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4886 else 4887 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4888 4889 EVT VT = N->getValueType(0); 4890 if (isTypeLegal(VT)) 4891 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4892 else { 4893 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4894 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4895 } 4896 return; 4897 } 4898 } 4899 break; 4900 } 4901 case ISD::INTRINSIC_W_CHAIN: { 4902 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4903 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4904 // FIXME: Hacky 4905 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4906 Results.push_back(Res.getOperand(I)); 4907 } 4908 } else { 4909 Results.push_back(Res); 4910 Results.push_back(Res.getValue(1)); 4911 } 4912 return; 4913 } 4914 4915 break; 4916 } 4917 case ISD::SELECT: { 4918 SDLoc SL(N); 4919 EVT VT = N->getValueType(0); 4920 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4921 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4922 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4923 4924 EVT SelectVT = NewVT; 4925 if (NewVT.bitsLT(MVT::i32)) { 4926 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4927 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4928 SelectVT = MVT::i32; 4929 } 4930 4931 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4932 N->getOperand(0), LHS, RHS); 4933 4934 if (NewVT != SelectVT) 4935 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4936 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4937 return; 4938 } 4939 case ISD::FNEG: { 4940 if (N->getValueType(0) != MVT::v2f16) 4941 break; 4942 4943 SDLoc SL(N); 4944 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4945 4946 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4947 BC, 4948 DAG.getConstant(0x80008000, SL, MVT::i32)); 4949 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4950 return; 4951 } 4952 case ISD::FABS: { 4953 if (N->getValueType(0) != MVT::v2f16) 4954 break; 4955 4956 SDLoc SL(N); 4957 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4958 4959 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4960 BC, 4961 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4962 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4963 return; 4964 } 4965 default: 4966 break; 4967 } 4968 } 4969 4970 /// Helper function for LowerBRCOND 4971 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4972 4973 SDNode *Parent = Value.getNode(); 4974 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4975 I != E; ++I) { 4976 4977 if (I.getUse().get() != Value) 4978 continue; 4979 4980 if (I->getOpcode() == Opcode) 4981 return *I; 4982 } 4983 return nullptr; 4984 } 4985 4986 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4987 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4988 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4989 case Intrinsic::amdgcn_if: 4990 return AMDGPUISD::IF; 4991 case Intrinsic::amdgcn_else: 4992 return AMDGPUISD::ELSE; 4993 case Intrinsic::amdgcn_loop: 4994 return AMDGPUISD::LOOP; 4995 case Intrinsic::amdgcn_end_cf: 4996 llvm_unreachable("should not occur"); 4997 default: 4998 return 0; 4999 } 5000 } 5001 5002 // break, if_break, else_break are all only used as inputs to loop, not 5003 // directly as branch conditions. 5004 return 0; 5005 } 5006 5007 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5008 const Triple &TT = getTargetMachine().getTargetTriple(); 5009 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5010 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5011 AMDGPU::shouldEmitConstantsToTextSection(TT); 5012 } 5013 5014 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5015 // FIXME: Either avoid relying on address space here or change the default 5016 // address space for functions to avoid the explicit check. 5017 return (GV->getValueType()->isFunctionTy() || 5018 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5019 !shouldEmitFixup(GV) && 5020 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5021 } 5022 5023 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5024 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5025 } 5026 5027 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5028 if (!GV->hasExternalLinkage()) 5029 return true; 5030 5031 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5032 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5033 } 5034 5035 /// This transforms the control flow intrinsics to get the branch destination as 5036 /// last parameter, also switches branch target with BR if the need arise 5037 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5038 SelectionDAG &DAG) const { 5039 SDLoc DL(BRCOND); 5040 5041 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5042 SDValue Target = BRCOND.getOperand(2); 5043 SDNode *BR = nullptr; 5044 SDNode *SetCC = nullptr; 5045 5046 if (Intr->getOpcode() == ISD::SETCC) { 5047 // As long as we negate the condition everything is fine 5048 SetCC = Intr; 5049 Intr = SetCC->getOperand(0).getNode(); 5050 5051 } else { 5052 // Get the target from BR if we don't negate the condition 5053 BR = findUser(BRCOND, ISD::BR); 5054 assert(BR && "brcond missing unconditional branch user"); 5055 Target = BR->getOperand(1); 5056 } 5057 5058 unsigned CFNode = isCFIntrinsic(Intr); 5059 if (CFNode == 0) { 5060 // This is a uniform branch so we don't need to legalize. 5061 return BRCOND; 5062 } 5063 5064 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5065 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5066 5067 assert(!SetCC || 5068 (SetCC->getConstantOperandVal(1) == 1 && 5069 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5070 ISD::SETNE)); 5071 5072 // operands of the new intrinsic call 5073 SmallVector<SDValue, 4> Ops; 5074 if (HaveChain) 5075 Ops.push_back(BRCOND.getOperand(0)); 5076 5077 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5078 Ops.push_back(Target); 5079 5080 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5081 5082 // build the new intrinsic call 5083 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5084 5085 if (!HaveChain) { 5086 SDValue Ops[] = { 5087 SDValue(Result, 0), 5088 BRCOND.getOperand(0) 5089 }; 5090 5091 Result = DAG.getMergeValues(Ops, DL).getNode(); 5092 } 5093 5094 if (BR) { 5095 // Give the branch instruction our target 5096 SDValue Ops[] = { 5097 BR->getOperand(0), 5098 BRCOND.getOperand(2) 5099 }; 5100 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5101 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5102 } 5103 5104 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5105 5106 // Copy the intrinsic results to registers 5107 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5108 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5109 if (!CopyToReg) 5110 continue; 5111 5112 Chain = DAG.getCopyToReg( 5113 Chain, DL, 5114 CopyToReg->getOperand(1), 5115 SDValue(Result, i - 1), 5116 SDValue()); 5117 5118 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5119 } 5120 5121 // Remove the old intrinsic from the chain 5122 DAG.ReplaceAllUsesOfValueWith( 5123 SDValue(Intr, Intr->getNumValues() - 1), 5124 Intr->getOperand(0)); 5125 5126 return Chain; 5127 } 5128 5129 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5130 SelectionDAG &DAG) const { 5131 MVT VT = Op.getSimpleValueType(); 5132 SDLoc DL(Op); 5133 // Checking the depth 5134 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5135 return DAG.getConstant(0, DL, VT); 5136 5137 MachineFunction &MF = DAG.getMachineFunction(); 5138 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5139 // Check for kernel and shader functions 5140 if (Info->isEntryFunction()) 5141 return DAG.getConstant(0, DL, VT); 5142 5143 MachineFrameInfo &MFI = MF.getFrameInfo(); 5144 // There is a call to @llvm.returnaddress in this function 5145 MFI.setReturnAddressIsTaken(true); 5146 5147 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5148 // Get the return address reg and mark it as an implicit live-in 5149 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5150 5151 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5152 } 5153 5154 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5155 SDValue Op, 5156 const SDLoc &DL, 5157 EVT VT) const { 5158 return Op.getValueType().bitsLE(VT) ? 5159 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5160 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5161 DAG.getTargetConstant(0, DL, MVT::i32)); 5162 } 5163 5164 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5165 assert(Op.getValueType() == MVT::f16 && 5166 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5167 5168 SDValue Src = Op.getOperand(0); 5169 EVT SrcVT = Src.getValueType(); 5170 if (SrcVT != MVT::f64) 5171 return Op; 5172 5173 SDLoc DL(Op); 5174 5175 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5176 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5177 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5178 } 5179 5180 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5181 SelectionDAG &DAG) const { 5182 EVT VT = Op.getValueType(); 5183 const MachineFunction &MF = DAG.getMachineFunction(); 5184 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5185 bool IsIEEEMode = Info->getMode().IEEE; 5186 5187 // FIXME: Assert during selection that this is only selected for 5188 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5189 // mode functions, but this happens to be OK since it's only done in cases 5190 // where there is known no sNaN. 5191 if (IsIEEEMode) 5192 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5193 5194 if (VT == MVT::v4f16) 5195 return splitBinaryVectorOp(Op, DAG); 5196 return Op; 5197 } 5198 5199 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5200 EVT VT = Op.getValueType(); 5201 SDLoc SL(Op); 5202 SDValue LHS = Op.getOperand(0); 5203 SDValue RHS = Op.getOperand(1); 5204 bool isSigned = Op.getOpcode() == ISD::SMULO; 5205 5206 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5207 const APInt &C = RHSC->getAPIntValue(); 5208 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5209 if (C.isPowerOf2()) { 5210 // smulo(x, signed_min) is same as umulo(x, signed_min). 5211 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5212 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5213 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5214 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5215 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5216 SL, VT, Result, ShiftAmt), 5217 LHS, ISD::SETNE); 5218 return DAG.getMergeValues({ Result, Overflow }, SL); 5219 } 5220 } 5221 5222 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5223 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5224 SL, VT, LHS, RHS); 5225 5226 SDValue Sign = isSigned 5227 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5228 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5229 : DAG.getConstant(0, SL, VT); 5230 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5231 5232 return DAG.getMergeValues({ Result, Overflow }, SL); 5233 } 5234 5235 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5236 if (!Subtarget->isTrapHandlerEnabled() || 5237 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5238 return lowerTrapEndpgm(Op, DAG); 5239 5240 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5241 switch (*HsaAbiVer) { 5242 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5243 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5244 return lowerTrapHsaQueuePtr(Op, DAG); 5245 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5246 return Subtarget->supportsGetDoorbellID() ? 5247 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5248 } 5249 } 5250 5251 llvm_unreachable("Unknown trap handler"); 5252 } 5253 5254 SDValue SITargetLowering::lowerTrapEndpgm( 5255 SDValue Op, SelectionDAG &DAG) const { 5256 SDLoc SL(Op); 5257 SDValue Chain = Op.getOperand(0); 5258 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5259 } 5260 5261 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5262 SDValue Op, SelectionDAG &DAG) const { 5263 SDLoc SL(Op); 5264 SDValue Chain = Op.getOperand(0); 5265 5266 MachineFunction &MF = DAG.getMachineFunction(); 5267 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5268 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5269 assert(UserSGPR != AMDGPU::NoRegister); 5270 SDValue QueuePtr = CreateLiveInRegister( 5271 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5272 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5273 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5274 QueuePtr, SDValue()); 5275 5276 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5277 SDValue Ops[] = { 5278 ToReg, 5279 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5280 SGPR01, 5281 ToReg.getValue(1) 5282 }; 5283 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5284 } 5285 5286 SDValue SITargetLowering::lowerTrapHsa( 5287 SDValue Op, SelectionDAG &DAG) const { 5288 SDLoc SL(Op); 5289 SDValue Chain = Op.getOperand(0); 5290 5291 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5292 SDValue Ops[] = { 5293 Chain, 5294 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5295 }; 5296 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5297 } 5298 5299 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5300 SDLoc SL(Op); 5301 SDValue Chain = Op.getOperand(0); 5302 MachineFunction &MF = DAG.getMachineFunction(); 5303 5304 if (!Subtarget->isTrapHandlerEnabled() || 5305 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5306 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5307 "debugtrap handler not supported", 5308 Op.getDebugLoc(), 5309 DS_Warning); 5310 LLVMContext &Ctx = MF.getFunction().getContext(); 5311 Ctx.diagnose(NoTrap); 5312 return Chain; 5313 } 5314 5315 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5316 SDValue Ops[] = { 5317 Chain, 5318 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5319 }; 5320 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5321 } 5322 5323 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5324 SelectionDAG &DAG) const { 5325 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5326 if (Subtarget->hasApertureRegs()) { 5327 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5328 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5329 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5330 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5331 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5332 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5333 unsigned Encoding = 5334 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5335 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5336 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5337 5338 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5339 SDValue ApertureReg = SDValue( 5340 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5341 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5342 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5343 } 5344 5345 MachineFunction &MF = DAG.getMachineFunction(); 5346 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5347 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5348 assert(UserSGPR != AMDGPU::NoRegister); 5349 5350 SDValue QueuePtr = CreateLiveInRegister( 5351 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5352 5353 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5354 // private_segment_aperture_base_hi. 5355 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5356 5357 SDValue Ptr = 5358 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5359 5360 // TODO: Use custom target PseudoSourceValue. 5361 // TODO: We should use the value from the IR intrinsic call, but it might not 5362 // be available and how do we get it? 5363 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5364 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5365 commonAlignment(Align(64), StructOffset), 5366 MachineMemOperand::MODereferenceable | 5367 MachineMemOperand::MOInvariant); 5368 } 5369 5370 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5371 SelectionDAG &DAG) const { 5372 SDLoc SL(Op); 5373 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5374 5375 SDValue Src = ASC->getOperand(0); 5376 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5377 5378 const AMDGPUTargetMachine &TM = 5379 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5380 5381 // flat -> local/private 5382 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5383 unsigned DestAS = ASC->getDestAddressSpace(); 5384 5385 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5386 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5387 unsigned NullVal = TM.getNullPointerValue(DestAS); 5388 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5389 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5390 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5391 5392 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5393 NonNull, Ptr, SegmentNullPtr); 5394 } 5395 } 5396 5397 // local/private -> flat 5398 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5399 unsigned SrcAS = ASC->getSrcAddressSpace(); 5400 5401 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5402 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5403 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5404 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5405 5406 SDValue NonNull 5407 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5408 5409 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5410 SDValue CvtPtr 5411 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5412 5413 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5414 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5415 FlatNullPtr); 5416 } 5417 } 5418 5419 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5420 Src.getValueType() == MVT::i64) 5421 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5422 5423 // global <-> flat are no-ops and never emitted. 5424 5425 const MachineFunction &MF = DAG.getMachineFunction(); 5426 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5427 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5428 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5429 5430 return DAG.getUNDEF(ASC->getValueType(0)); 5431 } 5432 5433 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5434 // the small vector and inserting them into the big vector. That is better than 5435 // the default expansion of doing it via a stack slot. Even though the use of 5436 // the stack slot would be optimized away afterwards, the stack slot itself 5437 // remains. 5438 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5439 SelectionDAG &DAG) const { 5440 SDValue Vec = Op.getOperand(0); 5441 SDValue Ins = Op.getOperand(1); 5442 SDValue Idx = Op.getOperand(2); 5443 EVT VecVT = Vec.getValueType(); 5444 EVT InsVT = Ins.getValueType(); 5445 EVT EltVT = VecVT.getVectorElementType(); 5446 unsigned InsNumElts = InsVT.getVectorNumElements(); 5447 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5448 SDLoc SL(Op); 5449 5450 for (unsigned I = 0; I != InsNumElts; ++I) { 5451 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5452 DAG.getConstant(I, SL, MVT::i32)); 5453 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5454 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5455 } 5456 return Vec; 5457 } 5458 5459 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5460 SelectionDAG &DAG) const { 5461 SDValue Vec = Op.getOperand(0); 5462 SDValue InsVal = Op.getOperand(1); 5463 SDValue Idx = Op.getOperand(2); 5464 EVT VecVT = Vec.getValueType(); 5465 EVT EltVT = VecVT.getVectorElementType(); 5466 unsigned VecSize = VecVT.getSizeInBits(); 5467 unsigned EltSize = EltVT.getSizeInBits(); 5468 5469 5470 assert(VecSize <= 64); 5471 5472 unsigned NumElts = VecVT.getVectorNumElements(); 5473 SDLoc SL(Op); 5474 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5475 5476 if (NumElts == 4 && EltSize == 16 && KIdx) { 5477 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5478 5479 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5480 DAG.getConstant(0, SL, MVT::i32)); 5481 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5482 DAG.getConstant(1, SL, MVT::i32)); 5483 5484 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5485 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5486 5487 unsigned Idx = KIdx->getZExtValue(); 5488 bool InsertLo = Idx < 2; 5489 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5490 InsertLo ? LoVec : HiVec, 5491 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5492 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5493 5494 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5495 5496 SDValue Concat = InsertLo ? 5497 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5498 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5499 5500 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5501 } 5502 5503 if (isa<ConstantSDNode>(Idx)) 5504 return SDValue(); 5505 5506 MVT IntVT = MVT::getIntegerVT(VecSize); 5507 5508 // Avoid stack access for dynamic indexing. 5509 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5510 5511 // Create a congruent vector with the target value in each element so that 5512 // the required element can be masked and ORed into the target vector. 5513 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5514 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5515 5516 assert(isPowerOf2_32(EltSize)); 5517 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5518 5519 // Convert vector index to bit-index. 5520 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5521 5522 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5523 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5524 DAG.getConstant(0xffff, SL, IntVT), 5525 ScaledIdx); 5526 5527 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5528 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5529 DAG.getNOT(SL, BFM, IntVT), BCVec); 5530 5531 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5532 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5533 } 5534 5535 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5536 SelectionDAG &DAG) const { 5537 SDLoc SL(Op); 5538 5539 EVT ResultVT = Op.getValueType(); 5540 SDValue Vec = Op.getOperand(0); 5541 SDValue Idx = Op.getOperand(1); 5542 EVT VecVT = Vec.getValueType(); 5543 unsigned VecSize = VecVT.getSizeInBits(); 5544 EVT EltVT = VecVT.getVectorElementType(); 5545 assert(VecSize <= 64); 5546 5547 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5548 5549 // Make sure we do any optimizations that will make it easier to fold 5550 // source modifiers before obscuring it with bit operations. 5551 5552 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5553 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5554 return Combined; 5555 5556 unsigned EltSize = EltVT.getSizeInBits(); 5557 assert(isPowerOf2_32(EltSize)); 5558 5559 MVT IntVT = MVT::getIntegerVT(VecSize); 5560 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5561 5562 // Convert vector index to bit-index (* EltSize) 5563 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5564 5565 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5566 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5567 5568 if (ResultVT == MVT::f16) { 5569 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5570 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5571 } 5572 5573 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5574 } 5575 5576 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5577 assert(Elt % 2 == 0); 5578 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5579 } 5580 5581 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5582 SelectionDAG &DAG) const { 5583 SDLoc SL(Op); 5584 EVT ResultVT = Op.getValueType(); 5585 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5586 5587 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5588 EVT EltVT = PackVT.getVectorElementType(); 5589 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5590 5591 // vector_shuffle <0,1,6,7> lhs, rhs 5592 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5593 // 5594 // vector_shuffle <6,7,2,3> lhs, rhs 5595 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5596 // 5597 // vector_shuffle <6,7,0,1> lhs, rhs 5598 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5599 5600 // Avoid scalarizing when both halves are reading from consecutive elements. 5601 SmallVector<SDValue, 4> Pieces; 5602 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5603 if (elementPairIsContiguous(SVN->getMask(), I)) { 5604 const int Idx = SVN->getMaskElt(I); 5605 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5606 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5607 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5608 PackVT, SVN->getOperand(VecIdx), 5609 DAG.getConstant(EltIdx, SL, MVT::i32)); 5610 Pieces.push_back(SubVec); 5611 } else { 5612 const int Idx0 = SVN->getMaskElt(I); 5613 const int Idx1 = SVN->getMaskElt(I + 1); 5614 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5615 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5616 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5617 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5618 5619 SDValue Vec0 = SVN->getOperand(VecIdx0); 5620 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5621 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5622 5623 SDValue Vec1 = SVN->getOperand(VecIdx1); 5624 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5625 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5626 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5627 } 5628 } 5629 5630 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5631 } 5632 5633 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5634 SelectionDAG &DAG) const { 5635 SDLoc SL(Op); 5636 EVT VT = Op.getValueType(); 5637 5638 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5639 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5640 5641 // Turn into pair of packed build_vectors. 5642 // TODO: Special case for constants that can be materialized with s_mov_b64. 5643 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5644 { Op.getOperand(0), Op.getOperand(1) }); 5645 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5646 { Op.getOperand(2), Op.getOperand(3) }); 5647 5648 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5649 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5650 5651 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5652 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5653 } 5654 5655 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5656 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5657 5658 SDValue Lo = Op.getOperand(0); 5659 SDValue Hi = Op.getOperand(1); 5660 5661 // Avoid adding defined bits with the zero_extend. 5662 if (Hi.isUndef()) { 5663 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5664 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5665 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5666 } 5667 5668 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5669 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5670 5671 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5672 DAG.getConstant(16, SL, MVT::i32)); 5673 if (Lo.isUndef()) 5674 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5675 5676 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5677 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5678 5679 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5680 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5681 } 5682 5683 bool 5684 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5685 // We can fold offsets for anything that doesn't require a GOT relocation. 5686 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5687 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5688 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5689 !shouldEmitGOTReloc(GA->getGlobal()); 5690 } 5691 5692 static SDValue 5693 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5694 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5695 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5696 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5697 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5698 // lowered to the following code sequence: 5699 // 5700 // For constant address space: 5701 // s_getpc_b64 s[0:1] 5702 // s_add_u32 s0, s0, $symbol 5703 // s_addc_u32 s1, s1, 0 5704 // 5705 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5706 // a fixup or relocation is emitted to replace $symbol with a literal 5707 // constant, which is a pc-relative offset from the encoding of the $symbol 5708 // operand to the global variable. 5709 // 5710 // For global address space: 5711 // s_getpc_b64 s[0:1] 5712 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5713 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5714 // 5715 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5716 // fixups or relocations are emitted to replace $symbol@*@lo and 5717 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5718 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5719 // operand to the global variable. 5720 // 5721 // What we want here is an offset from the value returned by s_getpc 5722 // (which is the address of the s_add_u32 instruction) to the global 5723 // variable, but since the encoding of $symbol starts 4 bytes after the start 5724 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5725 // small. This requires us to add 4 to the global variable offset in order to 5726 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5727 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5728 // instruction. 5729 SDValue PtrLo = 5730 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5731 SDValue PtrHi; 5732 if (GAFlags == SIInstrInfo::MO_NONE) { 5733 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5734 } else { 5735 PtrHi = 5736 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5737 } 5738 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5739 } 5740 5741 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5742 SDValue Op, 5743 SelectionDAG &DAG) const { 5744 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5745 SDLoc DL(GSD); 5746 EVT PtrVT = Op.getValueType(); 5747 5748 const GlobalValue *GV = GSD->getGlobal(); 5749 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5750 shouldUseLDSConstAddress(GV)) || 5751 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5752 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5753 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5754 GV->hasExternalLinkage()) { 5755 Type *Ty = GV->getValueType(); 5756 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5757 // zero-sized type in other languages to declare the dynamic shared 5758 // memory which size is not known at the compile time. They will be 5759 // allocated by the runtime and placed directly after the static 5760 // allocated ones. They all share the same offset. 5761 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5762 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5763 // Adjust alignment for that dynamic shared memory array. 5764 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5765 return SDValue( 5766 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5767 } 5768 } 5769 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5770 } 5771 5772 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5773 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5774 SIInstrInfo::MO_ABS32_LO); 5775 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5776 } 5777 5778 if (shouldEmitFixup(GV)) 5779 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5780 else if (shouldEmitPCReloc(GV)) 5781 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5782 SIInstrInfo::MO_REL32); 5783 5784 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5785 SIInstrInfo::MO_GOTPCREL32); 5786 5787 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5788 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5789 const DataLayout &DataLayout = DAG.getDataLayout(); 5790 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5791 MachinePointerInfo PtrInfo 5792 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5793 5794 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5795 MachineMemOperand::MODereferenceable | 5796 MachineMemOperand::MOInvariant); 5797 } 5798 5799 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5800 const SDLoc &DL, SDValue V) const { 5801 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5802 // the destination register. 5803 // 5804 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5805 // so we will end up with redundant moves to m0. 5806 // 5807 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5808 5809 // A Null SDValue creates a glue result. 5810 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5811 V, Chain); 5812 return SDValue(M0, 0); 5813 } 5814 5815 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5816 SDValue Op, 5817 MVT VT, 5818 unsigned Offset) const { 5819 SDLoc SL(Op); 5820 SDValue Param = lowerKernargMemParameter( 5821 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5822 // The local size values will have the hi 16-bits as zero. 5823 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5824 DAG.getValueType(VT)); 5825 } 5826 5827 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5828 EVT VT) { 5829 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5830 "non-hsa intrinsic with hsa target", 5831 DL.getDebugLoc()); 5832 DAG.getContext()->diagnose(BadIntrin); 5833 return DAG.getUNDEF(VT); 5834 } 5835 5836 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5837 EVT VT) { 5838 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5839 "intrinsic not supported on subtarget", 5840 DL.getDebugLoc()); 5841 DAG.getContext()->diagnose(BadIntrin); 5842 return DAG.getUNDEF(VT); 5843 } 5844 5845 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5846 ArrayRef<SDValue> Elts) { 5847 assert(!Elts.empty()); 5848 MVT Type; 5849 unsigned NumElts = Elts.size(); 5850 5851 if (NumElts <= 8) { 5852 Type = MVT::getVectorVT(MVT::f32, NumElts); 5853 } else { 5854 assert(Elts.size() <= 16); 5855 Type = MVT::v16f32; 5856 NumElts = 16; 5857 } 5858 5859 SmallVector<SDValue, 16> VecElts(NumElts); 5860 for (unsigned i = 0; i < Elts.size(); ++i) { 5861 SDValue Elt = Elts[i]; 5862 if (Elt.getValueType() != MVT::f32) 5863 Elt = DAG.getBitcast(MVT::f32, Elt); 5864 VecElts[i] = Elt; 5865 } 5866 for (unsigned i = Elts.size(); i < NumElts; ++i) 5867 VecElts[i] = DAG.getUNDEF(MVT::f32); 5868 5869 if (NumElts == 1) 5870 return VecElts[0]; 5871 return DAG.getBuildVector(Type, DL, VecElts); 5872 } 5873 5874 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5875 SDValue Src, int ExtraElts) { 5876 EVT SrcVT = Src.getValueType(); 5877 5878 SmallVector<SDValue, 8> Elts; 5879 5880 if (SrcVT.isVector()) 5881 DAG.ExtractVectorElements(Src, Elts); 5882 else 5883 Elts.push_back(Src); 5884 5885 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5886 while (ExtraElts--) 5887 Elts.push_back(Undef); 5888 5889 return DAG.getBuildVector(CastVT, DL, Elts); 5890 } 5891 5892 // Re-construct the required return value for a image load intrinsic. 5893 // This is more complicated due to the optional use TexFailCtrl which means the required 5894 // return type is an aggregate 5895 static SDValue constructRetValue(SelectionDAG &DAG, 5896 MachineSDNode *Result, 5897 ArrayRef<EVT> ResultTypes, 5898 bool IsTexFail, bool Unpacked, bool IsD16, 5899 int DMaskPop, int NumVDataDwords, 5900 const SDLoc &DL) { 5901 // Determine the required return type. This is the same regardless of IsTexFail flag 5902 EVT ReqRetVT = ResultTypes[0]; 5903 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5904 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5905 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5906 5907 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5908 DMaskPop : (DMaskPop + 1) / 2; 5909 5910 MVT DataDwordVT = NumDataDwords == 1 ? 5911 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5912 5913 MVT MaskPopVT = MaskPopDwords == 1 ? 5914 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5915 5916 SDValue Data(Result, 0); 5917 SDValue TexFail; 5918 5919 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5920 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5921 if (MaskPopVT.isVector()) { 5922 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5923 SDValue(Result, 0), ZeroIdx); 5924 } else { 5925 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5926 SDValue(Result, 0), ZeroIdx); 5927 } 5928 } 5929 5930 if (DataDwordVT.isVector()) 5931 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5932 NumDataDwords - MaskPopDwords); 5933 5934 if (IsD16) 5935 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5936 5937 EVT LegalReqRetVT = ReqRetVT; 5938 if (!ReqRetVT.isVector()) { 5939 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5940 } else { 5941 // We need to widen the return vector to a legal type 5942 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5943 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5944 LegalReqRetVT = 5945 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5946 ReqRetVT.getVectorNumElements() + 1); 5947 } 5948 } 5949 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5950 5951 if (IsTexFail) { 5952 TexFail = 5953 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5954 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5955 5956 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5957 } 5958 5959 if (Result->getNumValues() == 1) 5960 return Data; 5961 5962 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5963 } 5964 5965 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5966 SDValue *LWE, bool &IsTexFail) { 5967 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5968 5969 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5970 if (Value) { 5971 IsTexFail = true; 5972 } 5973 5974 SDLoc DL(TexFailCtrlConst); 5975 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5976 Value &= ~(uint64_t)0x1; 5977 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5978 Value &= ~(uint64_t)0x2; 5979 5980 return Value == 0; 5981 } 5982 5983 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 5984 MVT PackVectorVT, 5985 SmallVectorImpl<SDValue> &PackedAddrs, 5986 unsigned DimIdx, unsigned EndIdx, 5987 unsigned NumGradients) { 5988 SDLoc DL(Op); 5989 for (unsigned I = DimIdx; I < EndIdx; I++) { 5990 SDValue Addr = Op.getOperand(I); 5991 5992 // Gradients are packed with undef for each coordinate. 5993 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5994 // 1D: undef,dx/dh; undef,dx/dv 5995 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5996 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5997 if (((I + 1) >= EndIdx) || 5998 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5999 I == DimIdx + NumGradients - 1))) { 6000 if (Addr.getValueType() != MVT::i16) 6001 Addr = DAG.getBitcast(MVT::i16, Addr); 6002 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6003 } else { 6004 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6005 I++; 6006 } 6007 Addr = DAG.getBitcast(MVT::f32, Addr); 6008 PackedAddrs.push_back(Addr); 6009 } 6010 } 6011 6012 SDValue SITargetLowering::lowerImage(SDValue Op, 6013 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6014 SelectionDAG &DAG, bool WithChain) const { 6015 SDLoc DL(Op); 6016 MachineFunction &MF = DAG.getMachineFunction(); 6017 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6018 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6019 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6020 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6021 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6022 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6023 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6024 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6025 unsigned IntrOpcode = Intr->BaseOpcode; 6026 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6027 6028 SmallVector<EVT, 3> ResultTypes(Op->values()); 6029 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6030 bool IsD16 = false; 6031 bool IsG16 = false; 6032 bool IsA16 = false; 6033 SDValue VData; 6034 int NumVDataDwords; 6035 bool AdjustRetType = false; 6036 6037 // Offset of intrinsic arguments 6038 const unsigned ArgOffset = WithChain ? 2 : 1; 6039 6040 unsigned DMask; 6041 unsigned DMaskLanes = 0; 6042 6043 if (BaseOpcode->Atomic) { 6044 VData = Op.getOperand(2); 6045 6046 bool Is64Bit = VData.getValueType() == MVT::i64; 6047 if (BaseOpcode->AtomicX2) { 6048 SDValue VData2 = Op.getOperand(3); 6049 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6050 {VData, VData2}); 6051 if (Is64Bit) 6052 VData = DAG.getBitcast(MVT::v4i32, VData); 6053 6054 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6055 DMask = Is64Bit ? 0xf : 0x3; 6056 NumVDataDwords = Is64Bit ? 4 : 2; 6057 } else { 6058 DMask = Is64Bit ? 0x3 : 0x1; 6059 NumVDataDwords = Is64Bit ? 2 : 1; 6060 } 6061 } else { 6062 auto *DMaskConst = 6063 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6064 DMask = DMaskConst->getZExtValue(); 6065 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6066 6067 if (BaseOpcode->Store) { 6068 VData = Op.getOperand(2); 6069 6070 MVT StoreVT = VData.getSimpleValueType(); 6071 if (StoreVT.getScalarType() == MVT::f16) { 6072 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6073 return Op; // D16 is unsupported for this instruction 6074 6075 IsD16 = true; 6076 VData = handleD16VData(VData, DAG, true); 6077 } 6078 6079 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6080 } else { 6081 // Work out the num dwords based on the dmask popcount and underlying type 6082 // and whether packing is supported. 6083 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6084 if (LoadVT.getScalarType() == MVT::f16) { 6085 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6086 return Op; // D16 is unsupported for this instruction 6087 6088 IsD16 = true; 6089 } 6090 6091 // Confirm that the return type is large enough for the dmask specified 6092 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6093 (!LoadVT.isVector() && DMaskLanes > 1)) 6094 return Op; 6095 6096 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6097 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6098 // instructions. 6099 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6100 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6101 NumVDataDwords = (DMaskLanes + 1) / 2; 6102 else 6103 NumVDataDwords = DMaskLanes; 6104 6105 AdjustRetType = true; 6106 } 6107 } 6108 6109 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6110 SmallVector<SDValue, 4> VAddrs; 6111 6112 // Optimize _L to _LZ when _L is zero 6113 if (LZMappingInfo) { 6114 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6115 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6116 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6117 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6118 VAddrEnd--; // remove 'lod' 6119 } 6120 } 6121 } 6122 6123 // Optimize _mip away, when 'lod' is zero 6124 if (MIPMappingInfo) { 6125 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6126 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6127 if (ConstantLod->isNullValue()) { 6128 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6129 VAddrEnd--; // remove 'mip' 6130 } 6131 } 6132 } 6133 6134 // Push back extra arguments. 6135 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6136 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6137 6138 // Check for 16 bit addresses or derivatives and pack if true. 6139 MVT VAddrVT = 6140 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6141 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6142 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6143 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6144 6145 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6146 VAddrScalarVT = VAddrVT.getScalarType(); 6147 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6148 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6149 6150 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6151 // 16 bit gradients are supported, but are tied to the A16 control 6152 // so both gradients and addresses must be 16 bit 6153 LLVM_DEBUG( 6154 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6155 "require 16 bit args for both gradients and addresses"); 6156 return Op; 6157 } 6158 6159 if (IsA16) { 6160 if (!ST->hasA16()) { 6161 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6162 "support 16 bit addresses\n"); 6163 return Op; 6164 } 6165 } 6166 6167 // We've dealt with incorrect input so we know that if IsA16, IsG16 6168 // are set then we have to compress/pack operands (either address, 6169 // gradient or both) 6170 // In the case where a16 and gradients are tied (no G16 support) then we 6171 // have already verified that both IsA16 and IsG16 are true 6172 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6173 // Activate g16 6174 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6175 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6176 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6177 } 6178 6179 // Add gradients (packed or unpacked) 6180 if (IsG16) { 6181 // Pack the gradients 6182 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6183 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6184 ArgOffset + Intr->GradientStart, 6185 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6186 } else { 6187 for (unsigned I = ArgOffset + Intr->GradientStart; 6188 I < ArgOffset + Intr->CoordStart; I++) 6189 VAddrs.push_back(Op.getOperand(I)); 6190 } 6191 6192 // Add addresses (packed or unpacked) 6193 if (IsA16) { 6194 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6195 ArgOffset + Intr->CoordStart, VAddrEnd, 6196 0 /* No gradients */); 6197 } else { 6198 // Add uncompressed address 6199 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6200 VAddrs.push_back(Op.getOperand(I)); 6201 } 6202 6203 // If the register allocator cannot place the address registers contiguously 6204 // without introducing moves, then using the non-sequential address encoding 6205 // is always preferable, since it saves VALU instructions and is usually a 6206 // wash in terms of code size or even better. 6207 // 6208 // However, we currently have no way of hinting to the register allocator that 6209 // MIMG addresses should be placed contiguously when it is possible to do so, 6210 // so force non-NSA for the common 2-address case as a heuristic. 6211 // 6212 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6213 // allocation when possible. 6214 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6215 VAddrs.size() >= 3 && 6216 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6217 SDValue VAddr; 6218 if (!UseNSA) 6219 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6220 6221 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6222 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6223 SDValue Unorm; 6224 if (!BaseOpcode->Sampler) { 6225 Unorm = True; 6226 } else { 6227 auto UnormConst = 6228 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6229 6230 Unorm = UnormConst->getZExtValue() ? True : False; 6231 } 6232 6233 SDValue TFE; 6234 SDValue LWE; 6235 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6236 bool IsTexFail = false; 6237 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6238 return Op; 6239 6240 if (IsTexFail) { 6241 if (!DMaskLanes) { 6242 // Expecting to get an error flag since TFC is on - and dmask is 0 6243 // Force dmask to be at least 1 otherwise the instruction will fail 6244 DMask = 0x1; 6245 DMaskLanes = 1; 6246 NumVDataDwords = 1; 6247 } 6248 NumVDataDwords += 1; 6249 AdjustRetType = true; 6250 } 6251 6252 // Has something earlier tagged that the return type needs adjusting 6253 // This happens if the instruction is a load or has set TexFailCtrl flags 6254 if (AdjustRetType) { 6255 // NumVDataDwords reflects the true number of dwords required in the return type 6256 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6257 // This is a no-op load. This can be eliminated 6258 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6259 if (isa<MemSDNode>(Op)) 6260 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6261 return Undef; 6262 } 6263 6264 EVT NewVT = NumVDataDwords > 1 ? 6265 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6266 : MVT::i32; 6267 6268 ResultTypes[0] = NewVT; 6269 if (ResultTypes.size() == 3) { 6270 // Original result was aggregate type used for TexFailCtrl results 6271 // The actual instruction returns as a vector type which has now been 6272 // created. Remove the aggregate result. 6273 ResultTypes.erase(&ResultTypes[1]); 6274 } 6275 } 6276 6277 unsigned CPol = cast<ConstantSDNode>( 6278 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6279 if (BaseOpcode->Atomic) 6280 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6281 if (CPol & ~AMDGPU::CPol::ALL) 6282 return Op; 6283 6284 SmallVector<SDValue, 26> Ops; 6285 if (BaseOpcode->Store || BaseOpcode->Atomic) 6286 Ops.push_back(VData); // vdata 6287 if (UseNSA) 6288 append_range(Ops, VAddrs); 6289 else 6290 Ops.push_back(VAddr); 6291 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6292 if (BaseOpcode->Sampler) 6293 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6294 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6295 if (IsGFX10Plus) 6296 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6297 Ops.push_back(Unorm); 6298 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6299 Ops.push_back(IsA16 && // r128, a16 for gfx9 6300 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6301 if (IsGFX10Plus) 6302 Ops.push_back(IsA16 ? True : False); 6303 if (!Subtarget->hasGFX90AInsts()) { 6304 Ops.push_back(TFE); //tfe 6305 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6306 report_fatal_error("TFE is not supported on this GPU"); 6307 } 6308 Ops.push_back(LWE); // lwe 6309 if (!IsGFX10Plus) 6310 Ops.push_back(DimInfo->DA ? True : False); 6311 if (BaseOpcode->HasD16) 6312 Ops.push_back(IsD16 ? True : False); 6313 if (isa<MemSDNode>(Op)) 6314 Ops.push_back(Op.getOperand(0)); // chain 6315 6316 int NumVAddrDwords = 6317 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6318 int Opcode = -1; 6319 6320 if (IsGFX10Plus) { 6321 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6322 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6323 : AMDGPU::MIMGEncGfx10Default, 6324 NumVDataDwords, NumVAddrDwords); 6325 } else { 6326 if (Subtarget->hasGFX90AInsts()) { 6327 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6328 NumVDataDwords, NumVAddrDwords); 6329 if (Opcode == -1) 6330 report_fatal_error( 6331 "requested image instruction is not supported on this GPU"); 6332 } 6333 if (Opcode == -1 && 6334 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6335 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6336 NumVDataDwords, NumVAddrDwords); 6337 if (Opcode == -1) 6338 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6339 NumVDataDwords, NumVAddrDwords); 6340 } 6341 assert(Opcode != -1); 6342 6343 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6344 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6345 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6346 DAG.setNodeMemRefs(NewNode, {MemRef}); 6347 } 6348 6349 if (BaseOpcode->AtomicX2) { 6350 SmallVector<SDValue, 1> Elt; 6351 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6352 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6353 } 6354 if (BaseOpcode->Store) 6355 return SDValue(NewNode, 0); 6356 return constructRetValue(DAG, NewNode, 6357 OrigResultTypes, IsTexFail, 6358 Subtarget->hasUnpackedD16VMem(), IsD16, 6359 DMaskLanes, NumVDataDwords, DL); 6360 } 6361 6362 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6363 SDValue Offset, SDValue CachePolicy, 6364 SelectionDAG &DAG) const { 6365 MachineFunction &MF = DAG.getMachineFunction(); 6366 6367 const DataLayout &DataLayout = DAG.getDataLayout(); 6368 Align Alignment = 6369 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6370 6371 MachineMemOperand *MMO = MF.getMachineMemOperand( 6372 MachinePointerInfo(), 6373 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6374 MachineMemOperand::MOInvariant, 6375 VT.getStoreSize(), Alignment); 6376 6377 if (!Offset->isDivergent()) { 6378 SDValue Ops[] = { 6379 Rsrc, 6380 Offset, // Offset 6381 CachePolicy 6382 }; 6383 6384 // Widen vec3 load to vec4. 6385 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6386 EVT WidenedVT = 6387 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6388 auto WidenedOp = DAG.getMemIntrinsicNode( 6389 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6390 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6391 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6392 DAG.getVectorIdxConstant(0, DL)); 6393 return Subvector; 6394 } 6395 6396 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6397 DAG.getVTList(VT), Ops, VT, MMO); 6398 } 6399 6400 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6401 // assume that the buffer is unswizzled. 6402 SmallVector<SDValue, 4> Loads; 6403 unsigned NumLoads = 1; 6404 MVT LoadVT = VT.getSimpleVT(); 6405 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6406 assert((LoadVT.getScalarType() == MVT::i32 || 6407 LoadVT.getScalarType() == MVT::f32)); 6408 6409 if (NumElts == 8 || NumElts == 16) { 6410 NumLoads = NumElts / 4; 6411 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6412 } 6413 6414 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6415 SDValue Ops[] = { 6416 DAG.getEntryNode(), // Chain 6417 Rsrc, // rsrc 6418 DAG.getConstant(0, DL, MVT::i32), // vindex 6419 {}, // voffset 6420 {}, // soffset 6421 {}, // offset 6422 CachePolicy, // cachepolicy 6423 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6424 }; 6425 6426 // Use the alignment to ensure that the required offsets will fit into the 6427 // immediate offsets. 6428 setBufferOffsets(Offset, DAG, &Ops[3], 6429 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6430 6431 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6432 for (unsigned i = 0; i < NumLoads; ++i) { 6433 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6434 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6435 LoadVT, MMO, DAG)); 6436 } 6437 6438 if (NumElts == 8 || NumElts == 16) 6439 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6440 6441 return Loads[0]; 6442 } 6443 6444 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6445 SelectionDAG &DAG) const { 6446 MachineFunction &MF = DAG.getMachineFunction(); 6447 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6448 6449 EVT VT = Op.getValueType(); 6450 SDLoc DL(Op); 6451 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6452 6453 // TODO: Should this propagate fast-math-flags? 6454 6455 switch (IntrinsicID) { 6456 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6457 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6458 return emitNonHSAIntrinsicError(DAG, DL, VT); 6459 return getPreloadedValue(DAG, *MFI, VT, 6460 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6461 } 6462 case Intrinsic::amdgcn_dispatch_ptr: 6463 case Intrinsic::amdgcn_queue_ptr: { 6464 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6465 DiagnosticInfoUnsupported BadIntrin( 6466 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6467 DL.getDebugLoc()); 6468 DAG.getContext()->diagnose(BadIntrin); 6469 return DAG.getUNDEF(VT); 6470 } 6471 6472 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6473 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6474 return getPreloadedValue(DAG, *MFI, VT, RegID); 6475 } 6476 case Intrinsic::amdgcn_implicitarg_ptr: { 6477 if (MFI->isEntryFunction()) 6478 return getImplicitArgPtr(DAG, DL); 6479 return getPreloadedValue(DAG, *MFI, VT, 6480 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6481 } 6482 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6483 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6484 // This only makes sense to call in a kernel, so just lower to null. 6485 return DAG.getConstant(0, DL, VT); 6486 } 6487 6488 return getPreloadedValue(DAG, *MFI, VT, 6489 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6490 } 6491 case Intrinsic::amdgcn_dispatch_id: { 6492 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6493 } 6494 case Intrinsic::amdgcn_rcp: 6495 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6496 case Intrinsic::amdgcn_rsq: 6497 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6498 case Intrinsic::amdgcn_rsq_legacy: 6499 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6500 return emitRemovedIntrinsicError(DAG, DL, VT); 6501 return SDValue(); 6502 case Intrinsic::amdgcn_rcp_legacy: 6503 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6504 return emitRemovedIntrinsicError(DAG, DL, VT); 6505 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6506 case Intrinsic::amdgcn_rsq_clamp: { 6507 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6508 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6509 6510 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6511 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6512 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6513 6514 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6515 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6516 DAG.getConstantFP(Max, DL, VT)); 6517 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6518 DAG.getConstantFP(Min, DL, VT)); 6519 } 6520 case Intrinsic::r600_read_ngroups_x: 6521 if (Subtarget->isAmdHsaOS()) 6522 return emitNonHSAIntrinsicError(DAG, DL, VT); 6523 6524 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6525 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6526 false); 6527 case Intrinsic::r600_read_ngroups_y: 6528 if (Subtarget->isAmdHsaOS()) 6529 return emitNonHSAIntrinsicError(DAG, DL, VT); 6530 6531 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6532 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6533 false); 6534 case Intrinsic::r600_read_ngroups_z: 6535 if (Subtarget->isAmdHsaOS()) 6536 return emitNonHSAIntrinsicError(DAG, DL, VT); 6537 6538 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6539 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6540 false); 6541 case Intrinsic::r600_read_global_size_x: 6542 if (Subtarget->isAmdHsaOS()) 6543 return emitNonHSAIntrinsicError(DAG, DL, VT); 6544 6545 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6546 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6547 Align(4), false); 6548 case Intrinsic::r600_read_global_size_y: 6549 if (Subtarget->isAmdHsaOS()) 6550 return emitNonHSAIntrinsicError(DAG, DL, VT); 6551 6552 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6553 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6554 Align(4), false); 6555 case Intrinsic::r600_read_global_size_z: 6556 if (Subtarget->isAmdHsaOS()) 6557 return emitNonHSAIntrinsicError(DAG, DL, VT); 6558 6559 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6560 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6561 Align(4), false); 6562 case Intrinsic::r600_read_local_size_x: 6563 if (Subtarget->isAmdHsaOS()) 6564 return emitNonHSAIntrinsicError(DAG, DL, VT); 6565 6566 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6567 SI::KernelInputOffsets::LOCAL_SIZE_X); 6568 case Intrinsic::r600_read_local_size_y: 6569 if (Subtarget->isAmdHsaOS()) 6570 return emitNonHSAIntrinsicError(DAG, DL, VT); 6571 6572 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6573 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6574 case Intrinsic::r600_read_local_size_z: 6575 if (Subtarget->isAmdHsaOS()) 6576 return emitNonHSAIntrinsicError(DAG, DL, VT); 6577 6578 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6579 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6580 case Intrinsic::amdgcn_workgroup_id_x: 6581 return getPreloadedValue(DAG, *MFI, VT, 6582 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6583 case Intrinsic::amdgcn_workgroup_id_y: 6584 return getPreloadedValue(DAG, *MFI, VT, 6585 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6586 case Intrinsic::amdgcn_workgroup_id_z: 6587 return getPreloadedValue(DAG, *MFI, VT, 6588 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6589 case Intrinsic::amdgcn_workitem_id_x: 6590 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6591 SDLoc(DAG.getEntryNode()), 6592 MFI->getArgInfo().WorkItemIDX); 6593 case Intrinsic::amdgcn_workitem_id_y: 6594 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6595 SDLoc(DAG.getEntryNode()), 6596 MFI->getArgInfo().WorkItemIDY); 6597 case Intrinsic::amdgcn_workitem_id_z: 6598 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6599 SDLoc(DAG.getEntryNode()), 6600 MFI->getArgInfo().WorkItemIDZ); 6601 case Intrinsic::amdgcn_wavefrontsize: 6602 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6603 SDLoc(Op), MVT::i32); 6604 case Intrinsic::amdgcn_s_buffer_load: { 6605 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6606 if (CPol & ~AMDGPU::CPol::ALL) 6607 return Op; 6608 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6609 DAG); 6610 } 6611 case Intrinsic::amdgcn_fdiv_fast: 6612 return lowerFDIV_FAST(Op, DAG); 6613 case Intrinsic::amdgcn_sin: 6614 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6615 6616 case Intrinsic::amdgcn_cos: 6617 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6618 6619 case Intrinsic::amdgcn_mul_u24: 6620 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6621 case Intrinsic::amdgcn_mul_i24: 6622 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6623 6624 case Intrinsic::amdgcn_log_clamp: { 6625 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6626 return SDValue(); 6627 6628 return emitRemovedIntrinsicError(DAG, DL, VT); 6629 } 6630 case Intrinsic::amdgcn_ldexp: 6631 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6632 Op.getOperand(1), Op.getOperand(2)); 6633 6634 case Intrinsic::amdgcn_fract: 6635 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6636 6637 case Intrinsic::amdgcn_class: 6638 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6639 Op.getOperand(1), Op.getOperand(2)); 6640 case Intrinsic::amdgcn_div_fmas: 6641 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6642 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6643 Op.getOperand(4)); 6644 6645 case Intrinsic::amdgcn_div_fixup: 6646 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6647 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6648 6649 case Intrinsic::amdgcn_div_scale: { 6650 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6651 6652 // Translate to the operands expected by the machine instruction. The 6653 // first parameter must be the same as the first instruction. 6654 SDValue Numerator = Op.getOperand(1); 6655 SDValue Denominator = Op.getOperand(2); 6656 6657 // Note this order is opposite of the machine instruction's operations, 6658 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6659 // intrinsic has the numerator as the first operand to match a normal 6660 // division operation. 6661 6662 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6663 6664 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6665 Denominator, Numerator); 6666 } 6667 case Intrinsic::amdgcn_icmp: { 6668 // There is a Pat that handles this variant, so return it as-is. 6669 if (Op.getOperand(1).getValueType() == MVT::i1 && 6670 Op.getConstantOperandVal(2) == 0 && 6671 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6672 return Op; 6673 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6674 } 6675 case Intrinsic::amdgcn_fcmp: { 6676 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6677 } 6678 case Intrinsic::amdgcn_ballot: 6679 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6680 case Intrinsic::amdgcn_fmed3: 6681 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6682 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6683 case Intrinsic::amdgcn_fdot2: 6684 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6685 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6686 Op.getOperand(4)); 6687 case Intrinsic::amdgcn_fmul_legacy: 6688 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6689 Op.getOperand(1), Op.getOperand(2)); 6690 case Intrinsic::amdgcn_sffbh: 6691 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6692 case Intrinsic::amdgcn_sbfe: 6693 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6694 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6695 case Intrinsic::amdgcn_ubfe: 6696 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6697 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6698 case Intrinsic::amdgcn_cvt_pkrtz: 6699 case Intrinsic::amdgcn_cvt_pknorm_i16: 6700 case Intrinsic::amdgcn_cvt_pknorm_u16: 6701 case Intrinsic::amdgcn_cvt_pk_i16: 6702 case Intrinsic::amdgcn_cvt_pk_u16: { 6703 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6704 EVT VT = Op.getValueType(); 6705 unsigned Opcode; 6706 6707 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6708 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6709 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6710 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6711 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6712 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6713 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6714 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6715 else 6716 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6717 6718 if (isTypeLegal(VT)) 6719 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6720 6721 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6722 Op.getOperand(1), Op.getOperand(2)); 6723 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6724 } 6725 case Intrinsic::amdgcn_fmad_ftz: 6726 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6727 Op.getOperand(2), Op.getOperand(3)); 6728 6729 case Intrinsic::amdgcn_if_break: 6730 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6731 Op->getOperand(1), Op->getOperand(2)), 0); 6732 6733 case Intrinsic::amdgcn_groupstaticsize: { 6734 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6735 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6736 return Op; 6737 6738 const Module *M = MF.getFunction().getParent(); 6739 const GlobalValue *GV = 6740 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6741 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6742 SIInstrInfo::MO_ABS32_LO); 6743 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6744 } 6745 case Intrinsic::amdgcn_is_shared: 6746 case Intrinsic::amdgcn_is_private: { 6747 SDLoc SL(Op); 6748 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6749 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6750 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6751 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6752 Op.getOperand(1)); 6753 6754 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6755 DAG.getConstant(1, SL, MVT::i32)); 6756 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6757 } 6758 case Intrinsic::amdgcn_alignbit: 6759 return DAG.getNode(ISD::FSHR, DL, VT, 6760 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6761 case Intrinsic::amdgcn_perm: 6762 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6763 Op.getOperand(2), Op.getOperand(3)); 6764 case Intrinsic::amdgcn_reloc_constant: { 6765 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6766 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6767 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6768 auto RelocSymbol = cast<GlobalVariable>( 6769 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6770 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6771 SIInstrInfo::MO_ABS32_LO); 6772 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6773 } 6774 default: 6775 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6776 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6777 return lowerImage(Op, ImageDimIntr, DAG, false); 6778 6779 return Op; 6780 } 6781 } 6782 6783 /// Update \p MMO based on the offset inputs to an intrinsic. If any of the 6784 /// offsets are non-constant or if \p VIndex is non-zero then this function does 6785 /// nothing. Otherwise, it sets the MMO offset to the sum of \p VOffset, \p 6786 /// SOffset, and \p Offset. 6787 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6788 SDValue SOffset, SDValue Offset, 6789 SDValue VIndex = SDValue()) { 6790 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6791 !isa<ConstantSDNode>(Offset)) 6792 return; 6793 6794 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6795 !cast<ConstantSDNode>(VIndex)->isNullValue())) 6796 return; 6797 6798 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6799 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6800 cast<ConstantSDNode>(Offset)->getSExtValue()); 6801 } 6802 6803 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6804 SelectionDAG &DAG, 6805 unsigned NewOpcode) const { 6806 SDLoc DL(Op); 6807 6808 SDValue VData = Op.getOperand(2); 6809 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6810 SDValue Ops[] = { 6811 Op.getOperand(0), // Chain 6812 VData, // vdata 6813 Op.getOperand(3), // rsrc 6814 DAG.getConstant(0, DL, MVT::i32), // vindex 6815 Offsets.first, // voffset 6816 Op.getOperand(5), // soffset 6817 Offsets.second, // offset 6818 Op.getOperand(6), // cachepolicy 6819 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6820 }; 6821 6822 auto *M = cast<MemSDNode>(Op); 6823 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6824 6825 EVT MemVT = VData.getValueType(); 6826 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6827 M->getMemOperand()); 6828 } 6829 6830 // Return a value to use for the idxen operand by examining the vindex operand. 6831 static unsigned getIdxEn(SDValue VIndex) { 6832 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 6833 // No need to set idxen if vindex is known to be zero. 6834 return VIndexC->getZExtValue() != 0; 6835 return 1; 6836 } 6837 6838 SDValue 6839 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6840 unsigned NewOpcode) const { 6841 SDLoc DL(Op); 6842 6843 SDValue VData = Op.getOperand(2); 6844 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6845 SDValue Ops[] = { 6846 Op.getOperand(0), // Chain 6847 VData, // vdata 6848 Op.getOperand(3), // rsrc 6849 Op.getOperand(4), // vindex 6850 Offsets.first, // voffset 6851 Op.getOperand(6), // soffset 6852 Offsets.second, // offset 6853 Op.getOperand(7), // cachepolicy 6854 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6855 }; 6856 6857 auto *M = cast<MemSDNode>(Op); 6858 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 6859 6860 EVT MemVT = VData.getValueType(); 6861 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6862 M->getMemOperand()); 6863 } 6864 6865 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6866 SelectionDAG &DAG) const { 6867 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6868 SDLoc DL(Op); 6869 6870 switch (IntrID) { 6871 case Intrinsic::amdgcn_ds_ordered_add: 6872 case Intrinsic::amdgcn_ds_ordered_swap: { 6873 MemSDNode *M = cast<MemSDNode>(Op); 6874 SDValue Chain = M->getOperand(0); 6875 SDValue M0 = M->getOperand(2); 6876 SDValue Value = M->getOperand(3); 6877 unsigned IndexOperand = M->getConstantOperandVal(7); 6878 unsigned WaveRelease = M->getConstantOperandVal(8); 6879 unsigned WaveDone = M->getConstantOperandVal(9); 6880 6881 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6882 IndexOperand &= ~0x3f; 6883 unsigned CountDw = 0; 6884 6885 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6886 CountDw = (IndexOperand >> 24) & 0xf; 6887 IndexOperand &= ~(0xf << 24); 6888 6889 if (CountDw < 1 || CountDw > 4) { 6890 report_fatal_error( 6891 "ds_ordered_count: dword count must be between 1 and 4"); 6892 } 6893 } 6894 6895 if (IndexOperand) 6896 report_fatal_error("ds_ordered_count: bad index operand"); 6897 6898 if (WaveDone && !WaveRelease) 6899 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6900 6901 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6902 unsigned ShaderType = 6903 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6904 unsigned Offset0 = OrderedCountIndex << 2; 6905 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6906 (Instruction << 4); 6907 6908 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6909 Offset1 |= (CountDw - 1) << 6; 6910 6911 unsigned Offset = Offset0 | (Offset1 << 8); 6912 6913 SDValue Ops[] = { 6914 Chain, 6915 Value, 6916 DAG.getTargetConstant(Offset, DL, MVT::i16), 6917 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6918 }; 6919 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6920 M->getVTList(), Ops, M->getMemoryVT(), 6921 M->getMemOperand()); 6922 } 6923 case Intrinsic::amdgcn_ds_fadd: { 6924 MemSDNode *M = cast<MemSDNode>(Op); 6925 unsigned Opc; 6926 switch (IntrID) { 6927 case Intrinsic::amdgcn_ds_fadd: 6928 Opc = ISD::ATOMIC_LOAD_FADD; 6929 break; 6930 } 6931 6932 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6933 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6934 M->getMemOperand()); 6935 } 6936 case Intrinsic::amdgcn_atomic_inc: 6937 case Intrinsic::amdgcn_atomic_dec: 6938 case Intrinsic::amdgcn_ds_fmin: 6939 case Intrinsic::amdgcn_ds_fmax: { 6940 MemSDNode *M = cast<MemSDNode>(Op); 6941 unsigned Opc; 6942 switch (IntrID) { 6943 case Intrinsic::amdgcn_atomic_inc: 6944 Opc = AMDGPUISD::ATOMIC_INC; 6945 break; 6946 case Intrinsic::amdgcn_atomic_dec: 6947 Opc = AMDGPUISD::ATOMIC_DEC; 6948 break; 6949 case Intrinsic::amdgcn_ds_fmin: 6950 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6951 break; 6952 case Intrinsic::amdgcn_ds_fmax: 6953 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6954 break; 6955 default: 6956 llvm_unreachable("Unknown intrinsic!"); 6957 } 6958 SDValue Ops[] = { 6959 M->getOperand(0), // Chain 6960 M->getOperand(2), // Ptr 6961 M->getOperand(3) // Value 6962 }; 6963 6964 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6965 M->getMemoryVT(), M->getMemOperand()); 6966 } 6967 case Intrinsic::amdgcn_buffer_load: 6968 case Intrinsic::amdgcn_buffer_load_format: { 6969 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6970 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6971 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 6972 SDValue Ops[] = { 6973 Op.getOperand(0), // Chain 6974 Op.getOperand(2), // rsrc 6975 Op.getOperand(3), // vindex 6976 SDValue(), // voffset -- will be set by setBufferOffsets 6977 SDValue(), // soffset -- will be set by setBufferOffsets 6978 SDValue(), // offset -- will be set by setBufferOffsets 6979 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6980 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6981 }; 6982 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6983 6984 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6985 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6986 6987 EVT VT = Op.getValueType(); 6988 EVT IntVT = VT.changeTypeToInteger(); 6989 auto *M = cast<MemSDNode>(Op); 6990 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 6991 EVT LoadVT = Op.getValueType(); 6992 6993 if (LoadVT.getScalarType() == MVT::f16) 6994 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6995 M, DAG, Ops); 6996 6997 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6998 if (LoadVT.getScalarType() == MVT::i8 || 6999 LoadVT.getScalarType() == MVT::i16) 7000 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7001 7002 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7003 M->getMemOperand(), DAG); 7004 } 7005 case Intrinsic::amdgcn_raw_buffer_load: 7006 case Intrinsic::amdgcn_raw_buffer_load_format: { 7007 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7008 7009 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7010 SDValue Ops[] = { 7011 Op.getOperand(0), // Chain 7012 Op.getOperand(2), // rsrc 7013 DAG.getConstant(0, DL, MVT::i32), // vindex 7014 Offsets.first, // voffset 7015 Op.getOperand(4), // soffset 7016 Offsets.second, // offset 7017 Op.getOperand(5), // cachepolicy, swizzled buffer 7018 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7019 }; 7020 7021 auto *M = cast<MemSDNode>(Op); 7022 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7023 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7024 } 7025 case Intrinsic::amdgcn_struct_buffer_load: 7026 case Intrinsic::amdgcn_struct_buffer_load_format: { 7027 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7028 7029 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7030 SDValue Ops[] = { 7031 Op.getOperand(0), // Chain 7032 Op.getOperand(2), // rsrc 7033 Op.getOperand(3), // vindex 7034 Offsets.first, // voffset 7035 Op.getOperand(5), // soffset 7036 Offsets.second, // offset 7037 Op.getOperand(6), // cachepolicy, swizzled buffer 7038 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7039 }; 7040 7041 auto *M = cast<MemSDNode>(Op); 7042 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7043 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7044 } 7045 case Intrinsic::amdgcn_tbuffer_load: { 7046 MemSDNode *M = cast<MemSDNode>(Op); 7047 EVT LoadVT = Op.getValueType(); 7048 7049 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7050 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7051 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7052 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7053 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7054 SDValue Ops[] = { 7055 Op.getOperand(0), // Chain 7056 Op.getOperand(2), // rsrc 7057 Op.getOperand(3), // vindex 7058 Op.getOperand(4), // voffset 7059 Op.getOperand(5), // soffset 7060 Op.getOperand(6), // offset 7061 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7062 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7063 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7064 }; 7065 7066 if (LoadVT.getScalarType() == MVT::f16) 7067 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7068 M, DAG, Ops); 7069 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7070 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7071 DAG); 7072 } 7073 case Intrinsic::amdgcn_raw_tbuffer_load: { 7074 MemSDNode *M = cast<MemSDNode>(Op); 7075 EVT LoadVT = Op.getValueType(); 7076 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7077 7078 SDValue Ops[] = { 7079 Op.getOperand(0), // Chain 7080 Op.getOperand(2), // rsrc 7081 DAG.getConstant(0, DL, MVT::i32), // vindex 7082 Offsets.first, // voffset 7083 Op.getOperand(4), // soffset 7084 Offsets.second, // offset 7085 Op.getOperand(5), // format 7086 Op.getOperand(6), // cachepolicy, swizzled buffer 7087 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7088 }; 7089 7090 if (LoadVT.getScalarType() == MVT::f16) 7091 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7092 M, DAG, Ops); 7093 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7094 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7095 DAG); 7096 } 7097 case Intrinsic::amdgcn_struct_tbuffer_load: { 7098 MemSDNode *M = cast<MemSDNode>(Op); 7099 EVT LoadVT = Op.getValueType(); 7100 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7101 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), // format 7110 Op.getOperand(7), // cachepolicy, swizzled buffer 7111 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7112 }; 7113 7114 if (LoadVT.getScalarType() == MVT::f16) 7115 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7116 M, DAG, Ops); 7117 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7118 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7119 DAG); 7120 } 7121 case Intrinsic::amdgcn_buffer_atomic_swap: 7122 case Intrinsic::amdgcn_buffer_atomic_add: 7123 case Intrinsic::amdgcn_buffer_atomic_sub: 7124 case Intrinsic::amdgcn_buffer_atomic_csub: 7125 case Intrinsic::amdgcn_buffer_atomic_smin: 7126 case Intrinsic::amdgcn_buffer_atomic_umin: 7127 case Intrinsic::amdgcn_buffer_atomic_smax: 7128 case Intrinsic::amdgcn_buffer_atomic_umax: 7129 case Intrinsic::amdgcn_buffer_atomic_and: 7130 case Intrinsic::amdgcn_buffer_atomic_or: 7131 case Intrinsic::amdgcn_buffer_atomic_xor: 7132 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7133 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7134 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7135 SDValue Ops[] = { 7136 Op.getOperand(0), // Chain 7137 Op.getOperand(2), // vdata 7138 Op.getOperand(3), // rsrc 7139 Op.getOperand(4), // vindex 7140 SDValue(), // voffset -- will be set by setBufferOffsets 7141 SDValue(), // soffset -- will be set by setBufferOffsets 7142 SDValue(), // offset -- will be set by setBufferOffsets 7143 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7144 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7145 }; 7146 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7147 7148 EVT VT = Op.getValueType(); 7149 7150 auto *M = cast<MemSDNode>(Op); 7151 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7152 unsigned Opcode = 0; 7153 7154 switch (IntrID) { 7155 case Intrinsic::amdgcn_buffer_atomic_swap: 7156 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7157 break; 7158 case Intrinsic::amdgcn_buffer_atomic_add: 7159 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7160 break; 7161 case Intrinsic::amdgcn_buffer_atomic_sub: 7162 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7163 break; 7164 case Intrinsic::amdgcn_buffer_atomic_csub: 7165 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7166 break; 7167 case Intrinsic::amdgcn_buffer_atomic_smin: 7168 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7169 break; 7170 case Intrinsic::amdgcn_buffer_atomic_umin: 7171 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7172 break; 7173 case Intrinsic::amdgcn_buffer_atomic_smax: 7174 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7175 break; 7176 case Intrinsic::amdgcn_buffer_atomic_umax: 7177 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7178 break; 7179 case Intrinsic::amdgcn_buffer_atomic_and: 7180 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7181 break; 7182 case Intrinsic::amdgcn_buffer_atomic_or: 7183 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7184 break; 7185 case Intrinsic::amdgcn_buffer_atomic_xor: 7186 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7187 break; 7188 case Intrinsic::amdgcn_buffer_atomic_fadd: 7189 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7190 DiagnosticInfoUnsupported 7191 NoFpRet(DAG.getMachineFunction().getFunction(), 7192 "return versions of fp atomics not supported", 7193 DL.getDebugLoc(), DS_Error); 7194 DAG.getContext()->diagnose(NoFpRet); 7195 return SDValue(); 7196 } 7197 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7198 break; 7199 default: 7200 llvm_unreachable("unhandled atomic opcode"); 7201 } 7202 7203 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7204 M->getMemOperand()); 7205 } 7206 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7207 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7208 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7209 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7210 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7211 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7212 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7213 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7214 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7215 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7216 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7217 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7218 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7219 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7220 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7221 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7222 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7223 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7224 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7225 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7226 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7227 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7228 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7229 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7230 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7231 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7232 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7233 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7234 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7235 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7236 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7237 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7238 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7239 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7240 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7241 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7242 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7243 return lowerStructBufferAtomicIntrin(Op, DAG, 7244 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7245 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7246 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7247 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7248 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7249 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7250 return lowerStructBufferAtomicIntrin(Op, DAG, 7251 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7252 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7253 return lowerStructBufferAtomicIntrin(Op, DAG, 7254 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7255 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7256 return lowerStructBufferAtomicIntrin(Op, DAG, 7257 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7258 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7259 return lowerStructBufferAtomicIntrin(Op, DAG, 7260 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7261 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7262 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7263 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7264 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7265 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7266 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7267 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7268 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7269 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7270 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7271 7272 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7273 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7274 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7275 SDValue Ops[] = { 7276 Op.getOperand(0), // Chain 7277 Op.getOperand(2), // src 7278 Op.getOperand(3), // cmp 7279 Op.getOperand(4), // rsrc 7280 Op.getOperand(5), // vindex 7281 SDValue(), // voffset -- will be set by setBufferOffsets 7282 SDValue(), // soffset -- will be set by setBufferOffsets 7283 SDValue(), // offset -- will be set by setBufferOffsets 7284 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7285 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7286 }; 7287 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7288 7289 EVT VT = Op.getValueType(); 7290 auto *M = cast<MemSDNode>(Op); 7291 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7292 7293 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7294 Op->getVTList(), Ops, VT, M->getMemOperand()); 7295 } 7296 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7297 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7298 SDValue Ops[] = { 7299 Op.getOperand(0), // Chain 7300 Op.getOperand(2), // src 7301 Op.getOperand(3), // cmp 7302 Op.getOperand(4), // rsrc 7303 DAG.getConstant(0, DL, MVT::i32), // vindex 7304 Offsets.first, // voffset 7305 Op.getOperand(6), // soffset 7306 Offsets.second, // offset 7307 Op.getOperand(7), // cachepolicy 7308 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7309 }; 7310 EVT VT = Op.getValueType(); 7311 auto *M = cast<MemSDNode>(Op); 7312 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7313 7314 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7315 Op->getVTList(), Ops, VT, M->getMemOperand()); 7316 } 7317 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7318 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7319 SDValue Ops[] = { 7320 Op.getOperand(0), // Chain 7321 Op.getOperand(2), // src 7322 Op.getOperand(3), // cmp 7323 Op.getOperand(4), // rsrc 7324 Op.getOperand(5), // vindex 7325 Offsets.first, // voffset 7326 Op.getOperand(7), // soffset 7327 Offsets.second, // offset 7328 Op.getOperand(8), // cachepolicy 7329 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7330 }; 7331 EVT VT = Op.getValueType(); 7332 auto *M = cast<MemSDNode>(Op); 7333 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7334 7335 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7336 Op->getVTList(), Ops, VT, M->getMemOperand()); 7337 } 7338 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7339 SDLoc DL(Op); 7340 MemSDNode *M = cast<MemSDNode>(Op); 7341 SDValue NodePtr = M->getOperand(2); 7342 SDValue RayExtent = M->getOperand(3); 7343 SDValue RayOrigin = M->getOperand(4); 7344 SDValue RayDir = M->getOperand(5); 7345 SDValue RayInvDir = M->getOperand(6); 7346 SDValue TDescr = M->getOperand(7); 7347 7348 assert(NodePtr.getValueType() == MVT::i32 || 7349 NodePtr.getValueType() == MVT::i64); 7350 assert(RayDir.getValueType() == MVT::v4f16 || 7351 RayDir.getValueType() == MVT::v4f32); 7352 7353 if (!Subtarget->hasGFX10_AEncoding()) { 7354 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7355 return SDValue(); 7356 } 7357 7358 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7359 bool Is64 = NodePtr.getValueType() == MVT::i64; 7360 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7361 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7362 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7363 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7364 7365 SmallVector<SDValue, 16> Ops; 7366 7367 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7368 SmallVector<SDValue, 3> Lanes; 7369 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7370 if (Lanes[0].getValueSizeInBits() == 32) { 7371 for (unsigned I = 0; I < 3; ++I) 7372 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7373 } else { 7374 if (IsAligned) { 7375 Ops.push_back( 7376 DAG.getBitcast(MVT::i32, 7377 DAG.getBuildVector(MVT::v2f16, DL, 7378 { Lanes[0], Lanes[1] }))); 7379 Ops.push_back(Lanes[2]); 7380 } else { 7381 SDValue Elt0 = Ops.pop_back_val(); 7382 Ops.push_back( 7383 DAG.getBitcast(MVT::i32, 7384 DAG.getBuildVector(MVT::v2f16, DL, 7385 { Elt0, Lanes[0] }))); 7386 Ops.push_back( 7387 DAG.getBitcast(MVT::i32, 7388 DAG.getBuildVector(MVT::v2f16, DL, 7389 { Lanes[1], Lanes[2] }))); 7390 } 7391 } 7392 }; 7393 7394 if (Is64) 7395 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7396 else 7397 Ops.push_back(NodePtr); 7398 7399 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7400 packLanes(RayOrigin, true); 7401 packLanes(RayDir, true); 7402 packLanes(RayInvDir, false); 7403 Ops.push_back(TDescr); 7404 if (IsA16) 7405 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7406 Ops.push_back(M->getChain()); 7407 7408 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7409 MachineMemOperand *MemRef = M->getMemOperand(); 7410 DAG.setNodeMemRefs(NewNode, {MemRef}); 7411 return SDValue(NewNode, 0); 7412 } 7413 case Intrinsic::amdgcn_global_atomic_fadd: 7414 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7415 DiagnosticInfoUnsupported 7416 NoFpRet(DAG.getMachineFunction().getFunction(), 7417 "return versions of fp atomics not supported", 7418 DL.getDebugLoc(), DS_Error); 7419 DAG.getContext()->diagnose(NoFpRet); 7420 return SDValue(); 7421 } 7422 LLVM_FALLTHROUGH; 7423 case Intrinsic::amdgcn_global_atomic_fmin: 7424 case Intrinsic::amdgcn_global_atomic_fmax: 7425 case Intrinsic::amdgcn_flat_atomic_fadd: 7426 case Intrinsic::amdgcn_flat_atomic_fmin: 7427 case Intrinsic::amdgcn_flat_atomic_fmax: { 7428 MemSDNode *M = cast<MemSDNode>(Op); 7429 SDValue Ops[] = { 7430 M->getOperand(0), // Chain 7431 M->getOperand(2), // Ptr 7432 M->getOperand(3) // Value 7433 }; 7434 unsigned Opcode = 0; 7435 switch (IntrID) { 7436 case Intrinsic::amdgcn_global_atomic_fadd: 7437 case Intrinsic::amdgcn_flat_atomic_fadd: { 7438 EVT VT = Op.getOperand(3).getValueType(); 7439 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7440 DAG.getVTList(VT, MVT::Other), Ops, 7441 M->getMemOperand()); 7442 } 7443 case Intrinsic::amdgcn_global_atomic_fmin: 7444 case Intrinsic::amdgcn_flat_atomic_fmin: { 7445 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7446 break; 7447 } 7448 case Intrinsic::amdgcn_global_atomic_fmax: 7449 case Intrinsic::amdgcn_flat_atomic_fmax: { 7450 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7451 break; 7452 } 7453 default: 7454 llvm_unreachable("unhandled atomic opcode"); 7455 } 7456 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7457 M->getVTList(), Ops, M->getMemoryVT(), 7458 M->getMemOperand()); 7459 } 7460 default: 7461 7462 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7463 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7464 return lowerImage(Op, ImageDimIntr, DAG, true); 7465 7466 return SDValue(); 7467 } 7468 } 7469 7470 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7471 // dwordx4 if on SI. 7472 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7473 SDVTList VTList, 7474 ArrayRef<SDValue> Ops, EVT MemVT, 7475 MachineMemOperand *MMO, 7476 SelectionDAG &DAG) const { 7477 EVT VT = VTList.VTs[0]; 7478 EVT WidenedVT = VT; 7479 EVT WidenedMemVT = MemVT; 7480 if (!Subtarget->hasDwordx3LoadStores() && 7481 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7482 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7483 WidenedVT.getVectorElementType(), 4); 7484 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7485 WidenedMemVT.getVectorElementType(), 4); 7486 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7487 } 7488 7489 assert(VTList.NumVTs == 2); 7490 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7491 7492 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7493 WidenedMemVT, MMO); 7494 if (WidenedVT != VT) { 7495 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7496 DAG.getVectorIdxConstant(0, DL)); 7497 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7498 } 7499 return NewOp; 7500 } 7501 7502 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7503 bool ImageStore) const { 7504 EVT StoreVT = VData.getValueType(); 7505 7506 // No change for f16 and legal vector D16 types. 7507 if (!StoreVT.isVector()) 7508 return VData; 7509 7510 SDLoc DL(VData); 7511 unsigned NumElements = StoreVT.getVectorNumElements(); 7512 7513 if (Subtarget->hasUnpackedD16VMem()) { 7514 // We need to unpack the packed data to store. 7515 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7516 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7517 7518 EVT EquivStoreVT = 7519 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7520 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7521 return DAG.UnrollVectorOp(ZExt.getNode()); 7522 } 7523 7524 // The sq block of gfx8.1 does not estimate register use correctly for d16 7525 // image store instructions. The data operand is computed as if it were not a 7526 // d16 image instruction. 7527 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7528 // Bitcast to i16 7529 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7530 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7531 7532 // Decompose into scalars 7533 SmallVector<SDValue, 4> Elts; 7534 DAG.ExtractVectorElements(IntVData, Elts); 7535 7536 // Group pairs of i16 into v2i16 and bitcast to i32 7537 SmallVector<SDValue, 4> PackedElts; 7538 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7539 SDValue Pair = 7540 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7541 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7542 PackedElts.push_back(IntPair); 7543 } 7544 if ((NumElements % 2) == 1) { 7545 // Handle v3i16 7546 unsigned I = Elts.size() / 2; 7547 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7548 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7549 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7550 PackedElts.push_back(IntPair); 7551 } 7552 7553 // Pad using UNDEF 7554 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7555 7556 // Build final vector 7557 EVT VecVT = 7558 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7559 return DAG.getBuildVector(VecVT, DL, PackedElts); 7560 } 7561 7562 if (NumElements == 3) { 7563 EVT IntStoreVT = 7564 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7565 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7566 7567 EVT WidenedStoreVT = EVT::getVectorVT( 7568 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7569 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7570 WidenedStoreVT.getStoreSizeInBits()); 7571 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7572 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7573 } 7574 7575 assert(isTypeLegal(StoreVT)); 7576 return VData; 7577 } 7578 7579 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7580 SelectionDAG &DAG) const { 7581 SDLoc DL(Op); 7582 SDValue Chain = Op.getOperand(0); 7583 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7584 MachineFunction &MF = DAG.getMachineFunction(); 7585 7586 switch (IntrinsicID) { 7587 case Intrinsic::amdgcn_exp_compr: { 7588 SDValue Src0 = Op.getOperand(4); 7589 SDValue Src1 = Op.getOperand(5); 7590 // Hack around illegal type on SI by directly selecting it. 7591 if (isTypeLegal(Src0.getValueType())) 7592 return SDValue(); 7593 7594 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7595 SDValue Undef = DAG.getUNDEF(MVT::f32); 7596 const SDValue Ops[] = { 7597 Op.getOperand(2), // tgt 7598 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7599 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7600 Undef, // src2 7601 Undef, // src3 7602 Op.getOperand(7), // vm 7603 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7604 Op.getOperand(3), // en 7605 Op.getOperand(0) // Chain 7606 }; 7607 7608 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7609 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7610 } 7611 case Intrinsic::amdgcn_s_barrier: { 7612 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7613 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7614 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7615 if (WGSize <= ST.getWavefrontSize()) 7616 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7617 Op.getOperand(0)), 0); 7618 } 7619 return SDValue(); 7620 }; 7621 case Intrinsic::amdgcn_tbuffer_store: { 7622 SDValue VData = Op.getOperand(2); 7623 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7624 if (IsD16) 7625 VData = handleD16VData(VData, DAG); 7626 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7627 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7628 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7629 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7630 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7631 SDValue Ops[] = { 7632 Chain, 7633 VData, // vdata 7634 Op.getOperand(3), // rsrc 7635 Op.getOperand(4), // vindex 7636 Op.getOperand(5), // voffset 7637 Op.getOperand(6), // soffset 7638 Op.getOperand(7), // offset 7639 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7640 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7641 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7642 }; 7643 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7644 AMDGPUISD::TBUFFER_STORE_FORMAT; 7645 MemSDNode *M = cast<MemSDNode>(Op); 7646 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7647 M->getMemoryVT(), M->getMemOperand()); 7648 } 7649 7650 case Intrinsic::amdgcn_struct_tbuffer_store: { 7651 SDValue VData = Op.getOperand(2); 7652 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7653 if (IsD16) 7654 VData = handleD16VData(VData, DAG); 7655 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7656 SDValue Ops[] = { 7657 Chain, 7658 VData, // vdata 7659 Op.getOperand(3), // rsrc 7660 Op.getOperand(4), // vindex 7661 Offsets.first, // voffset 7662 Op.getOperand(6), // soffset 7663 Offsets.second, // offset 7664 Op.getOperand(7), // format 7665 Op.getOperand(8), // cachepolicy, swizzled buffer 7666 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7667 }; 7668 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7669 AMDGPUISD::TBUFFER_STORE_FORMAT; 7670 MemSDNode *M = cast<MemSDNode>(Op); 7671 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7672 M->getMemoryVT(), M->getMemOperand()); 7673 } 7674 7675 case Intrinsic::amdgcn_raw_tbuffer_store: { 7676 SDValue VData = Op.getOperand(2); 7677 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7678 if (IsD16) 7679 VData = handleD16VData(VData, DAG); 7680 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7681 SDValue Ops[] = { 7682 Chain, 7683 VData, // vdata 7684 Op.getOperand(3), // rsrc 7685 DAG.getConstant(0, DL, MVT::i32), // vindex 7686 Offsets.first, // voffset 7687 Op.getOperand(5), // soffset 7688 Offsets.second, // offset 7689 Op.getOperand(6), // format 7690 Op.getOperand(7), // cachepolicy, swizzled buffer 7691 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7692 }; 7693 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7694 AMDGPUISD::TBUFFER_STORE_FORMAT; 7695 MemSDNode *M = cast<MemSDNode>(Op); 7696 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7697 M->getMemoryVT(), M->getMemOperand()); 7698 } 7699 7700 case Intrinsic::amdgcn_buffer_store: 7701 case Intrinsic::amdgcn_buffer_store_format: { 7702 SDValue VData = Op.getOperand(2); 7703 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7704 if (IsD16) 7705 VData = handleD16VData(VData, DAG); 7706 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7707 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7708 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7709 SDValue Ops[] = { 7710 Chain, 7711 VData, 7712 Op.getOperand(3), // rsrc 7713 Op.getOperand(4), // vindex 7714 SDValue(), // voffset -- will be set by setBufferOffsets 7715 SDValue(), // soffset -- will be set by setBufferOffsets 7716 SDValue(), // offset -- will be set by setBufferOffsets 7717 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7718 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7719 }; 7720 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7721 7722 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7723 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7724 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7725 MemSDNode *M = cast<MemSDNode>(Op); 7726 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7727 7728 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7729 EVT VDataType = VData.getValueType().getScalarType(); 7730 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7731 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7732 7733 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7734 M->getMemoryVT(), M->getMemOperand()); 7735 } 7736 7737 case Intrinsic::amdgcn_raw_buffer_store: 7738 case Intrinsic::amdgcn_raw_buffer_store_format: { 7739 const bool IsFormat = 7740 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7741 7742 SDValue VData = Op.getOperand(2); 7743 EVT VDataVT = VData.getValueType(); 7744 EVT EltType = VDataVT.getScalarType(); 7745 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7746 if (IsD16) { 7747 VData = handleD16VData(VData, DAG); 7748 VDataVT = VData.getValueType(); 7749 } 7750 7751 if (!isTypeLegal(VDataVT)) { 7752 VData = 7753 DAG.getNode(ISD::BITCAST, DL, 7754 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7755 } 7756 7757 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7758 SDValue Ops[] = { 7759 Chain, 7760 VData, 7761 Op.getOperand(3), // rsrc 7762 DAG.getConstant(0, DL, MVT::i32), // vindex 7763 Offsets.first, // voffset 7764 Op.getOperand(5), // soffset 7765 Offsets.second, // offset 7766 Op.getOperand(6), // cachepolicy, swizzled buffer 7767 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7768 }; 7769 unsigned Opc = 7770 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7771 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7772 MemSDNode *M = cast<MemSDNode>(Op); 7773 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7774 7775 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7776 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7777 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7778 7779 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7780 M->getMemoryVT(), M->getMemOperand()); 7781 } 7782 7783 case Intrinsic::amdgcn_struct_buffer_store: 7784 case Intrinsic::amdgcn_struct_buffer_store_format: { 7785 const bool IsFormat = 7786 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7787 7788 SDValue VData = Op.getOperand(2); 7789 EVT VDataVT = VData.getValueType(); 7790 EVT EltType = VDataVT.getScalarType(); 7791 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7792 7793 if (IsD16) { 7794 VData = handleD16VData(VData, DAG); 7795 VDataVT = VData.getValueType(); 7796 } 7797 7798 if (!isTypeLegal(VDataVT)) { 7799 VData = 7800 DAG.getNode(ISD::BITCAST, DL, 7801 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7802 } 7803 7804 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7805 SDValue Ops[] = { 7806 Chain, 7807 VData, 7808 Op.getOperand(3), // rsrc 7809 Op.getOperand(4), // vindex 7810 Offsets.first, // voffset 7811 Op.getOperand(6), // soffset 7812 Offsets.second, // offset 7813 Op.getOperand(7), // cachepolicy, swizzled buffer 7814 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7815 }; 7816 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7817 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7818 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7819 MemSDNode *M = cast<MemSDNode>(Op); 7820 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7821 7822 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7823 EVT VDataType = VData.getValueType().getScalarType(); 7824 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7825 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7826 7827 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7828 M->getMemoryVT(), M->getMemOperand()); 7829 } 7830 case Intrinsic::amdgcn_end_cf: 7831 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7832 Op->getOperand(2), Chain), 0); 7833 7834 default: { 7835 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7836 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7837 return lowerImage(Op, ImageDimIntr, DAG, true); 7838 7839 return Op; 7840 } 7841 } 7842 } 7843 7844 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7845 // offset (the offset that is included in bounds checking and swizzling, to be 7846 // split between the instruction's voffset and immoffset fields) and soffset 7847 // (the offset that is excluded from bounds checking and swizzling, to go in 7848 // the instruction's soffset field). This function takes the first kind of 7849 // offset and figures out how to split it between voffset and immoffset. 7850 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7851 SDValue Offset, SelectionDAG &DAG) const { 7852 SDLoc DL(Offset); 7853 const unsigned MaxImm = 4095; 7854 SDValue N0 = Offset; 7855 ConstantSDNode *C1 = nullptr; 7856 7857 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7858 N0 = SDValue(); 7859 else if (DAG.isBaseWithConstantOffset(N0)) { 7860 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7861 N0 = N0.getOperand(0); 7862 } 7863 7864 if (C1) { 7865 unsigned ImmOffset = C1->getZExtValue(); 7866 // If the immediate value is too big for the immoffset field, put the value 7867 // and -4096 into the immoffset field so that the value that is copied/added 7868 // for the voffset field is a multiple of 4096, and it stands more chance 7869 // of being CSEd with the copy/add for another similar load/store. 7870 // However, do not do that rounding down to a multiple of 4096 if that is a 7871 // negative number, as it appears to be illegal to have a negative offset 7872 // in the vgpr, even if adding the immediate offset makes it positive. 7873 unsigned Overflow = ImmOffset & ~MaxImm; 7874 ImmOffset -= Overflow; 7875 if ((int32_t)Overflow < 0) { 7876 Overflow += ImmOffset; 7877 ImmOffset = 0; 7878 } 7879 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7880 if (Overflow) { 7881 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7882 if (!N0) 7883 N0 = OverflowVal; 7884 else { 7885 SDValue Ops[] = { N0, OverflowVal }; 7886 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7887 } 7888 } 7889 } 7890 if (!N0) 7891 N0 = DAG.getConstant(0, DL, MVT::i32); 7892 if (!C1) 7893 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7894 return {N0, SDValue(C1, 0)}; 7895 } 7896 7897 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7898 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7899 // pointed to by Offsets. 7900 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7901 SelectionDAG &DAG, SDValue *Offsets, 7902 Align Alignment) const { 7903 SDLoc DL(CombinedOffset); 7904 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7905 uint32_t Imm = C->getZExtValue(); 7906 uint32_t SOffset, ImmOffset; 7907 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7908 Alignment)) { 7909 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7910 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7911 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7912 return; 7913 } 7914 } 7915 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7916 SDValue N0 = CombinedOffset.getOperand(0); 7917 SDValue N1 = CombinedOffset.getOperand(1); 7918 uint32_t SOffset, ImmOffset; 7919 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7920 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7921 Subtarget, Alignment)) { 7922 Offsets[0] = N0; 7923 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7924 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7925 return; 7926 } 7927 } 7928 Offsets[0] = CombinedOffset; 7929 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7930 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7931 } 7932 7933 // Handle 8 bit and 16 bit buffer loads 7934 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7935 EVT LoadVT, SDLoc DL, 7936 ArrayRef<SDValue> Ops, 7937 MemSDNode *M) const { 7938 EVT IntVT = LoadVT.changeTypeToInteger(); 7939 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7940 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7941 7942 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7943 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7944 Ops, IntVT, 7945 M->getMemOperand()); 7946 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7947 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7948 7949 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7950 } 7951 7952 // Handle 8 bit and 16 bit buffer stores 7953 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7954 EVT VDataType, SDLoc DL, 7955 SDValue Ops[], 7956 MemSDNode *M) const { 7957 if (VDataType == MVT::f16) 7958 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7959 7960 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7961 Ops[1] = BufferStoreExt; 7962 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7963 AMDGPUISD::BUFFER_STORE_SHORT; 7964 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7965 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7966 M->getMemOperand()); 7967 } 7968 7969 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7970 ISD::LoadExtType ExtType, SDValue Op, 7971 const SDLoc &SL, EVT VT) { 7972 if (VT.bitsLT(Op.getValueType())) 7973 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7974 7975 switch (ExtType) { 7976 case ISD::SEXTLOAD: 7977 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7978 case ISD::ZEXTLOAD: 7979 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7980 case ISD::EXTLOAD: 7981 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7982 case ISD::NON_EXTLOAD: 7983 return Op; 7984 } 7985 7986 llvm_unreachable("invalid ext type"); 7987 } 7988 7989 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7990 SelectionDAG &DAG = DCI.DAG; 7991 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7992 return SDValue(); 7993 7994 // FIXME: Constant loads should all be marked invariant. 7995 unsigned AS = Ld->getAddressSpace(); 7996 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7997 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7998 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7999 return SDValue(); 8000 8001 // Don't do this early, since it may interfere with adjacent load merging for 8002 // illegal types. We can avoid losing alignment information for exotic types 8003 // pre-legalize. 8004 EVT MemVT = Ld->getMemoryVT(); 8005 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8006 MemVT.getSizeInBits() >= 32) 8007 return SDValue(); 8008 8009 SDLoc SL(Ld); 8010 8011 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8012 "unexpected vector extload"); 8013 8014 // TODO: Drop only high part of range. 8015 SDValue Ptr = Ld->getBasePtr(); 8016 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8017 MVT::i32, SL, Ld->getChain(), Ptr, 8018 Ld->getOffset(), 8019 Ld->getPointerInfo(), MVT::i32, 8020 Ld->getAlignment(), 8021 Ld->getMemOperand()->getFlags(), 8022 Ld->getAAInfo(), 8023 nullptr); // Drop ranges 8024 8025 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8026 if (MemVT.isFloatingPoint()) { 8027 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8028 "unexpected fp extload"); 8029 TruncVT = MemVT.changeTypeToInteger(); 8030 } 8031 8032 SDValue Cvt = NewLoad; 8033 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8034 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8035 DAG.getValueType(TruncVT)); 8036 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8037 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8038 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8039 } else { 8040 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8041 } 8042 8043 EVT VT = Ld->getValueType(0); 8044 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8045 8046 DCI.AddToWorklist(Cvt.getNode()); 8047 8048 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8049 // the appropriate extension from the 32-bit load. 8050 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8051 DCI.AddToWorklist(Cvt.getNode()); 8052 8053 // Handle conversion back to floating point if necessary. 8054 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8055 8056 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8057 } 8058 8059 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8060 SDLoc DL(Op); 8061 LoadSDNode *Load = cast<LoadSDNode>(Op); 8062 ISD::LoadExtType ExtType = Load->getExtensionType(); 8063 EVT MemVT = Load->getMemoryVT(); 8064 8065 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8066 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8067 return SDValue(); 8068 8069 // FIXME: Copied from PPC 8070 // First, load into 32 bits, then truncate to 1 bit. 8071 8072 SDValue Chain = Load->getChain(); 8073 SDValue BasePtr = Load->getBasePtr(); 8074 MachineMemOperand *MMO = Load->getMemOperand(); 8075 8076 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8077 8078 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8079 BasePtr, RealMemVT, MMO); 8080 8081 if (!MemVT.isVector()) { 8082 SDValue Ops[] = { 8083 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8084 NewLD.getValue(1) 8085 }; 8086 8087 return DAG.getMergeValues(Ops, DL); 8088 } 8089 8090 SmallVector<SDValue, 3> Elts; 8091 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8092 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8093 DAG.getConstant(I, DL, MVT::i32)); 8094 8095 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8096 } 8097 8098 SDValue Ops[] = { 8099 DAG.getBuildVector(MemVT, DL, Elts), 8100 NewLD.getValue(1) 8101 }; 8102 8103 return DAG.getMergeValues(Ops, DL); 8104 } 8105 8106 if (!MemVT.isVector()) 8107 return SDValue(); 8108 8109 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8110 "Custom lowering for non-i32 vectors hasn't been implemented."); 8111 8112 unsigned Alignment = Load->getAlignment(); 8113 unsigned AS = Load->getAddressSpace(); 8114 if (Subtarget->hasLDSMisalignedBug() && 8115 AS == AMDGPUAS::FLAT_ADDRESS && 8116 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8117 return SplitVectorLoad(Op, DAG); 8118 } 8119 8120 MachineFunction &MF = DAG.getMachineFunction(); 8121 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8122 // If there is a possibilty that flat instruction access scratch memory 8123 // then we need to use the same legalization rules we use for private. 8124 if (AS == AMDGPUAS::FLAT_ADDRESS && 8125 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8126 AS = MFI->hasFlatScratchInit() ? 8127 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8128 8129 unsigned NumElements = MemVT.getVectorNumElements(); 8130 8131 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8132 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8133 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8134 if (MemVT.isPow2VectorType()) 8135 return SDValue(); 8136 return WidenOrSplitVectorLoad(Op, DAG); 8137 } 8138 // Non-uniform loads will be selected to MUBUF instructions, so they 8139 // have the same legalization requirements as global and private 8140 // loads. 8141 // 8142 } 8143 8144 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8145 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8146 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8147 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8148 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8149 Alignment >= 4 && NumElements < 32) { 8150 if (MemVT.isPow2VectorType()) 8151 return SDValue(); 8152 return WidenOrSplitVectorLoad(Op, DAG); 8153 } 8154 // Non-uniform loads will be selected to MUBUF instructions, so they 8155 // have the same legalization requirements as global and private 8156 // loads. 8157 // 8158 } 8159 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8160 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8161 AS == AMDGPUAS::GLOBAL_ADDRESS || 8162 AS == AMDGPUAS::FLAT_ADDRESS) { 8163 if (NumElements > 4) 8164 return SplitVectorLoad(Op, DAG); 8165 // v3 loads not supported on SI. 8166 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8167 return WidenOrSplitVectorLoad(Op, DAG); 8168 8169 // v3 and v4 loads are supported for private and global memory. 8170 return SDValue(); 8171 } 8172 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8173 // Depending on the setting of the private_element_size field in the 8174 // resource descriptor, we can only make private accesses up to a certain 8175 // size. 8176 switch (Subtarget->getMaxPrivateElementSize()) { 8177 case 4: { 8178 SDValue Ops[2]; 8179 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8180 return DAG.getMergeValues(Ops, DL); 8181 } 8182 case 8: 8183 if (NumElements > 2) 8184 return SplitVectorLoad(Op, DAG); 8185 return SDValue(); 8186 case 16: 8187 // Same as global/flat 8188 if (NumElements > 4) 8189 return SplitVectorLoad(Op, DAG); 8190 // v3 loads not supported on SI. 8191 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8192 return WidenOrSplitVectorLoad(Op, DAG); 8193 8194 return SDValue(); 8195 default: 8196 llvm_unreachable("unsupported private_element_size"); 8197 } 8198 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8199 // Use ds_read_b128 or ds_read_b96 when possible. 8200 if (Subtarget->hasDS96AndDS128() && 8201 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8202 MemVT.getStoreSize() == 12) && 8203 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8204 Load->getAlign())) 8205 return SDValue(); 8206 8207 if (NumElements > 2) 8208 return SplitVectorLoad(Op, DAG); 8209 8210 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8211 // address is negative, then the instruction is incorrectly treated as 8212 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8213 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8214 // load later in the SILoadStoreOptimizer. 8215 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8216 NumElements == 2 && MemVT.getStoreSize() == 8 && 8217 Load->getAlignment() < 8) { 8218 return SplitVectorLoad(Op, DAG); 8219 } 8220 } 8221 8222 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8223 MemVT, *Load->getMemOperand())) { 8224 SDValue Ops[2]; 8225 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8226 return DAG.getMergeValues(Ops, DL); 8227 } 8228 8229 return SDValue(); 8230 } 8231 8232 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8233 EVT VT = Op.getValueType(); 8234 assert(VT.getSizeInBits() == 64); 8235 8236 SDLoc DL(Op); 8237 SDValue Cond = Op.getOperand(0); 8238 8239 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8240 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8241 8242 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8243 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8244 8245 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8246 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8247 8248 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8249 8250 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8251 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8252 8253 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8254 8255 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8256 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8257 } 8258 8259 // Catch division cases where we can use shortcuts with rcp and rsq 8260 // instructions. 8261 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8262 SelectionDAG &DAG) const { 8263 SDLoc SL(Op); 8264 SDValue LHS = Op.getOperand(0); 8265 SDValue RHS = Op.getOperand(1); 8266 EVT VT = Op.getValueType(); 8267 const SDNodeFlags Flags = Op->getFlags(); 8268 8269 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8270 8271 // Without !fpmath accuracy information, we can't do more because we don't 8272 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8273 if (!AllowInaccurateRcp) 8274 return SDValue(); 8275 8276 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8277 if (CLHS->isExactlyValue(1.0)) { 8278 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8279 // the CI documentation has a worst case error of 1 ulp. 8280 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8281 // use it as long as we aren't trying to use denormals. 8282 // 8283 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8284 8285 // 1.0 / sqrt(x) -> rsq(x) 8286 8287 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8288 // error seems really high at 2^29 ULP. 8289 if (RHS.getOpcode() == ISD::FSQRT) 8290 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8291 8292 // 1.0 / x -> rcp(x) 8293 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8294 } 8295 8296 // Same as for 1.0, but expand the sign out of the constant. 8297 if (CLHS->isExactlyValue(-1.0)) { 8298 // -1.0 / x -> rcp (fneg x) 8299 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8300 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8301 } 8302 } 8303 8304 // Turn into multiply by the reciprocal. 8305 // x / y -> x * (1.0 / y) 8306 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8307 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8308 } 8309 8310 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8311 SelectionDAG &DAG) const { 8312 SDLoc SL(Op); 8313 SDValue X = Op.getOperand(0); 8314 SDValue Y = Op.getOperand(1); 8315 EVT VT = Op.getValueType(); 8316 const SDNodeFlags Flags = Op->getFlags(); 8317 8318 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8319 DAG.getTarget().Options.UnsafeFPMath; 8320 if (!AllowInaccurateDiv) 8321 return SDValue(); 8322 8323 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8324 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8325 8326 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8327 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8328 8329 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8330 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8331 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8332 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8333 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8334 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8335 } 8336 8337 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8338 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8339 SDNodeFlags Flags) { 8340 if (GlueChain->getNumValues() <= 1) { 8341 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8342 } 8343 8344 assert(GlueChain->getNumValues() == 3); 8345 8346 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8347 switch (Opcode) { 8348 default: llvm_unreachable("no chain equivalent for opcode"); 8349 case ISD::FMUL: 8350 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8351 break; 8352 } 8353 8354 return DAG.getNode(Opcode, SL, VTList, 8355 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8356 Flags); 8357 } 8358 8359 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8360 EVT VT, SDValue A, SDValue B, SDValue C, 8361 SDValue GlueChain, SDNodeFlags Flags) { 8362 if (GlueChain->getNumValues() <= 1) { 8363 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8364 } 8365 8366 assert(GlueChain->getNumValues() == 3); 8367 8368 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8369 switch (Opcode) { 8370 default: llvm_unreachable("no chain equivalent for opcode"); 8371 case ISD::FMA: 8372 Opcode = AMDGPUISD::FMA_W_CHAIN; 8373 break; 8374 } 8375 8376 return DAG.getNode(Opcode, SL, VTList, 8377 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8378 Flags); 8379 } 8380 8381 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8382 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8383 return FastLowered; 8384 8385 SDLoc SL(Op); 8386 SDValue Src0 = Op.getOperand(0); 8387 SDValue Src1 = Op.getOperand(1); 8388 8389 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8390 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8391 8392 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8393 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8394 8395 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8396 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8397 8398 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8399 } 8400 8401 // Faster 2.5 ULP division that does not support denormals. 8402 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8403 SDLoc SL(Op); 8404 SDValue LHS = Op.getOperand(1); 8405 SDValue RHS = Op.getOperand(2); 8406 8407 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8408 8409 const APFloat K0Val(BitsToFloat(0x6f800000)); 8410 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8411 8412 const APFloat K1Val(BitsToFloat(0x2f800000)); 8413 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8414 8415 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8416 8417 EVT SetCCVT = 8418 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8419 8420 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8421 8422 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8423 8424 // TODO: Should this propagate fast-math-flags? 8425 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8426 8427 // rcp does not support denormals. 8428 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8429 8430 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8431 8432 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8433 } 8434 8435 // Returns immediate value for setting the F32 denorm mode when using the 8436 // S_DENORM_MODE instruction. 8437 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8438 const SDLoc &SL, const GCNSubtarget *ST) { 8439 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8440 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8441 ? FP_DENORM_FLUSH_NONE 8442 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8443 8444 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8445 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8446 } 8447 8448 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8449 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8450 return FastLowered; 8451 8452 // The selection matcher assumes anything with a chain selecting to a 8453 // mayRaiseFPException machine instruction. Since we're introducing a chain 8454 // here, we need to explicitly report nofpexcept for the regular fdiv 8455 // lowering. 8456 SDNodeFlags Flags = Op->getFlags(); 8457 Flags.setNoFPExcept(true); 8458 8459 SDLoc SL(Op); 8460 SDValue LHS = Op.getOperand(0); 8461 SDValue RHS = Op.getOperand(1); 8462 8463 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8464 8465 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8466 8467 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8468 {RHS, RHS, LHS}, Flags); 8469 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8470 {LHS, RHS, LHS}, Flags); 8471 8472 // Denominator is scaled to not be denormal, so using rcp is ok. 8473 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8474 DenominatorScaled, Flags); 8475 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8476 DenominatorScaled, Flags); 8477 8478 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8479 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8480 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8481 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8482 8483 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8484 8485 if (!HasFP32Denormals) { 8486 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8487 // lowering. The chain dependence is insufficient, and we need glue. We do 8488 // not need the glue variants in a strictfp function. 8489 8490 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8491 8492 SDNode *EnableDenorm; 8493 if (Subtarget->hasDenormModeInst()) { 8494 const SDValue EnableDenormValue = 8495 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8496 8497 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8498 DAG.getEntryNode(), EnableDenormValue).getNode(); 8499 } else { 8500 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8501 SL, MVT::i32); 8502 EnableDenorm = 8503 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8504 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8505 } 8506 8507 SDValue Ops[3] = { 8508 NegDivScale0, 8509 SDValue(EnableDenorm, 0), 8510 SDValue(EnableDenorm, 1) 8511 }; 8512 8513 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8514 } 8515 8516 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8517 ApproxRcp, One, NegDivScale0, Flags); 8518 8519 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8520 ApproxRcp, Fma0, Flags); 8521 8522 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8523 Fma1, Fma1, Flags); 8524 8525 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8526 NumeratorScaled, Mul, Flags); 8527 8528 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8529 Fma2, Fma1, Mul, Fma2, Flags); 8530 8531 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8532 NumeratorScaled, Fma3, Flags); 8533 8534 if (!HasFP32Denormals) { 8535 SDNode *DisableDenorm; 8536 if (Subtarget->hasDenormModeInst()) { 8537 const SDValue DisableDenormValue = 8538 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8539 8540 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8541 Fma4.getValue(1), DisableDenormValue, 8542 Fma4.getValue(2)).getNode(); 8543 } else { 8544 const SDValue DisableDenormValue = 8545 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8546 8547 DisableDenorm = DAG.getMachineNode( 8548 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8549 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8550 } 8551 8552 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8553 SDValue(DisableDenorm, 0), DAG.getRoot()); 8554 DAG.setRoot(OutputChain); 8555 } 8556 8557 SDValue Scale = NumeratorScaled.getValue(1); 8558 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8559 {Fma4, Fma1, Fma3, Scale}, Flags); 8560 8561 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8562 } 8563 8564 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8565 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8566 return FastLowered; 8567 8568 SDLoc SL(Op); 8569 SDValue X = Op.getOperand(0); 8570 SDValue Y = Op.getOperand(1); 8571 8572 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8573 8574 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8575 8576 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8577 8578 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8579 8580 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8581 8582 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8583 8584 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8585 8586 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8587 8588 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8589 8590 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8591 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8592 8593 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8594 NegDivScale0, Mul, DivScale1); 8595 8596 SDValue Scale; 8597 8598 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8599 // Workaround a hardware bug on SI where the condition output from div_scale 8600 // is not usable. 8601 8602 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8603 8604 // Figure out if the scale to use for div_fmas. 8605 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8606 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8607 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8608 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8609 8610 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8611 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8612 8613 SDValue Scale0Hi 8614 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8615 SDValue Scale1Hi 8616 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8617 8618 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8619 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8620 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8621 } else { 8622 Scale = DivScale1.getValue(1); 8623 } 8624 8625 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8626 Fma4, Fma3, Mul, Scale); 8627 8628 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8629 } 8630 8631 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8632 EVT VT = Op.getValueType(); 8633 8634 if (VT == MVT::f32) 8635 return LowerFDIV32(Op, DAG); 8636 8637 if (VT == MVT::f64) 8638 return LowerFDIV64(Op, DAG); 8639 8640 if (VT == MVT::f16) 8641 return LowerFDIV16(Op, DAG); 8642 8643 llvm_unreachable("Unexpected type for fdiv"); 8644 } 8645 8646 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8647 SDLoc DL(Op); 8648 StoreSDNode *Store = cast<StoreSDNode>(Op); 8649 EVT VT = Store->getMemoryVT(); 8650 8651 if (VT == MVT::i1) { 8652 return DAG.getTruncStore(Store->getChain(), DL, 8653 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8654 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8655 } 8656 8657 assert(VT.isVector() && 8658 Store->getValue().getValueType().getScalarType() == MVT::i32); 8659 8660 unsigned AS = Store->getAddressSpace(); 8661 if (Subtarget->hasLDSMisalignedBug() && 8662 AS == AMDGPUAS::FLAT_ADDRESS && 8663 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8664 return SplitVectorStore(Op, DAG); 8665 } 8666 8667 MachineFunction &MF = DAG.getMachineFunction(); 8668 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8669 // If there is a possibilty that flat instruction access scratch memory 8670 // then we need to use the same legalization rules we use for private. 8671 if (AS == AMDGPUAS::FLAT_ADDRESS && 8672 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8673 AS = MFI->hasFlatScratchInit() ? 8674 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8675 8676 unsigned NumElements = VT.getVectorNumElements(); 8677 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8678 AS == AMDGPUAS::FLAT_ADDRESS) { 8679 if (NumElements > 4) 8680 return SplitVectorStore(Op, DAG); 8681 // v3 stores not supported on SI. 8682 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8683 return SplitVectorStore(Op, DAG); 8684 8685 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8686 VT, *Store->getMemOperand())) 8687 return expandUnalignedStore(Store, DAG); 8688 8689 return SDValue(); 8690 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8691 switch (Subtarget->getMaxPrivateElementSize()) { 8692 case 4: 8693 return scalarizeVectorStore(Store, DAG); 8694 case 8: 8695 if (NumElements > 2) 8696 return SplitVectorStore(Op, DAG); 8697 return SDValue(); 8698 case 16: 8699 if (NumElements > 4 || 8700 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8701 return SplitVectorStore(Op, DAG); 8702 return SDValue(); 8703 default: 8704 llvm_unreachable("unsupported private_element_size"); 8705 } 8706 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8707 // Use ds_write_b128 or ds_write_b96 when possible. 8708 if (Subtarget->hasDS96AndDS128() && 8709 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8710 (VT.getStoreSize() == 12)) && 8711 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8712 Store->getAlign())) 8713 return SDValue(); 8714 8715 if (NumElements > 2) 8716 return SplitVectorStore(Op, DAG); 8717 8718 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8719 // address is negative, then the instruction is incorrectly treated as 8720 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8721 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8722 // store later in the SILoadStoreOptimizer. 8723 if (!Subtarget->hasUsableDSOffset() && 8724 NumElements == 2 && VT.getStoreSize() == 8 && 8725 Store->getAlignment() < 8) { 8726 return SplitVectorStore(Op, DAG); 8727 } 8728 8729 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8730 VT, *Store->getMemOperand())) { 8731 if (VT.isVector()) 8732 return SplitVectorStore(Op, DAG); 8733 return expandUnalignedStore(Store, DAG); 8734 } 8735 8736 return SDValue(); 8737 } else { 8738 llvm_unreachable("unhandled address space"); 8739 } 8740 } 8741 8742 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8743 SDLoc DL(Op); 8744 EVT VT = Op.getValueType(); 8745 SDValue Arg = Op.getOperand(0); 8746 SDValue TrigVal; 8747 8748 // Propagate fast-math flags so that the multiply we introduce can be folded 8749 // if Arg is already the result of a multiply by constant. 8750 auto Flags = Op->getFlags(); 8751 8752 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8753 8754 if (Subtarget->hasTrigReducedRange()) { 8755 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8756 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8757 } else { 8758 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8759 } 8760 8761 switch (Op.getOpcode()) { 8762 case ISD::FCOS: 8763 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8764 case ISD::FSIN: 8765 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8766 default: 8767 llvm_unreachable("Wrong trig opcode"); 8768 } 8769 } 8770 8771 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8772 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8773 assert(AtomicNode->isCompareAndSwap()); 8774 unsigned AS = AtomicNode->getAddressSpace(); 8775 8776 // No custom lowering required for local address space 8777 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8778 return Op; 8779 8780 // Non-local address space requires custom lowering for atomic compare 8781 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8782 SDLoc DL(Op); 8783 SDValue ChainIn = Op.getOperand(0); 8784 SDValue Addr = Op.getOperand(1); 8785 SDValue Old = Op.getOperand(2); 8786 SDValue New = Op.getOperand(3); 8787 EVT VT = Op.getValueType(); 8788 MVT SimpleVT = VT.getSimpleVT(); 8789 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8790 8791 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8792 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8793 8794 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8795 Ops, VT, AtomicNode->getMemOperand()); 8796 } 8797 8798 //===----------------------------------------------------------------------===// 8799 // Custom DAG optimizations 8800 //===----------------------------------------------------------------------===// 8801 8802 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8803 DAGCombinerInfo &DCI) const { 8804 EVT VT = N->getValueType(0); 8805 EVT ScalarVT = VT.getScalarType(); 8806 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8807 return SDValue(); 8808 8809 SelectionDAG &DAG = DCI.DAG; 8810 SDLoc DL(N); 8811 8812 SDValue Src = N->getOperand(0); 8813 EVT SrcVT = Src.getValueType(); 8814 8815 // TODO: We could try to match extracting the higher bytes, which would be 8816 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8817 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8818 // about in practice. 8819 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8820 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8821 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8822 DCI.AddToWorklist(Cvt.getNode()); 8823 8824 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8825 if (ScalarVT != MVT::f32) { 8826 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8827 DAG.getTargetConstant(0, DL, MVT::i32)); 8828 } 8829 return Cvt; 8830 } 8831 } 8832 8833 return SDValue(); 8834 } 8835 8836 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8837 8838 // This is a variant of 8839 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8840 // 8841 // The normal DAG combiner will do this, but only if the add has one use since 8842 // that would increase the number of instructions. 8843 // 8844 // This prevents us from seeing a constant offset that can be folded into a 8845 // memory instruction's addressing mode. If we know the resulting add offset of 8846 // a pointer can be folded into an addressing offset, we can replace the pointer 8847 // operand with the add of new constant offset. This eliminates one of the uses, 8848 // and may allow the remaining use to also be simplified. 8849 // 8850 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8851 unsigned AddrSpace, 8852 EVT MemVT, 8853 DAGCombinerInfo &DCI) const { 8854 SDValue N0 = N->getOperand(0); 8855 SDValue N1 = N->getOperand(1); 8856 8857 // We only do this to handle cases where it's profitable when there are 8858 // multiple uses of the add, so defer to the standard combine. 8859 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8860 N0->hasOneUse()) 8861 return SDValue(); 8862 8863 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8864 if (!CN1) 8865 return SDValue(); 8866 8867 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8868 if (!CAdd) 8869 return SDValue(); 8870 8871 // If the resulting offset is too large, we can't fold it into the addressing 8872 // mode offset. 8873 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8874 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8875 8876 AddrMode AM; 8877 AM.HasBaseReg = true; 8878 AM.BaseOffs = Offset.getSExtValue(); 8879 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8880 return SDValue(); 8881 8882 SelectionDAG &DAG = DCI.DAG; 8883 SDLoc SL(N); 8884 EVT VT = N->getValueType(0); 8885 8886 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8887 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8888 8889 SDNodeFlags Flags; 8890 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8891 (N0.getOpcode() == ISD::OR || 8892 N0->getFlags().hasNoUnsignedWrap())); 8893 8894 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8895 } 8896 8897 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8898 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8899 /// specific intrinsic, but they all place the pointer operand first. 8900 static unsigned getBasePtrIndex(const MemSDNode *N) { 8901 switch (N->getOpcode()) { 8902 case ISD::STORE: 8903 case ISD::INTRINSIC_W_CHAIN: 8904 case ISD::INTRINSIC_VOID: 8905 return 2; 8906 default: 8907 return 1; 8908 } 8909 } 8910 8911 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8912 DAGCombinerInfo &DCI) const { 8913 SelectionDAG &DAG = DCI.DAG; 8914 SDLoc SL(N); 8915 8916 unsigned PtrIdx = getBasePtrIndex(N); 8917 SDValue Ptr = N->getOperand(PtrIdx); 8918 8919 // TODO: We could also do this for multiplies. 8920 if (Ptr.getOpcode() == ISD::SHL) { 8921 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8922 N->getMemoryVT(), DCI); 8923 if (NewPtr) { 8924 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8925 8926 NewOps[PtrIdx] = NewPtr; 8927 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8928 } 8929 } 8930 8931 return SDValue(); 8932 } 8933 8934 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8935 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8936 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8937 (Opc == ISD::XOR && Val == 0); 8938 } 8939 8940 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8941 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8942 // integer combine opportunities since most 64-bit operations are decomposed 8943 // this way. TODO: We won't want this for SALU especially if it is an inline 8944 // immediate. 8945 SDValue SITargetLowering::splitBinaryBitConstantOp( 8946 DAGCombinerInfo &DCI, 8947 const SDLoc &SL, 8948 unsigned Opc, SDValue LHS, 8949 const ConstantSDNode *CRHS) const { 8950 uint64_t Val = CRHS->getZExtValue(); 8951 uint32_t ValLo = Lo_32(Val); 8952 uint32_t ValHi = Hi_32(Val); 8953 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8954 8955 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8956 bitOpWithConstantIsReducible(Opc, ValHi)) || 8957 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8958 // If we need to materialize a 64-bit immediate, it will be split up later 8959 // anyway. Avoid creating the harder to understand 64-bit immediate 8960 // materialization. 8961 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8962 } 8963 8964 return SDValue(); 8965 } 8966 8967 // Returns true if argument is a boolean value which is not serialized into 8968 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8969 static bool isBoolSGPR(SDValue V) { 8970 if (V.getValueType() != MVT::i1) 8971 return false; 8972 switch (V.getOpcode()) { 8973 default: 8974 break; 8975 case ISD::SETCC: 8976 case AMDGPUISD::FP_CLASS: 8977 return true; 8978 case ISD::AND: 8979 case ISD::OR: 8980 case ISD::XOR: 8981 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8982 } 8983 return false; 8984 } 8985 8986 // If a constant has all zeroes or all ones within each byte return it. 8987 // Otherwise return 0. 8988 static uint32_t getConstantPermuteMask(uint32_t C) { 8989 // 0xff for any zero byte in the mask 8990 uint32_t ZeroByteMask = 0; 8991 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8992 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8993 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8994 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8995 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8996 if ((NonZeroByteMask & C) != NonZeroByteMask) 8997 return 0; // Partial bytes selected. 8998 return C; 8999 } 9000 9001 // Check if a node selects whole bytes from its operand 0 starting at a byte 9002 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9003 // or -1 if not succeeded. 9004 // Note byte select encoding: 9005 // value 0-3 selects corresponding source byte; 9006 // value 0xc selects zero; 9007 // value 0xff selects 0xff. 9008 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9009 assert(V.getValueSizeInBits() == 32); 9010 9011 if (V.getNumOperands() != 2) 9012 return ~0; 9013 9014 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9015 if (!N1) 9016 return ~0; 9017 9018 uint32_t C = N1->getZExtValue(); 9019 9020 switch (V.getOpcode()) { 9021 default: 9022 break; 9023 case ISD::AND: 9024 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9025 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9026 } 9027 break; 9028 9029 case ISD::OR: 9030 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9031 return (0x03020100 & ~ConstMask) | ConstMask; 9032 } 9033 break; 9034 9035 case ISD::SHL: 9036 if (C % 8) 9037 return ~0; 9038 9039 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9040 9041 case ISD::SRL: 9042 if (C % 8) 9043 return ~0; 9044 9045 return uint32_t(0x0c0c0c0c03020100ull >> C); 9046 } 9047 9048 return ~0; 9049 } 9050 9051 SDValue SITargetLowering::performAndCombine(SDNode *N, 9052 DAGCombinerInfo &DCI) const { 9053 if (DCI.isBeforeLegalize()) 9054 return SDValue(); 9055 9056 SelectionDAG &DAG = DCI.DAG; 9057 EVT VT = N->getValueType(0); 9058 SDValue LHS = N->getOperand(0); 9059 SDValue RHS = N->getOperand(1); 9060 9061 9062 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9063 if (VT == MVT::i64 && CRHS) { 9064 if (SDValue Split 9065 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9066 return Split; 9067 } 9068 9069 if (CRHS && VT == MVT::i32) { 9070 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9071 // nb = number of trailing zeroes in mask 9072 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9073 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9074 uint64_t Mask = CRHS->getZExtValue(); 9075 unsigned Bits = countPopulation(Mask); 9076 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9077 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9078 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9079 unsigned Shift = CShift->getZExtValue(); 9080 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9081 unsigned Offset = NB + Shift; 9082 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9083 SDLoc SL(N); 9084 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9085 LHS->getOperand(0), 9086 DAG.getConstant(Offset, SL, MVT::i32), 9087 DAG.getConstant(Bits, SL, MVT::i32)); 9088 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9089 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9090 DAG.getValueType(NarrowVT)); 9091 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9092 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9093 return Shl; 9094 } 9095 } 9096 } 9097 9098 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9099 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9100 isa<ConstantSDNode>(LHS.getOperand(2))) { 9101 uint32_t Sel = getConstantPermuteMask(Mask); 9102 if (!Sel) 9103 return SDValue(); 9104 9105 // Select 0xc for all zero bytes 9106 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9107 SDLoc DL(N); 9108 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9109 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9110 } 9111 } 9112 9113 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9114 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9115 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9116 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9117 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9118 9119 SDValue X = LHS.getOperand(0); 9120 SDValue Y = RHS.getOperand(0); 9121 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9122 return SDValue(); 9123 9124 if (LCC == ISD::SETO) { 9125 if (X != LHS.getOperand(1)) 9126 return SDValue(); 9127 9128 if (RCC == ISD::SETUNE) { 9129 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9130 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9131 return SDValue(); 9132 9133 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9134 SIInstrFlags::N_SUBNORMAL | 9135 SIInstrFlags::N_ZERO | 9136 SIInstrFlags::P_ZERO | 9137 SIInstrFlags::P_SUBNORMAL | 9138 SIInstrFlags::P_NORMAL; 9139 9140 static_assert(((~(SIInstrFlags::S_NAN | 9141 SIInstrFlags::Q_NAN | 9142 SIInstrFlags::N_INFINITY | 9143 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9144 "mask not equal"); 9145 9146 SDLoc DL(N); 9147 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9148 X, DAG.getConstant(Mask, DL, MVT::i32)); 9149 } 9150 } 9151 } 9152 9153 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9154 std::swap(LHS, RHS); 9155 9156 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9157 RHS.hasOneUse()) { 9158 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9159 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9160 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9161 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9162 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9163 (RHS.getOperand(0) == LHS.getOperand(0) && 9164 LHS.getOperand(0) == LHS.getOperand(1))) { 9165 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9166 unsigned NewMask = LCC == ISD::SETO ? 9167 Mask->getZExtValue() & ~OrdMask : 9168 Mask->getZExtValue() & OrdMask; 9169 9170 SDLoc DL(N); 9171 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9172 DAG.getConstant(NewMask, DL, MVT::i32)); 9173 } 9174 } 9175 9176 if (VT == MVT::i32 && 9177 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9178 // and x, (sext cc from i1) => select cc, x, 0 9179 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9180 std::swap(LHS, RHS); 9181 if (isBoolSGPR(RHS.getOperand(0))) 9182 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9183 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9184 } 9185 9186 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9187 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9188 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9189 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9190 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9191 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9192 if (LHSMask != ~0u && RHSMask != ~0u) { 9193 // Canonicalize the expression in an attempt to have fewer unique masks 9194 // and therefore fewer registers used to hold the masks. 9195 if (LHSMask > RHSMask) { 9196 std::swap(LHSMask, RHSMask); 9197 std::swap(LHS, RHS); 9198 } 9199 9200 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9201 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9202 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9203 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9204 9205 // Check of we need to combine values from two sources within a byte. 9206 if (!(LHSUsedLanes & RHSUsedLanes) && 9207 // If we select high and lower word keep it for SDWA. 9208 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9209 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9210 // Each byte in each mask is either selector mask 0-3, or has higher 9211 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9212 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9213 // mask which is not 0xff wins. By anding both masks we have a correct 9214 // result except that 0x0c shall be corrected to give 0x0c only. 9215 uint32_t Mask = LHSMask & RHSMask; 9216 for (unsigned I = 0; I < 32; I += 8) { 9217 uint32_t ByteSel = 0xff << I; 9218 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9219 Mask &= (0x0c << I) & 0xffffffff; 9220 } 9221 9222 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9223 // or 0x0c. 9224 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9225 SDLoc DL(N); 9226 9227 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9228 LHS.getOperand(0), RHS.getOperand(0), 9229 DAG.getConstant(Sel, DL, MVT::i32)); 9230 } 9231 } 9232 } 9233 9234 return SDValue(); 9235 } 9236 9237 SDValue SITargetLowering::performOrCombine(SDNode *N, 9238 DAGCombinerInfo &DCI) const { 9239 SelectionDAG &DAG = DCI.DAG; 9240 SDValue LHS = N->getOperand(0); 9241 SDValue RHS = N->getOperand(1); 9242 9243 EVT VT = N->getValueType(0); 9244 if (VT == MVT::i1) { 9245 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9246 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9247 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9248 SDValue Src = LHS.getOperand(0); 9249 if (Src != RHS.getOperand(0)) 9250 return SDValue(); 9251 9252 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9253 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9254 if (!CLHS || !CRHS) 9255 return SDValue(); 9256 9257 // Only 10 bits are used. 9258 static const uint32_t MaxMask = 0x3ff; 9259 9260 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9261 SDLoc DL(N); 9262 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9263 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9264 } 9265 9266 return SDValue(); 9267 } 9268 9269 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9270 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9271 LHS.getOpcode() == AMDGPUISD::PERM && 9272 isa<ConstantSDNode>(LHS.getOperand(2))) { 9273 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9274 if (!Sel) 9275 return SDValue(); 9276 9277 Sel |= LHS.getConstantOperandVal(2); 9278 SDLoc DL(N); 9279 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9280 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9281 } 9282 9283 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9284 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9285 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9286 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9287 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9288 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9289 if (LHSMask != ~0u && RHSMask != ~0u) { 9290 // Canonicalize the expression in an attempt to have fewer unique masks 9291 // and therefore fewer registers used to hold the masks. 9292 if (LHSMask > RHSMask) { 9293 std::swap(LHSMask, RHSMask); 9294 std::swap(LHS, RHS); 9295 } 9296 9297 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9298 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9299 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9300 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9301 9302 // Check of we need to combine values from two sources within a byte. 9303 if (!(LHSUsedLanes & RHSUsedLanes) && 9304 // If we select high and lower word keep it for SDWA. 9305 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9306 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9307 // Kill zero bytes selected by other mask. Zero value is 0xc. 9308 LHSMask &= ~RHSUsedLanes; 9309 RHSMask &= ~LHSUsedLanes; 9310 // Add 4 to each active LHS lane 9311 LHSMask |= LHSUsedLanes & 0x04040404; 9312 // Combine masks 9313 uint32_t Sel = LHSMask | RHSMask; 9314 SDLoc DL(N); 9315 9316 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9317 LHS.getOperand(0), RHS.getOperand(0), 9318 DAG.getConstant(Sel, DL, MVT::i32)); 9319 } 9320 } 9321 } 9322 9323 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9324 return SDValue(); 9325 9326 // TODO: This could be a generic combine with a predicate for extracting the 9327 // high half of an integer being free. 9328 9329 // (or i64:x, (zero_extend i32:y)) -> 9330 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9331 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9332 RHS.getOpcode() != ISD::ZERO_EXTEND) 9333 std::swap(LHS, RHS); 9334 9335 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9336 SDValue ExtSrc = RHS.getOperand(0); 9337 EVT SrcVT = ExtSrc.getValueType(); 9338 if (SrcVT == MVT::i32) { 9339 SDLoc SL(N); 9340 SDValue LowLHS, HiBits; 9341 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9342 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9343 9344 DCI.AddToWorklist(LowOr.getNode()); 9345 DCI.AddToWorklist(HiBits.getNode()); 9346 9347 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9348 LowOr, HiBits); 9349 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9350 } 9351 } 9352 9353 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9354 if (CRHS) { 9355 if (SDValue Split 9356 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9357 return Split; 9358 } 9359 9360 return SDValue(); 9361 } 9362 9363 SDValue SITargetLowering::performXorCombine(SDNode *N, 9364 DAGCombinerInfo &DCI) const { 9365 EVT VT = N->getValueType(0); 9366 if (VT != MVT::i64) 9367 return SDValue(); 9368 9369 SDValue LHS = N->getOperand(0); 9370 SDValue RHS = N->getOperand(1); 9371 9372 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9373 if (CRHS) { 9374 if (SDValue Split 9375 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9376 return Split; 9377 } 9378 9379 return SDValue(); 9380 } 9381 9382 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9383 DAGCombinerInfo &DCI) const { 9384 if (!Subtarget->has16BitInsts() || 9385 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9386 return SDValue(); 9387 9388 EVT VT = N->getValueType(0); 9389 if (VT != MVT::i32) 9390 return SDValue(); 9391 9392 SDValue Src = N->getOperand(0); 9393 if (Src.getValueType() != MVT::i16) 9394 return SDValue(); 9395 9396 return SDValue(); 9397 } 9398 9399 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9400 DAGCombinerInfo &DCI) 9401 const { 9402 SDValue Src = N->getOperand(0); 9403 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9404 9405 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9406 VTSign->getVT() == MVT::i8) || 9407 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9408 VTSign->getVT() == MVT::i16)) && 9409 Src.hasOneUse()) { 9410 auto *M = cast<MemSDNode>(Src); 9411 SDValue Ops[] = { 9412 Src.getOperand(0), // Chain 9413 Src.getOperand(1), // rsrc 9414 Src.getOperand(2), // vindex 9415 Src.getOperand(3), // voffset 9416 Src.getOperand(4), // soffset 9417 Src.getOperand(5), // offset 9418 Src.getOperand(6), 9419 Src.getOperand(7) 9420 }; 9421 // replace with BUFFER_LOAD_BYTE/SHORT 9422 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9423 Src.getOperand(0).getValueType()); 9424 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9425 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9426 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9427 ResList, 9428 Ops, M->getMemoryVT(), 9429 M->getMemOperand()); 9430 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9431 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9432 } 9433 return SDValue(); 9434 } 9435 9436 SDValue SITargetLowering::performClassCombine(SDNode *N, 9437 DAGCombinerInfo &DCI) const { 9438 SelectionDAG &DAG = DCI.DAG; 9439 SDValue Mask = N->getOperand(1); 9440 9441 // fp_class x, 0 -> false 9442 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9443 if (CMask->isNullValue()) 9444 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9445 } 9446 9447 if (N->getOperand(0).isUndef()) 9448 return DAG.getUNDEF(MVT::i1); 9449 9450 return SDValue(); 9451 } 9452 9453 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9454 DAGCombinerInfo &DCI) const { 9455 EVT VT = N->getValueType(0); 9456 SDValue N0 = N->getOperand(0); 9457 9458 if (N0.isUndef()) 9459 return N0; 9460 9461 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9462 N0.getOpcode() == ISD::SINT_TO_FP)) { 9463 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9464 N->getFlags()); 9465 } 9466 9467 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9468 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9469 N0.getOperand(0), N->getFlags()); 9470 } 9471 9472 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9473 } 9474 9475 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9476 unsigned MaxDepth) const { 9477 unsigned Opcode = Op.getOpcode(); 9478 if (Opcode == ISD::FCANONICALIZE) 9479 return true; 9480 9481 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9482 auto F = CFP->getValueAPF(); 9483 if (F.isNaN() && F.isSignaling()) 9484 return false; 9485 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9486 } 9487 9488 // If source is a result of another standard FP operation it is already in 9489 // canonical form. 9490 if (MaxDepth == 0) 9491 return false; 9492 9493 switch (Opcode) { 9494 // These will flush denorms if required. 9495 case ISD::FADD: 9496 case ISD::FSUB: 9497 case ISD::FMUL: 9498 case ISD::FCEIL: 9499 case ISD::FFLOOR: 9500 case ISD::FMA: 9501 case ISD::FMAD: 9502 case ISD::FSQRT: 9503 case ISD::FDIV: 9504 case ISD::FREM: 9505 case ISD::FP_ROUND: 9506 case ISD::FP_EXTEND: 9507 case AMDGPUISD::FMUL_LEGACY: 9508 case AMDGPUISD::FMAD_FTZ: 9509 case AMDGPUISD::RCP: 9510 case AMDGPUISD::RSQ: 9511 case AMDGPUISD::RSQ_CLAMP: 9512 case AMDGPUISD::RCP_LEGACY: 9513 case AMDGPUISD::RCP_IFLAG: 9514 case AMDGPUISD::DIV_SCALE: 9515 case AMDGPUISD::DIV_FMAS: 9516 case AMDGPUISD::DIV_FIXUP: 9517 case AMDGPUISD::FRACT: 9518 case AMDGPUISD::LDEXP: 9519 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9520 case AMDGPUISD::CVT_F32_UBYTE0: 9521 case AMDGPUISD::CVT_F32_UBYTE1: 9522 case AMDGPUISD::CVT_F32_UBYTE2: 9523 case AMDGPUISD::CVT_F32_UBYTE3: 9524 return true; 9525 9526 // It can/will be lowered or combined as a bit operation. 9527 // Need to check their input recursively to handle. 9528 case ISD::FNEG: 9529 case ISD::FABS: 9530 case ISD::FCOPYSIGN: 9531 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9532 9533 case ISD::FSIN: 9534 case ISD::FCOS: 9535 case ISD::FSINCOS: 9536 return Op.getValueType().getScalarType() != MVT::f16; 9537 9538 case ISD::FMINNUM: 9539 case ISD::FMAXNUM: 9540 case ISD::FMINNUM_IEEE: 9541 case ISD::FMAXNUM_IEEE: 9542 case AMDGPUISD::CLAMP: 9543 case AMDGPUISD::FMED3: 9544 case AMDGPUISD::FMAX3: 9545 case AMDGPUISD::FMIN3: { 9546 // FIXME: Shouldn't treat the generic operations different based these. 9547 // However, we aren't really required to flush the result from 9548 // minnum/maxnum.. 9549 9550 // snans will be quieted, so we only need to worry about denormals. 9551 if (Subtarget->supportsMinMaxDenormModes() || 9552 denormalsEnabledForType(DAG, Op.getValueType())) 9553 return true; 9554 9555 // Flushing may be required. 9556 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9557 // targets need to check their input recursively. 9558 9559 // FIXME: Does this apply with clamp? It's implemented with max. 9560 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9561 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9562 return false; 9563 } 9564 9565 return true; 9566 } 9567 case ISD::SELECT: { 9568 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9569 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9570 } 9571 case ISD::BUILD_VECTOR: { 9572 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9573 SDValue SrcOp = Op.getOperand(i); 9574 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9575 return false; 9576 } 9577 9578 return true; 9579 } 9580 case ISD::EXTRACT_VECTOR_ELT: 9581 case ISD::EXTRACT_SUBVECTOR: { 9582 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9583 } 9584 case ISD::INSERT_VECTOR_ELT: { 9585 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9586 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9587 } 9588 case ISD::UNDEF: 9589 // Could be anything. 9590 return false; 9591 9592 case ISD::BITCAST: 9593 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9594 case ISD::TRUNCATE: { 9595 // Hack round the mess we make when legalizing extract_vector_elt 9596 if (Op.getValueType() == MVT::i16) { 9597 SDValue TruncSrc = Op.getOperand(0); 9598 if (TruncSrc.getValueType() == MVT::i32 && 9599 TruncSrc.getOpcode() == ISD::BITCAST && 9600 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9601 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9602 } 9603 } 9604 return false; 9605 } 9606 case ISD::INTRINSIC_WO_CHAIN: { 9607 unsigned IntrinsicID 9608 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9609 // TODO: Handle more intrinsics 9610 switch (IntrinsicID) { 9611 case Intrinsic::amdgcn_cvt_pkrtz: 9612 case Intrinsic::amdgcn_cubeid: 9613 case Intrinsic::amdgcn_frexp_mant: 9614 case Intrinsic::amdgcn_fdot2: 9615 case Intrinsic::amdgcn_rcp: 9616 case Intrinsic::amdgcn_rsq: 9617 case Intrinsic::amdgcn_rsq_clamp: 9618 case Intrinsic::amdgcn_rcp_legacy: 9619 case Intrinsic::amdgcn_rsq_legacy: 9620 case Intrinsic::amdgcn_trig_preop: 9621 return true; 9622 default: 9623 break; 9624 } 9625 9626 LLVM_FALLTHROUGH; 9627 } 9628 default: 9629 return denormalsEnabledForType(DAG, Op.getValueType()) && 9630 DAG.isKnownNeverSNaN(Op); 9631 } 9632 9633 llvm_unreachable("invalid operation"); 9634 } 9635 9636 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9637 unsigned MaxDepth) const { 9638 MachineRegisterInfo &MRI = MF.getRegInfo(); 9639 MachineInstr *MI = MRI.getVRegDef(Reg); 9640 unsigned Opcode = MI->getOpcode(); 9641 9642 if (Opcode == AMDGPU::G_FCANONICALIZE) 9643 return true; 9644 9645 if (Opcode == AMDGPU::G_FCONSTANT) { 9646 auto F = MI->getOperand(1).getFPImm()->getValueAPF(); 9647 if (F.isNaN() && F.isSignaling()) 9648 return false; 9649 return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF); 9650 } 9651 9652 if (MaxDepth == 0) 9653 return false; 9654 9655 switch (Opcode) { 9656 case AMDGPU::G_FMINNUM_IEEE: 9657 case AMDGPU::G_FMAXNUM_IEEE: { 9658 if (Subtarget->supportsMinMaxDenormModes() || 9659 denormalsEnabledForType(MRI.getType(Reg), MF)) 9660 return true; 9661 for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) { 9662 if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1)) 9663 return false; 9664 } 9665 return true; 9666 } 9667 default: 9668 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9669 isKnownNeverSNaN(Reg, MRI); 9670 } 9671 9672 llvm_unreachable("invalid operation"); 9673 } 9674 9675 // Constant fold canonicalize. 9676 SDValue SITargetLowering::getCanonicalConstantFP( 9677 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9678 // Flush denormals to 0 if not enabled. 9679 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9680 return DAG.getConstantFP(0.0, SL, VT); 9681 9682 if (C.isNaN()) { 9683 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9684 if (C.isSignaling()) { 9685 // Quiet a signaling NaN. 9686 // FIXME: Is this supposed to preserve payload bits? 9687 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9688 } 9689 9690 // Make sure it is the canonical NaN bitpattern. 9691 // 9692 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9693 // immediate? 9694 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9695 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9696 } 9697 9698 // Already canonical. 9699 return DAG.getConstantFP(C, SL, VT); 9700 } 9701 9702 static bool vectorEltWillFoldAway(SDValue Op) { 9703 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9704 } 9705 9706 SDValue SITargetLowering::performFCanonicalizeCombine( 9707 SDNode *N, 9708 DAGCombinerInfo &DCI) const { 9709 SelectionDAG &DAG = DCI.DAG; 9710 SDValue N0 = N->getOperand(0); 9711 EVT VT = N->getValueType(0); 9712 9713 // fcanonicalize undef -> qnan 9714 if (N0.isUndef()) { 9715 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9716 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9717 } 9718 9719 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9720 EVT VT = N->getValueType(0); 9721 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9722 } 9723 9724 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9725 // (fcanonicalize k) 9726 // 9727 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9728 9729 // TODO: This could be better with wider vectors that will be split to v2f16, 9730 // and to consider uses since there aren't that many packed operations. 9731 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9732 isTypeLegal(MVT::v2f16)) { 9733 SDLoc SL(N); 9734 SDValue NewElts[2]; 9735 SDValue Lo = N0.getOperand(0); 9736 SDValue Hi = N0.getOperand(1); 9737 EVT EltVT = Lo.getValueType(); 9738 9739 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9740 for (unsigned I = 0; I != 2; ++I) { 9741 SDValue Op = N0.getOperand(I); 9742 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9743 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9744 CFP->getValueAPF()); 9745 } else if (Op.isUndef()) { 9746 // Handled below based on what the other operand is. 9747 NewElts[I] = Op; 9748 } else { 9749 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9750 } 9751 } 9752 9753 // If one half is undef, and one is constant, perfer a splat vector rather 9754 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9755 // cheaper to use and may be free with a packed operation. 9756 if (NewElts[0].isUndef()) { 9757 if (isa<ConstantFPSDNode>(NewElts[1])) 9758 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9759 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9760 } 9761 9762 if (NewElts[1].isUndef()) { 9763 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9764 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9765 } 9766 9767 return DAG.getBuildVector(VT, SL, NewElts); 9768 } 9769 } 9770 9771 unsigned SrcOpc = N0.getOpcode(); 9772 9773 // If it's free to do so, push canonicalizes further up the source, which may 9774 // find a canonical source. 9775 // 9776 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9777 // sNaNs. 9778 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9779 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9780 if (CRHS && N0.hasOneUse()) { 9781 SDLoc SL(N); 9782 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9783 N0.getOperand(0)); 9784 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9785 DCI.AddToWorklist(Canon0.getNode()); 9786 9787 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9788 } 9789 } 9790 9791 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9792 } 9793 9794 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9795 switch (Opc) { 9796 case ISD::FMAXNUM: 9797 case ISD::FMAXNUM_IEEE: 9798 return AMDGPUISD::FMAX3; 9799 case ISD::SMAX: 9800 return AMDGPUISD::SMAX3; 9801 case ISD::UMAX: 9802 return AMDGPUISD::UMAX3; 9803 case ISD::FMINNUM: 9804 case ISD::FMINNUM_IEEE: 9805 return AMDGPUISD::FMIN3; 9806 case ISD::SMIN: 9807 return AMDGPUISD::SMIN3; 9808 case ISD::UMIN: 9809 return AMDGPUISD::UMIN3; 9810 default: 9811 llvm_unreachable("Not a min/max opcode"); 9812 } 9813 } 9814 9815 SDValue SITargetLowering::performIntMed3ImmCombine( 9816 SelectionDAG &DAG, const SDLoc &SL, 9817 SDValue Op0, SDValue Op1, bool Signed) const { 9818 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9819 if (!K1) 9820 return SDValue(); 9821 9822 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9823 if (!K0) 9824 return SDValue(); 9825 9826 if (Signed) { 9827 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9828 return SDValue(); 9829 } else { 9830 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9831 return SDValue(); 9832 } 9833 9834 EVT VT = K0->getValueType(0); 9835 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9836 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9837 return DAG.getNode(Med3Opc, SL, VT, 9838 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9839 } 9840 9841 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9842 if (VT == MVT::i16) { 9843 MVT NVT = MVT::i32; 9844 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9845 9846 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9847 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9848 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9849 9850 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9851 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9852 } 9853 9854 return SDValue(); 9855 } 9856 9857 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9858 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9859 return C; 9860 9861 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9862 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9863 return C; 9864 } 9865 9866 return nullptr; 9867 } 9868 9869 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9870 const SDLoc &SL, 9871 SDValue Op0, 9872 SDValue Op1) const { 9873 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9874 if (!K1) 9875 return SDValue(); 9876 9877 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9878 if (!K0) 9879 return SDValue(); 9880 9881 // Ordered >= (although NaN inputs should have folded away by now). 9882 if (K0->getValueAPF() > K1->getValueAPF()) 9883 return SDValue(); 9884 9885 const MachineFunction &MF = DAG.getMachineFunction(); 9886 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9887 9888 // TODO: Check IEEE bit enabled? 9889 EVT VT = Op0.getValueType(); 9890 if (Info->getMode().DX10Clamp) { 9891 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9892 // hardware fmed3 behavior converting to a min. 9893 // FIXME: Should this be allowing -0.0? 9894 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9895 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9896 } 9897 9898 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9899 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9900 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9901 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9902 // then give the other result, which is different from med3 with a NaN 9903 // input. 9904 SDValue Var = Op0.getOperand(0); 9905 if (!DAG.isKnownNeverSNaN(Var)) 9906 return SDValue(); 9907 9908 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9909 9910 if ((!K0->hasOneUse() || 9911 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9912 (!K1->hasOneUse() || 9913 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9914 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9915 Var, SDValue(K0, 0), SDValue(K1, 0)); 9916 } 9917 } 9918 9919 return SDValue(); 9920 } 9921 9922 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9923 DAGCombinerInfo &DCI) const { 9924 SelectionDAG &DAG = DCI.DAG; 9925 9926 EVT VT = N->getValueType(0); 9927 unsigned Opc = N->getOpcode(); 9928 SDValue Op0 = N->getOperand(0); 9929 SDValue Op1 = N->getOperand(1); 9930 9931 // Only do this if the inner op has one use since this will just increases 9932 // register pressure for no benefit. 9933 9934 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9935 !VT.isVector() && 9936 (VT == MVT::i32 || VT == MVT::f32 || 9937 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9938 // max(max(a, b), c) -> max3(a, b, c) 9939 // min(min(a, b), c) -> min3(a, b, c) 9940 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9941 SDLoc DL(N); 9942 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9943 DL, 9944 N->getValueType(0), 9945 Op0.getOperand(0), 9946 Op0.getOperand(1), 9947 Op1); 9948 } 9949 9950 // Try commuted. 9951 // max(a, max(b, c)) -> max3(a, b, c) 9952 // min(a, min(b, c)) -> min3(a, b, c) 9953 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9954 SDLoc DL(N); 9955 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9956 DL, 9957 N->getValueType(0), 9958 Op0, 9959 Op1.getOperand(0), 9960 Op1.getOperand(1)); 9961 } 9962 } 9963 9964 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9965 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9966 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9967 return Med3; 9968 } 9969 9970 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9971 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9972 return Med3; 9973 } 9974 9975 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9976 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9977 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9978 (Opc == AMDGPUISD::FMIN_LEGACY && 9979 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9980 (VT == MVT::f32 || VT == MVT::f64 || 9981 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9982 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9983 Op0.hasOneUse()) { 9984 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9985 return Res; 9986 } 9987 9988 return SDValue(); 9989 } 9990 9991 static bool isClampZeroToOne(SDValue A, SDValue B) { 9992 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9993 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9994 // FIXME: Should this be allowing -0.0? 9995 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9996 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9997 } 9998 } 9999 10000 return false; 10001 } 10002 10003 // FIXME: Should only worry about snans for version with chain. 10004 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10005 DAGCombinerInfo &DCI) const { 10006 EVT VT = N->getValueType(0); 10007 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10008 // NaNs. With a NaN input, the order of the operands may change the result. 10009 10010 SelectionDAG &DAG = DCI.DAG; 10011 SDLoc SL(N); 10012 10013 SDValue Src0 = N->getOperand(0); 10014 SDValue Src1 = N->getOperand(1); 10015 SDValue Src2 = N->getOperand(2); 10016 10017 if (isClampZeroToOne(Src0, Src1)) { 10018 // const_a, const_b, x -> clamp is safe in all cases including signaling 10019 // nans. 10020 // FIXME: Should this be allowing -0.0? 10021 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10022 } 10023 10024 const MachineFunction &MF = DAG.getMachineFunction(); 10025 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10026 10027 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10028 // handling no dx10-clamp? 10029 if (Info->getMode().DX10Clamp) { 10030 // If NaNs is clamped to 0, we are free to reorder the inputs. 10031 10032 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10033 std::swap(Src0, Src1); 10034 10035 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10036 std::swap(Src1, Src2); 10037 10038 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10039 std::swap(Src0, Src1); 10040 10041 if (isClampZeroToOne(Src1, Src2)) 10042 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10043 } 10044 10045 return SDValue(); 10046 } 10047 10048 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10049 DAGCombinerInfo &DCI) const { 10050 SDValue Src0 = N->getOperand(0); 10051 SDValue Src1 = N->getOperand(1); 10052 if (Src0.isUndef() && Src1.isUndef()) 10053 return DCI.DAG.getUNDEF(N->getValueType(0)); 10054 return SDValue(); 10055 } 10056 10057 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10058 // expanded into a set of cmp/select instructions. 10059 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10060 unsigned NumElem, 10061 bool IsDivergentIdx) { 10062 if (UseDivergentRegisterIndexing) 10063 return false; 10064 10065 unsigned VecSize = EltSize * NumElem; 10066 10067 // Sub-dword vectors of size 2 dword or less have better implementation. 10068 if (VecSize <= 64 && EltSize < 32) 10069 return false; 10070 10071 // Always expand the rest of sub-dword instructions, otherwise it will be 10072 // lowered via memory. 10073 if (EltSize < 32) 10074 return true; 10075 10076 // Always do this if var-idx is divergent, otherwise it will become a loop. 10077 if (IsDivergentIdx) 10078 return true; 10079 10080 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10081 unsigned NumInsts = NumElem /* Number of compares */ + 10082 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10083 return NumInsts <= 16; 10084 } 10085 10086 static bool shouldExpandVectorDynExt(SDNode *N) { 10087 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10088 if (isa<ConstantSDNode>(Idx)) 10089 return false; 10090 10091 SDValue Vec = N->getOperand(0); 10092 EVT VecVT = Vec.getValueType(); 10093 EVT EltVT = VecVT.getVectorElementType(); 10094 unsigned EltSize = EltVT.getSizeInBits(); 10095 unsigned NumElem = VecVT.getVectorNumElements(); 10096 10097 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10098 Idx->isDivergent()); 10099 } 10100 10101 SDValue SITargetLowering::performExtractVectorEltCombine( 10102 SDNode *N, DAGCombinerInfo &DCI) const { 10103 SDValue Vec = N->getOperand(0); 10104 SelectionDAG &DAG = DCI.DAG; 10105 10106 EVT VecVT = Vec.getValueType(); 10107 EVT EltVT = VecVT.getVectorElementType(); 10108 10109 if ((Vec.getOpcode() == ISD::FNEG || 10110 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10111 SDLoc SL(N); 10112 EVT EltVT = N->getValueType(0); 10113 SDValue Idx = N->getOperand(1); 10114 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10115 Vec.getOperand(0), Idx); 10116 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10117 } 10118 10119 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10120 // => 10121 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10122 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10123 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10124 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10125 SDLoc SL(N); 10126 EVT EltVT = N->getValueType(0); 10127 SDValue Idx = N->getOperand(1); 10128 unsigned Opc = Vec.getOpcode(); 10129 10130 switch(Opc) { 10131 default: 10132 break; 10133 // TODO: Support other binary operations. 10134 case ISD::FADD: 10135 case ISD::FSUB: 10136 case ISD::FMUL: 10137 case ISD::ADD: 10138 case ISD::UMIN: 10139 case ISD::UMAX: 10140 case ISD::SMIN: 10141 case ISD::SMAX: 10142 case ISD::FMAXNUM: 10143 case ISD::FMINNUM: 10144 case ISD::FMAXNUM_IEEE: 10145 case ISD::FMINNUM_IEEE: { 10146 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10147 Vec.getOperand(0), Idx); 10148 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10149 Vec.getOperand(1), Idx); 10150 10151 DCI.AddToWorklist(Elt0.getNode()); 10152 DCI.AddToWorklist(Elt1.getNode()); 10153 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10154 } 10155 } 10156 } 10157 10158 unsigned VecSize = VecVT.getSizeInBits(); 10159 unsigned EltSize = EltVT.getSizeInBits(); 10160 10161 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10162 if (::shouldExpandVectorDynExt(N)) { 10163 SDLoc SL(N); 10164 SDValue Idx = N->getOperand(1); 10165 SDValue V; 10166 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10167 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10168 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10169 if (I == 0) 10170 V = Elt; 10171 else 10172 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10173 } 10174 return V; 10175 } 10176 10177 if (!DCI.isBeforeLegalize()) 10178 return SDValue(); 10179 10180 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10181 // elements. This exposes more load reduction opportunities by replacing 10182 // multiple small extract_vector_elements with a single 32-bit extract. 10183 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10184 if (isa<MemSDNode>(Vec) && 10185 EltSize <= 16 && 10186 EltVT.isByteSized() && 10187 VecSize > 32 && 10188 VecSize % 32 == 0 && 10189 Idx) { 10190 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10191 10192 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10193 unsigned EltIdx = BitIndex / 32; 10194 unsigned LeftoverBitIdx = BitIndex % 32; 10195 SDLoc SL(N); 10196 10197 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10198 DCI.AddToWorklist(Cast.getNode()); 10199 10200 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10201 DAG.getConstant(EltIdx, SL, MVT::i32)); 10202 DCI.AddToWorklist(Elt.getNode()); 10203 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10204 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10205 DCI.AddToWorklist(Srl.getNode()); 10206 10207 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10208 DCI.AddToWorklist(Trunc.getNode()); 10209 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10210 } 10211 10212 return SDValue(); 10213 } 10214 10215 SDValue 10216 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10217 DAGCombinerInfo &DCI) const { 10218 SDValue Vec = N->getOperand(0); 10219 SDValue Idx = N->getOperand(2); 10220 EVT VecVT = Vec.getValueType(); 10221 EVT EltVT = VecVT.getVectorElementType(); 10222 10223 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10224 // => BUILD_VECTOR n x select (e, const-idx) 10225 if (!::shouldExpandVectorDynExt(N)) 10226 return SDValue(); 10227 10228 SelectionDAG &DAG = DCI.DAG; 10229 SDLoc SL(N); 10230 SDValue Ins = N->getOperand(1); 10231 EVT IdxVT = Idx.getValueType(); 10232 10233 SmallVector<SDValue, 16> Ops; 10234 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10235 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10236 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10237 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10238 Ops.push_back(V); 10239 } 10240 10241 return DAG.getBuildVector(VecVT, SL, Ops); 10242 } 10243 10244 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10245 const SDNode *N0, 10246 const SDNode *N1) const { 10247 EVT VT = N0->getValueType(0); 10248 10249 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10250 // support denormals ever. 10251 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10252 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10253 getSubtarget()->hasMadF16())) && 10254 isOperationLegal(ISD::FMAD, VT)) 10255 return ISD::FMAD; 10256 10257 const TargetOptions &Options = DAG.getTarget().Options; 10258 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10259 (N0->getFlags().hasAllowContract() && 10260 N1->getFlags().hasAllowContract())) && 10261 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10262 return ISD::FMA; 10263 } 10264 10265 return 0; 10266 } 10267 10268 // For a reassociatable opcode perform: 10269 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10270 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10271 SelectionDAG &DAG) const { 10272 EVT VT = N->getValueType(0); 10273 if (VT != MVT::i32 && VT != MVT::i64) 10274 return SDValue(); 10275 10276 unsigned Opc = N->getOpcode(); 10277 SDValue Op0 = N->getOperand(0); 10278 SDValue Op1 = N->getOperand(1); 10279 10280 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10281 return SDValue(); 10282 10283 if (Op0->isDivergent()) 10284 std::swap(Op0, Op1); 10285 10286 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10287 return SDValue(); 10288 10289 SDValue Op2 = Op1.getOperand(1); 10290 Op1 = Op1.getOperand(0); 10291 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10292 return SDValue(); 10293 10294 if (Op1->isDivergent()) 10295 std::swap(Op1, Op2); 10296 10297 // If either operand is constant this will conflict with 10298 // DAGCombiner::ReassociateOps(). 10299 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10300 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10301 return SDValue(); 10302 10303 SDLoc SL(N); 10304 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10305 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10306 } 10307 10308 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10309 EVT VT, 10310 SDValue N0, SDValue N1, SDValue N2, 10311 bool Signed) { 10312 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10313 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10314 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10315 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10316 } 10317 10318 SDValue SITargetLowering::performAddCombine(SDNode *N, 10319 DAGCombinerInfo &DCI) const { 10320 SelectionDAG &DAG = DCI.DAG; 10321 EVT VT = N->getValueType(0); 10322 SDLoc SL(N); 10323 SDValue LHS = N->getOperand(0); 10324 SDValue RHS = N->getOperand(1); 10325 10326 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10327 && Subtarget->hasMad64_32() && 10328 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10329 VT.getScalarSizeInBits() <= 64) { 10330 if (LHS.getOpcode() != ISD::MUL) 10331 std::swap(LHS, RHS); 10332 10333 SDValue MulLHS = LHS.getOperand(0); 10334 SDValue MulRHS = LHS.getOperand(1); 10335 SDValue AddRHS = RHS; 10336 10337 // TODO: Maybe restrict if SGPR inputs. 10338 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10339 numBitsUnsigned(MulRHS, DAG) <= 32) { 10340 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10341 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10342 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10343 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10344 } 10345 10346 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10347 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10348 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10349 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10350 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10351 } 10352 10353 return SDValue(); 10354 } 10355 10356 if (SDValue V = reassociateScalarOps(N, DAG)) { 10357 return V; 10358 } 10359 10360 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10361 return SDValue(); 10362 10363 // add x, zext (setcc) => addcarry x, 0, setcc 10364 // add x, sext (setcc) => subcarry x, 0, setcc 10365 unsigned Opc = LHS.getOpcode(); 10366 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10367 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10368 std::swap(RHS, LHS); 10369 10370 Opc = RHS.getOpcode(); 10371 switch (Opc) { 10372 default: break; 10373 case ISD::ZERO_EXTEND: 10374 case ISD::SIGN_EXTEND: 10375 case ISD::ANY_EXTEND: { 10376 auto Cond = RHS.getOperand(0); 10377 // If this won't be a real VOPC output, we would still need to insert an 10378 // extra instruction anyway. 10379 if (!isBoolSGPR(Cond)) 10380 break; 10381 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10382 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10383 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10384 return DAG.getNode(Opc, SL, VTList, Args); 10385 } 10386 case ISD::ADDCARRY: { 10387 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10388 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10389 if (!C || C->getZExtValue() != 0) break; 10390 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10391 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10392 } 10393 } 10394 return SDValue(); 10395 } 10396 10397 SDValue SITargetLowering::performSubCombine(SDNode *N, 10398 DAGCombinerInfo &DCI) const { 10399 SelectionDAG &DAG = DCI.DAG; 10400 EVT VT = N->getValueType(0); 10401 10402 if (VT != MVT::i32) 10403 return SDValue(); 10404 10405 SDLoc SL(N); 10406 SDValue LHS = N->getOperand(0); 10407 SDValue RHS = N->getOperand(1); 10408 10409 // sub x, zext (setcc) => subcarry x, 0, setcc 10410 // sub x, sext (setcc) => addcarry x, 0, setcc 10411 unsigned Opc = RHS.getOpcode(); 10412 switch (Opc) { 10413 default: break; 10414 case ISD::ZERO_EXTEND: 10415 case ISD::SIGN_EXTEND: 10416 case ISD::ANY_EXTEND: { 10417 auto Cond = RHS.getOperand(0); 10418 // If this won't be a real VOPC output, we would still need to insert an 10419 // extra instruction anyway. 10420 if (!isBoolSGPR(Cond)) 10421 break; 10422 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10423 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10424 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10425 return DAG.getNode(Opc, SL, VTList, Args); 10426 } 10427 } 10428 10429 if (LHS.getOpcode() == ISD::SUBCARRY) { 10430 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10431 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10432 if (!C || !C->isNullValue()) 10433 return SDValue(); 10434 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10435 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10436 } 10437 return SDValue(); 10438 } 10439 10440 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10441 DAGCombinerInfo &DCI) const { 10442 10443 if (N->getValueType(0) != MVT::i32) 10444 return SDValue(); 10445 10446 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10447 if (!C || C->getZExtValue() != 0) 10448 return SDValue(); 10449 10450 SelectionDAG &DAG = DCI.DAG; 10451 SDValue LHS = N->getOperand(0); 10452 10453 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10454 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10455 unsigned LHSOpc = LHS.getOpcode(); 10456 unsigned Opc = N->getOpcode(); 10457 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10458 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10459 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10460 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10461 } 10462 return SDValue(); 10463 } 10464 10465 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10466 DAGCombinerInfo &DCI) const { 10467 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10468 return SDValue(); 10469 10470 SelectionDAG &DAG = DCI.DAG; 10471 EVT VT = N->getValueType(0); 10472 10473 SDLoc SL(N); 10474 SDValue LHS = N->getOperand(0); 10475 SDValue RHS = N->getOperand(1); 10476 10477 // These should really be instruction patterns, but writing patterns with 10478 // source modiifiers is a pain. 10479 10480 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10481 if (LHS.getOpcode() == ISD::FADD) { 10482 SDValue A = LHS.getOperand(0); 10483 if (A == LHS.getOperand(1)) { 10484 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10485 if (FusedOp != 0) { 10486 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10487 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10488 } 10489 } 10490 } 10491 10492 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10493 if (RHS.getOpcode() == ISD::FADD) { 10494 SDValue A = RHS.getOperand(0); 10495 if (A == RHS.getOperand(1)) { 10496 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10497 if (FusedOp != 0) { 10498 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10499 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10500 } 10501 } 10502 } 10503 10504 return SDValue(); 10505 } 10506 10507 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10508 DAGCombinerInfo &DCI) const { 10509 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10510 return SDValue(); 10511 10512 SelectionDAG &DAG = DCI.DAG; 10513 SDLoc SL(N); 10514 EVT VT = N->getValueType(0); 10515 assert(!VT.isVector()); 10516 10517 // Try to get the fneg to fold into the source modifier. This undoes generic 10518 // DAG combines and folds them into the mad. 10519 // 10520 // Only do this if we are not trying to support denormals. v_mad_f32 does 10521 // not support denormals ever. 10522 SDValue LHS = N->getOperand(0); 10523 SDValue RHS = N->getOperand(1); 10524 if (LHS.getOpcode() == ISD::FADD) { 10525 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10526 SDValue A = LHS.getOperand(0); 10527 if (A == LHS.getOperand(1)) { 10528 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10529 if (FusedOp != 0){ 10530 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10531 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10532 10533 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10534 } 10535 } 10536 } 10537 10538 if (RHS.getOpcode() == ISD::FADD) { 10539 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10540 10541 SDValue A = RHS.getOperand(0); 10542 if (A == RHS.getOperand(1)) { 10543 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10544 if (FusedOp != 0){ 10545 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10546 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10547 } 10548 } 10549 } 10550 10551 return SDValue(); 10552 } 10553 10554 SDValue SITargetLowering::performFMACombine(SDNode *N, 10555 DAGCombinerInfo &DCI) const { 10556 SelectionDAG &DAG = DCI.DAG; 10557 EVT VT = N->getValueType(0); 10558 SDLoc SL(N); 10559 10560 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10561 return SDValue(); 10562 10563 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10564 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10565 SDValue Op1 = N->getOperand(0); 10566 SDValue Op2 = N->getOperand(1); 10567 SDValue FMA = N->getOperand(2); 10568 10569 if (FMA.getOpcode() != ISD::FMA || 10570 Op1.getOpcode() != ISD::FP_EXTEND || 10571 Op2.getOpcode() != ISD::FP_EXTEND) 10572 return SDValue(); 10573 10574 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10575 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10576 // is sufficient to allow generaing fdot2. 10577 const TargetOptions &Options = DAG.getTarget().Options; 10578 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10579 (N->getFlags().hasAllowContract() && 10580 FMA->getFlags().hasAllowContract())) { 10581 Op1 = Op1.getOperand(0); 10582 Op2 = Op2.getOperand(0); 10583 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10584 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10585 return SDValue(); 10586 10587 SDValue Vec1 = Op1.getOperand(0); 10588 SDValue Idx1 = Op1.getOperand(1); 10589 SDValue Vec2 = Op2.getOperand(0); 10590 10591 SDValue FMAOp1 = FMA.getOperand(0); 10592 SDValue FMAOp2 = FMA.getOperand(1); 10593 SDValue FMAAcc = FMA.getOperand(2); 10594 10595 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10596 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10597 return SDValue(); 10598 10599 FMAOp1 = FMAOp1.getOperand(0); 10600 FMAOp2 = FMAOp2.getOperand(0); 10601 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10602 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10603 return SDValue(); 10604 10605 SDValue Vec3 = FMAOp1.getOperand(0); 10606 SDValue Vec4 = FMAOp2.getOperand(0); 10607 SDValue Idx2 = FMAOp1.getOperand(1); 10608 10609 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10610 // Idx1 and Idx2 cannot be the same. 10611 Idx1 == Idx2) 10612 return SDValue(); 10613 10614 if (Vec1 == Vec2 || Vec3 == Vec4) 10615 return SDValue(); 10616 10617 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10618 return SDValue(); 10619 10620 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10621 (Vec1 == Vec4 && Vec2 == Vec3)) { 10622 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10623 DAG.getTargetConstant(0, SL, MVT::i1)); 10624 } 10625 } 10626 return SDValue(); 10627 } 10628 10629 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10630 DAGCombinerInfo &DCI) const { 10631 SelectionDAG &DAG = DCI.DAG; 10632 SDLoc SL(N); 10633 10634 SDValue LHS = N->getOperand(0); 10635 SDValue RHS = N->getOperand(1); 10636 EVT VT = LHS.getValueType(); 10637 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10638 10639 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10640 if (!CRHS) { 10641 CRHS = dyn_cast<ConstantSDNode>(LHS); 10642 if (CRHS) { 10643 std::swap(LHS, RHS); 10644 CC = getSetCCSwappedOperands(CC); 10645 } 10646 } 10647 10648 if (CRHS) { 10649 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10650 isBoolSGPR(LHS.getOperand(0))) { 10651 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10652 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10653 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10654 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10655 if ((CRHS->isAllOnesValue() && 10656 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10657 (CRHS->isNullValue() && 10658 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10659 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10660 DAG.getConstant(-1, SL, MVT::i1)); 10661 if ((CRHS->isAllOnesValue() && 10662 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10663 (CRHS->isNullValue() && 10664 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10665 return LHS.getOperand(0); 10666 } 10667 10668 uint64_t CRHSVal = CRHS->getZExtValue(); 10669 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10670 LHS.getOpcode() == ISD::SELECT && 10671 isa<ConstantSDNode>(LHS.getOperand(1)) && 10672 isa<ConstantSDNode>(LHS.getOperand(2)) && 10673 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10674 isBoolSGPR(LHS.getOperand(0))) { 10675 // Given CT != FT: 10676 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10677 // setcc (select cc, CT, CF), CF, ne => cc 10678 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10679 // setcc (select cc, CT, CF), CT, eq => cc 10680 uint64_t CT = LHS.getConstantOperandVal(1); 10681 uint64_t CF = LHS.getConstantOperandVal(2); 10682 10683 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10684 (CT == CRHSVal && CC == ISD::SETNE)) 10685 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10686 DAG.getConstant(-1, SL, MVT::i1)); 10687 if ((CF == CRHSVal && CC == ISD::SETNE) || 10688 (CT == CRHSVal && CC == ISD::SETEQ)) 10689 return LHS.getOperand(0); 10690 } 10691 } 10692 10693 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10694 VT != MVT::f16)) 10695 return SDValue(); 10696 10697 // Match isinf/isfinite pattern 10698 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10699 // (fcmp one (fabs x), inf) -> (fp_class x, 10700 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10701 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10702 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10703 if (!CRHS) 10704 return SDValue(); 10705 10706 const APFloat &APF = CRHS->getValueAPF(); 10707 if (APF.isInfinity() && !APF.isNegative()) { 10708 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10709 SIInstrFlags::N_INFINITY; 10710 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10711 SIInstrFlags::P_ZERO | 10712 SIInstrFlags::N_NORMAL | 10713 SIInstrFlags::P_NORMAL | 10714 SIInstrFlags::N_SUBNORMAL | 10715 SIInstrFlags::P_SUBNORMAL; 10716 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10717 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10718 DAG.getConstant(Mask, SL, MVT::i32)); 10719 } 10720 } 10721 10722 return SDValue(); 10723 } 10724 10725 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10726 DAGCombinerInfo &DCI) const { 10727 SelectionDAG &DAG = DCI.DAG; 10728 SDLoc SL(N); 10729 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10730 10731 SDValue Src = N->getOperand(0); 10732 SDValue Shift = N->getOperand(0); 10733 10734 // TODO: Extend type shouldn't matter (assuming legal types). 10735 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10736 Shift = Shift.getOperand(0); 10737 10738 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10739 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10740 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10741 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10742 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10743 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10744 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10745 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10746 SDLoc(Shift.getOperand(0)), MVT::i32); 10747 10748 unsigned ShiftOffset = 8 * Offset; 10749 if (Shift.getOpcode() == ISD::SHL) 10750 ShiftOffset -= C->getZExtValue(); 10751 else 10752 ShiftOffset += C->getZExtValue(); 10753 10754 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10755 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10756 MVT::f32, Shift); 10757 } 10758 } 10759 } 10760 10761 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10762 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10763 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10764 // We simplified Src. If this node is not dead, visit it again so it is 10765 // folded properly. 10766 if (N->getOpcode() != ISD::DELETED_NODE) 10767 DCI.AddToWorklist(N); 10768 return SDValue(N, 0); 10769 } 10770 10771 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10772 if (SDValue DemandedSrc = 10773 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10774 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10775 10776 return SDValue(); 10777 } 10778 10779 SDValue SITargetLowering::performClampCombine(SDNode *N, 10780 DAGCombinerInfo &DCI) const { 10781 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10782 if (!CSrc) 10783 return SDValue(); 10784 10785 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10786 const APFloat &F = CSrc->getValueAPF(); 10787 APFloat Zero = APFloat::getZero(F.getSemantics()); 10788 if (F < Zero || 10789 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10790 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10791 } 10792 10793 APFloat One(F.getSemantics(), "1.0"); 10794 if (F > One) 10795 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10796 10797 return SDValue(CSrc, 0); 10798 } 10799 10800 10801 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10802 DAGCombinerInfo &DCI) const { 10803 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10804 return SDValue(); 10805 switch (N->getOpcode()) { 10806 case ISD::ADD: 10807 return performAddCombine(N, DCI); 10808 case ISD::SUB: 10809 return performSubCombine(N, DCI); 10810 case ISD::ADDCARRY: 10811 case ISD::SUBCARRY: 10812 return performAddCarrySubCarryCombine(N, DCI); 10813 case ISD::FADD: 10814 return performFAddCombine(N, DCI); 10815 case ISD::FSUB: 10816 return performFSubCombine(N, DCI); 10817 case ISD::SETCC: 10818 return performSetCCCombine(N, DCI); 10819 case ISD::FMAXNUM: 10820 case ISD::FMINNUM: 10821 case ISD::FMAXNUM_IEEE: 10822 case ISD::FMINNUM_IEEE: 10823 case ISD::SMAX: 10824 case ISD::SMIN: 10825 case ISD::UMAX: 10826 case ISD::UMIN: 10827 case AMDGPUISD::FMIN_LEGACY: 10828 case AMDGPUISD::FMAX_LEGACY: 10829 return performMinMaxCombine(N, DCI); 10830 case ISD::FMA: 10831 return performFMACombine(N, DCI); 10832 case ISD::AND: 10833 return performAndCombine(N, DCI); 10834 case ISD::OR: 10835 return performOrCombine(N, DCI); 10836 case ISD::XOR: 10837 return performXorCombine(N, DCI); 10838 case ISD::ZERO_EXTEND: 10839 return performZeroExtendCombine(N, DCI); 10840 case ISD::SIGN_EXTEND_INREG: 10841 return performSignExtendInRegCombine(N , DCI); 10842 case AMDGPUISD::FP_CLASS: 10843 return performClassCombine(N, DCI); 10844 case ISD::FCANONICALIZE: 10845 return performFCanonicalizeCombine(N, DCI); 10846 case AMDGPUISD::RCP: 10847 return performRcpCombine(N, DCI); 10848 case AMDGPUISD::FRACT: 10849 case AMDGPUISD::RSQ: 10850 case AMDGPUISD::RCP_LEGACY: 10851 case AMDGPUISD::RCP_IFLAG: 10852 case AMDGPUISD::RSQ_CLAMP: 10853 case AMDGPUISD::LDEXP: { 10854 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10855 SDValue Src = N->getOperand(0); 10856 if (Src.isUndef()) 10857 return Src; 10858 break; 10859 } 10860 case ISD::SINT_TO_FP: 10861 case ISD::UINT_TO_FP: 10862 return performUCharToFloatCombine(N, DCI); 10863 case AMDGPUISD::CVT_F32_UBYTE0: 10864 case AMDGPUISD::CVT_F32_UBYTE1: 10865 case AMDGPUISD::CVT_F32_UBYTE2: 10866 case AMDGPUISD::CVT_F32_UBYTE3: 10867 return performCvtF32UByteNCombine(N, DCI); 10868 case AMDGPUISD::FMED3: 10869 return performFMed3Combine(N, DCI); 10870 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10871 return performCvtPkRTZCombine(N, DCI); 10872 case AMDGPUISD::CLAMP: 10873 return performClampCombine(N, DCI); 10874 case ISD::SCALAR_TO_VECTOR: { 10875 SelectionDAG &DAG = DCI.DAG; 10876 EVT VT = N->getValueType(0); 10877 10878 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10879 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10880 SDLoc SL(N); 10881 SDValue Src = N->getOperand(0); 10882 EVT EltVT = Src.getValueType(); 10883 if (EltVT == MVT::f16) 10884 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10885 10886 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10887 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10888 } 10889 10890 break; 10891 } 10892 case ISD::EXTRACT_VECTOR_ELT: 10893 return performExtractVectorEltCombine(N, DCI); 10894 case ISD::INSERT_VECTOR_ELT: 10895 return performInsertVectorEltCombine(N, DCI); 10896 case ISD::LOAD: { 10897 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10898 return Widended; 10899 LLVM_FALLTHROUGH; 10900 } 10901 default: { 10902 if (!DCI.isBeforeLegalize()) { 10903 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10904 return performMemSDNodeCombine(MemNode, DCI); 10905 } 10906 10907 break; 10908 } 10909 } 10910 10911 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10912 } 10913 10914 /// Helper function for adjustWritemask 10915 static unsigned SubIdx2Lane(unsigned Idx) { 10916 switch (Idx) { 10917 default: return ~0u; 10918 case AMDGPU::sub0: return 0; 10919 case AMDGPU::sub1: return 1; 10920 case AMDGPU::sub2: return 2; 10921 case AMDGPU::sub3: return 3; 10922 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10923 } 10924 } 10925 10926 /// Adjust the writemask of MIMG instructions 10927 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10928 SelectionDAG &DAG) const { 10929 unsigned Opcode = Node->getMachineOpcode(); 10930 10931 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10932 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10933 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10934 return Node; // not implemented for D16 10935 10936 SDNode *Users[5] = { nullptr }; 10937 unsigned Lane = 0; 10938 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10939 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10940 unsigned NewDmask = 0; 10941 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10942 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10943 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10944 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10945 unsigned TFCLane = 0; 10946 bool HasChain = Node->getNumValues() > 1; 10947 10948 if (OldDmask == 0) { 10949 // These are folded out, but on the chance it happens don't assert. 10950 return Node; 10951 } 10952 10953 unsigned OldBitsSet = countPopulation(OldDmask); 10954 // Work out which is the TFE/LWE lane if that is enabled. 10955 if (UsesTFC) { 10956 TFCLane = OldBitsSet; 10957 } 10958 10959 // Try to figure out the used register components 10960 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10961 I != E; ++I) { 10962 10963 // Don't look at users of the chain. 10964 if (I.getUse().getResNo() != 0) 10965 continue; 10966 10967 // Abort if we can't understand the usage 10968 if (!I->isMachineOpcode() || 10969 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10970 return Node; 10971 10972 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10973 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10974 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10975 // set, etc. 10976 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10977 if (Lane == ~0u) 10978 return Node; 10979 10980 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10981 if (UsesTFC && Lane == TFCLane) { 10982 Users[Lane] = *I; 10983 } else { 10984 // Set which texture component corresponds to the lane. 10985 unsigned Comp; 10986 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10987 Comp = countTrailingZeros(Dmask); 10988 Dmask &= ~(1 << Comp); 10989 } 10990 10991 // Abort if we have more than one user per component. 10992 if (Users[Lane]) 10993 return Node; 10994 10995 Users[Lane] = *I; 10996 NewDmask |= 1 << Comp; 10997 } 10998 } 10999 11000 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11001 bool NoChannels = !NewDmask; 11002 if (NoChannels) { 11003 if (!UsesTFC) { 11004 // No uses of the result and not using TFC. Then do nothing. 11005 return Node; 11006 } 11007 // If the original dmask has one channel - then nothing to do 11008 if (OldBitsSet == 1) 11009 return Node; 11010 // Use an arbitrary dmask - required for the instruction to work 11011 NewDmask = 1; 11012 } 11013 // Abort if there's no change 11014 if (NewDmask == OldDmask) 11015 return Node; 11016 11017 unsigned BitsSet = countPopulation(NewDmask); 11018 11019 // Check for TFE or LWE - increase the number of channels by one to account 11020 // for the extra return value 11021 // This will need adjustment for D16 if this is also included in 11022 // adjustWriteMask (this function) but at present D16 are excluded. 11023 unsigned NewChannels = BitsSet + UsesTFC; 11024 11025 int NewOpcode = 11026 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11027 assert(NewOpcode != -1 && 11028 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11029 "failed to find equivalent MIMG op"); 11030 11031 // Adjust the writemask in the node 11032 SmallVector<SDValue, 12> Ops; 11033 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11034 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11035 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11036 11037 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11038 11039 MVT ResultVT = NewChannels == 1 ? 11040 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11041 NewChannels == 5 ? 8 : NewChannels); 11042 SDVTList NewVTList = HasChain ? 11043 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11044 11045 11046 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11047 NewVTList, Ops); 11048 11049 if (HasChain) { 11050 // Update chain. 11051 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11052 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11053 } 11054 11055 if (NewChannels == 1) { 11056 assert(Node->hasNUsesOfValue(1, 0)); 11057 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11058 SDLoc(Node), Users[Lane]->getValueType(0), 11059 SDValue(NewNode, 0)); 11060 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11061 return nullptr; 11062 } 11063 11064 // Update the users of the node with the new indices 11065 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11066 SDNode *User = Users[i]; 11067 if (!User) { 11068 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11069 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11070 if (i || !NoChannels) 11071 continue; 11072 } else { 11073 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11074 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11075 } 11076 11077 switch (Idx) { 11078 default: break; 11079 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11080 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11081 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11082 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11083 } 11084 } 11085 11086 DAG.RemoveDeadNode(Node); 11087 return nullptr; 11088 } 11089 11090 static bool isFrameIndexOp(SDValue Op) { 11091 if (Op.getOpcode() == ISD::AssertZext) 11092 Op = Op.getOperand(0); 11093 11094 return isa<FrameIndexSDNode>(Op); 11095 } 11096 11097 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11098 /// with frame index operands. 11099 /// LLVM assumes that inputs are to these instructions are registers. 11100 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11101 SelectionDAG &DAG) const { 11102 if (Node->getOpcode() == ISD::CopyToReg) { 11103 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11104 SDValue SrcVal = Node->getOperand(2); 11105 11106 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11107 // to try understanding copies to physical registers. 11108 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11109 SDLoc SL(Node); 11110 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11111 SDValue VReg = DAG.getRegister( 11112 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11113 11114 SDNode *Glued = Node->getGluedNode(); 11115 SDValue ToVReg 11116 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11117 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11118 SDValue ToResultReg 11119 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11120 VReg, ToVReg.getValue(1)); 11121 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11122 DAG.RemoveDeadNode(Node); 11123 return ToResultReg.getNode(); 11124 } 11125 } 11126 11127 SmallVector<SDValue, 8> Ops; 11128 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11129 if (!isFrameIndexOp(Node->getOperand(i))) { 11130 Ops.push_back(Node->getOperand(i)); 11131 continue; 11132 } 11133 11134 SDLoc DL(Node); 11135 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11136 Node->getOperand(i).getValueType(), 11137 Node->getOperand(i)), 0)); 11138 } 11139 11140 return DAG.UpdateNodeOperands(Node, Ops); 11141 } 11142 11143 /// Fold the instructions after selecting them. 11144 /// Returns null if users were already updated. 11145 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11146 SelectionDAG &DAG) const { 11147 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11148 unsigned Opcode = Node->getMachineOpcode(); 11149 11150 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11151 !TII->isGather4(Opcode) && 11152 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11153 return adjustWritemask(Node, DAG); 11154 } 11155 11156 if (Opcode == AMDGPU::INSERT_SUBREG || 11157 Opcode == AMDGPU::REG_SEQUENCE) { 11158 legalizeTargetIndependentNode(Node, DAG); 11159 return Node; 11160 } 11161 11162 switch (Opcode) { 11163 case AMDGPU::V_DIV_SCALE_F32_e64: 11164 case AMDGPU::V_DIV_SCALE_F64_e64: { 11165 // Satisfy the operand register constraint when one of the inputs is 11166 // undefined. Ordinarily each undef value will have its own implicit_def of 11167 // a vreg, so force these to use a single register. 11168 SDValue Src0 = Node->getOperand(1); 11169 SDValue Src1 = Node->getOperand(3); 11170 SDValue Src2 = Node->getOperand(5); 11171 11172 if ((Src0.isMachineOpcode() && 11173 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11174 (Src0 == Src1 || Src0 == Src2)) 11175 break; 11176 11177 MVT VT = Src0.getValueType().getSimpleVT(); 11178 const TargetRegisterClass *RC = 11179 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11180 11181 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11182 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11183 11184 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11185 UndefReg, Src0, SDValue()); 11186 11187 // src0 must be the same register as src1 or src2, even if the value is 11188 // undefined, so make sure we don't violate this constraint. 11189 if (Src0.isMachineOpcode() && 11190 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11191 if (Src1.isMachineOpcode() && 11192 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11193 Src0 = Src1; 11194 else if (Src2.isMachineOpcode() && 11195 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11196 Src0 = Src2; 11197 else { 11198 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11199 Src0 = UndefReg; 11200 Src1 = UndefReg; 11201 } 11202 } else 11203 break; 11204 11205 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11206 Ops[1] = Src0; 11207 Ops[3] = Src1; 11208 Ops[5] = Src2; 11209 Ops.push_back(ImpDef.getValue(1)); 11210 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11211 } 11212 default: 11213 break; 11214 } 11215 11216 return Node; 11217 } 11218 11219 // Any MIMG instructions that use tfe or lwe require an initialization of the 11220 // result register that will be written in the case of a memory access failure. 11221 // The required code is also added to tie this init code to the result of the 11222 // img instruction. 11223 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11224 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11225 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11226 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11227 MachineBasicBlock &MBB = *MI.getParent(); 11228 11229 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11230 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11231 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11232 11233 if (!TFE && !LWE) // intersect_ray 11234 return; 11235 11236 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11237 unsigned LWEVal = LWE->getImm(); 11238 unsigned D16Val = D16 ? D16->getImm() : 0; 11239 11240 if (!TFEVal && !LWEVal) 11241 return; 11242 11243 // At least one of TFE or LWE are non-zero 11244 // We have to insert a suitable initialization of the result value and 11245 // tie this to the dest of the image instruction. 11246 11247 const DebugLoc &DL = MI.getDebugLoc(); 11248 11249 int DstIdx = 11250 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11251 11252 // Calculate which dword we have to initialize to 0. 11253 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11254 11255 // check that dmask operand is found. 11256 assert(MO_Dmask && "Expected dmask operand in instruction"); 11257 11258 unsigned dmask = MO_Dmask->getImm(); 11259 // Determine the number of active lanes taking into account the 11260 // Gather4 special case 11261 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11262 11263 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11264 11265 unsigned InitIdx = 11266 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11267 11268 // Abandon attempt if the dst size isn't large enough 11269 // - this is in fact an error but this is picked up elsewhere and 11270 // reported correctly. 11271 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11272 if (DstSize < InitIdx) 11273 return; 11274 11275 // Create a register for the intialization value. 11276 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11277 unsigned NewDst = 0; // Final initialized value will be in here 11278 11279 // If PRTStrictNull feature is enabled (the default) then initialize 11280 // all the result registers to 0, otherwise just the error indication 11281 // register (VGPRn+1) 11282 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11283 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11284 11285 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11286 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11287 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11288 // Initialize dword 11289 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11290 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11291 .addImm(0); 11292 // Insert into the super-reg 11293 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11294 .addReg(PrevDst) 11295 .addReg(SubReg) 11296 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11297 11298 PrevDst = NewDst; 11299 } 11300 11301 // Add as an implicit operand 11302 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11303 11304 // Tie the just added implicit operand to the dst 11305 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11306 } 11307 11308 /// Assign the register class depending on the number of 11309 /// bits set in the writemask 11310 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11311 SDNode *Node) const { 11312 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11313 11314 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11315 11316 if (TII->isVOP3(MI.getOpcode())) { 11317 // Make sure constant bus requirements are respected. 11318 TII->legalizeOperandsVOP3(MRI, MI); 11319 11320 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11321 // This saves a chain-copy of registers and better ballance register 11322 // use between vgpr and agpr as agpr tuples tend to be big. 11323 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11324 unsigned Opc = MI.getOpcode(); 11325 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11326 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11327 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11328 if (I == -1) 11329 break; 11330 MachineOperand &Op = MI.getOperand(I); 11331 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11332 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11333 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11334 continue; 11335 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11336 if (!Src || !Src->isCopy() || 11337 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11338 continue; 11339 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11340 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11341 // All uses of agpr64 and agpr32 can also accept vgpr except for 11342 // v_accvgpr_read, but we do not produce agpr reads during selection, 11343 // so no use checks are needed. 11344 MRI.setRegClass(Op.getReg(), NewRC); 11345 } 11346 } 11347 11348 return; 11349 } 11350 11351 // Replace unused atomics with the no return version. 11352 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11353 if (NoRetAtomicOp != -1) { 11354 if (!Node->hasAnyUseOfValue(0)) { 11355 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11356 AMDGPU::OpName::cpol); 11357 if (CPolIdx != -1) { 11358 MachineOperand &CPol = MI.getOperand(CPolIdx); 11359 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11360 } 11361 MI.RemoveOperand(0); 11362 MI.setDesc(TII->get(NoRetAtomicOp)); 11363 return; 11364 } 11365 11366 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11367 // instruction, because the return type of these instructions is a vec2 of 11368 // the memory type, so it can be tied to the input operand. 11369 // This means these instructions always have a use, so we need to add a 11370 // special case to check if the atomic has only one extract_subreg use, 11371 // which itself has no uses. 11372 if ((Node->hasNUsesOfValue(1, 0) && 11373 Node->use_begin()->isMachineOpcode() && 11374 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11375 !Node->use_begin()->hasAnyUseOfValue(0))) { 11376 Register Def = MI.getOperand(0).getReg(); 11377 11378 // Change this into a noret atomic. 11379 MI.setDesc(TII->get(NoRetAtomicOp)); 11380 MI.RemoveOperand(0); 11381 11382 // If we only remove the def operand from the atomic instruction, the 11383 // extract_subreg will be left with a use of a vreg without a def. 11384 // So we need to insert an implicit_def to avoid machine verifier 11385 // errors. 11386 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11387 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11388 } 11389 return; 11390 } 11391 11392 if (TII->isMIMG(MI) && !MI.mayStore()) 11393 AddIMGInit(MI); 11394 } 11395 11396 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11397 uint64_t Val) { 11398 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11399 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11400 } 11401 11402 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11403 const SDLoc &DL, 11404 SDValue Ptr) const { 11405 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11406 11407 // Build the half of the subregister with the constants before building the 11408 // full 128-bit register. If we are building multiple resource descriptors, 11409 // this will allow CSEing of the 2-component register. 11410 const SDValue Ops0[] = { 11411 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11412 buildSMovImm32(DAG, DL, 0), 11413 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11414 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11415 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11416 }; 11417 11418 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11419 MVT::v2i32, Ops0), 0); 11420 11421 // Combine the constants and the pointer. 11422 const SDValue Ops1[] = { 11423 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11424 Ptr, 11425 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11426 SubRegHi, 11427 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11428 }; 11429 11430 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11431 } 11432 11433 /// Return a resource descriptor with the 'Add TID' bit enabled 11434 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11435 /// of the resource descriptor) to create an offset, which is added to 11436 /// the resource pointer. 11437 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11438 SDValue Ptr, uint32_t RsrcDword1, 11439 uint64_t RsrcDword2And3) const { 11440 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11441 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11442 if (RsrcDword1) { 11443 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11444 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11445 0); 11446 } 11447 11448 SDValue DataLo = buildSMovImm32(DAG, DL, 11449 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11450 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11451 11452 const SDValue Ops[] = { 11453 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11454 PtrLo, 11455 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11456 PtrHi, 11457 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11458 DataLo, 11459 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11460 DataHi, 11461 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11462 }; 11463 11464 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11465 } 11466 11467 //===----------------------------------------------------------------------===// 11468 // SI Inline Assembly Support 11469 //===----------------------------------------------------------------------===// 11470 11471 std::pair<unsigned, const TargetRegisterClass *> 11472 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11473 StringRef Constraint, 11474 MVT VT) const { 11475 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11476 11477 const TargetRegisterClass *RC = nullptr; 11478 if (Constraint.size() == 1) { 11479 const unsigned BitWidth = VT.getSizeInBits(); 11480 switch (Constraint[0]) { 11481 default: 11482 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11483 case 's': 11484 case 'r': 11485 switch (BitWidth) { 11486 case 16: 11487 RC = &AMDGPU::SReg_32RegClass; 11488 break; 11489 case 64: 11490 RC = &AMDGPU::SGPR_64RegClass; 11491 break; 11492 default: 11493 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11494 if (!RC) 11495 return std::make_pair(0U, nullptr); 11496 break; 11497 } 11498 break; 11499 case 'v': 11500 switch (BitWidth) { 11501 case 16: 11502 RC = &AMDGPU::VGPR_32RegClass; 11503 break; 11504 default: 11505 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11506 if (!RC) 11507 return std::make_pair(0U, nullptr); 11508 break; 11509 } 11510 break; 11511 case 'a': 11512 if (!Subtarget->hasMAIInsts()) 11513 break; 11514 switch (BitWidth) { 11515 case 16: 11516 RC = &AMDGPU::AGPR_32RegClass; 11517 break; 11518 default: 11519 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11520 if (!RC) 11521 return std::make_pair(0U, nullptr); 11522 break; 11523 } 11524 break; 11525 } 11526 // We actually support i128, i16 and f16 as inline parameters 11527 // even if they are not reported as legal 11528 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11529 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11530 return std::make_pair(0U, RC); 11531 } 11532 11533 if (Constraint.size() > 1) { 11534 if (Constraint[1] == 'v') { 11535 RC = &AMDGPU::VGPR_32RegClass; 11536 } else if (Constraint[1] == 's') { 11537 RC = &AMDGPU::SGPR_32RegClass; 11538 } else if (Constraint[1] == 'a') { 11539 RC = &AMDGPU::AGPR_32RegClass; 11540 } 11541 11542 if (RC) { 11543 uint32_t Idx; 11544 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11545 if (!Failed && Idx < RC->getNumRegs()) 11546 return std::make_pair(RC->getRegister(Idx), RC); 11547 } 11548 } 11549 11550 // FIXME: Returns VS_32 for physical SGPR constraints 11551 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11552 } 11553 11554 static bool isImmConstraint(StringRef Constraint) { 11555 if (Constraint.size() == 1) { 11556 switch (Constraint[0]) { 11557 default: break; 11558 case 'I': 11559 case 'J': 11560 case 'A': 11561 case 'B': 11562 case 'C': 11563 return true; 11564 } 11565 } else if (Constraint == "DA" || 11566 Constraint == "DB") { 11567 return true; 11568 } 11569 return false; 11570 } 11571 11572 SITargetLowering::ConstraintType 11573 SITargetLowering::getConstraintType(StringRef Constraint) const { 11574 if (Constraint.size() == 1) { 11575 switch (Constraint[0]) { 11576 default: break; 11577 case 's': 11578 case 'v': 11579 case 'a': 11580 return C_RegisterClass; 11581 } 11582 } 11583 if (isImmConstraint(Constraint)) { 11584 return C_Other; 11585 } 11586 return TargetLowering::getConstraintType(Constraint); 11587 } 11588 11589 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11590 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11591 Val = Val & maskTrailingOnes<uint64_t>(Size); 11592 } 11593 return Val; 11594 } 11595 11596 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11597 std::string &Constraint, 11598 std::vector<SDValue> &Ops, 11599 SelectionDAG &DAG) const { 11600 if (isImmConstraint(Constraint)) { 11601 uint64_t Val; 11602 if (getAsmOperandConstVal(Op, Val) && 11603 checkAsmConstraintVal(Op, Constraint, Val)) { 11604 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11605 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11606 } 11607 } else { 11608 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11609 } 11610 } 11611 11612 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11613 unsigned Size = Op.getScalarValueSizeInBits(); 11614 if (Size > 64) 11615 return false; 11616 11617 if (Size == 16 && !Subtarget->has16BitInsts()) 11618 return false; 11619 11620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11621 Val = C->getSExtValue(); 11622 return true; 11623 } 11624 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11625 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11626 return true; 11627 } 11628 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11629 if (Size != 16 || Op.getNumOperands() != 2) 11630 return false; 11631 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11632 return false; 11633 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11634 Val = C->getSExtValue(); 11635 return true; 11636 } 11637 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11638 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11639 return true; 11640 } 11641 } 11642 11643 return false; 11644 } 11645 11646 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11647 const std::string &Constraint, 11648 uint64_t Val) const { 11649 if (Constraint.size() == 1) { 11650 switch (Constraint[0]) { 11651 case 'I': 11652 return AMDGPU::isInlinableIntLiteral(Val); 11653 case 'J': 11654 return isInt<16>(Val); 11655 case 'A': 11656 return checkAsmConstraintValA(Op, Val); 11657 case 'B': 11658 return isInt<32>(Val); 11659 case 'C': 11660 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11661 AMDGPU::isInlinableIntLiteral(Val); 11662 default: 11663 break; 11664 } 11665 } else if (Constraint.size() == 2) { 11666 if (Constraint == "DA") { 11667 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11668 int64_t LoBits = static_cast<int32_t>(Val); 11669 return checkAsmConstraintValA(Op, HiBits, 32) && 11670 checkAsmConstraintValA(Op, LoBits, 32); 11671 } 11672 if (Constraint == "DB") { 11673 return true; 11674 } 11675 } 11676 llvm_unreachable("Invalid asm constraint"); 11677 } 11678 11679 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11680 uint64_t Val, 11681 unsigned MaxSize) const { 11682 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11683 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11684 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11685 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11686 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11687 return true; 11688 } 11689 return false; 11690 } 11691 11692 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11693 switch (UnalignedClassID) { 11694 case AMDGPU::VReg_64RegClassID: 11695 return AMDGPU::VReg_64_Align2RegClassID; 11696 case AMDGPU::VReg_96RegClassID: 11697 return AMDGPU::VReg_96_Align2RegClassID; 11698 case AMDGPU::VReg_128RegClassID: 11699 return AMDGPU::VReg_128_Align2RegClassID; 11700 case AMDGPU::VReg_160RegClassID: 11701 return AMDGPU::VReg_160_Align2RegClassID; 11702 case AMDGPU::VReg_192RegClassID: 11703 return AMDGPU::VReg_192_Align2RegClassID; 11704 case AMDGPU::VReg_224RegClassID: 11705 return AMDGPU::VReg_224_Align2RegClassID; 11706 case AMDGPU::VReg_256RegClassID: 11707 return AMDGPU::VReg_256_Align2RegClassID; 11708 case AMDGPU::VReg_512RegClassID: 11709 return AMDGPU::VReg_512_Align2RegClassID; 11710 case AMDGPU::VReg_1024RegClassID: 11711 return AMDGPU::VReg_1024_Align2RegClassID; 11712 case AMDGPU::AReg_64RegClassID: 11713 return AMDGPU::AReg_64_Align2RegClassID; 11714 case AMDGPU::AReg_96RegClassID: 11715 return AMDGPU::AReg_96_Align2RegClassID; 11716 case AMDGPU::AReg_128RegClassID: 11717 return AMDGPU::AReg_128_Align2RegClassID; 11718 case AMDGPU::AReg_160RegClassID: 11719 return AMDGPU::AReg_160_Align2RegClassID; 11720 case AMDGPU::AReg_192RegClassID: 11721 return AMDGPU::AReg_192_Align2RegClassID; 11722 case AMDGPU::AReg_256RegClassID: 11723 return AMDGPU::AReg_256_Align2RegClassID; 11724 case AMDGPU::AReg_512RegClassID: 11725 return AMDGPU::AReg_512_Align2RegClassID; 11726 case AMDGPU::AReg_1024RegClassID: 11727 return AMDGPU::AReg_1024_Align2RegClassID; 11728 default: 11729 return -1; 11730 } 11731 } 11732 11733 // Figure out which registers should be reserved for stack access. Only after 11734 // the function is legalized do we know all of the non-spill stack objects or if 11735 // calls are present. 11736 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11737 MachineRegisterInfo &MRI = MF.getRegInfo(); 11738 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11739 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11740 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11741 const SIInstrInfo *TII = ST.getInstrInfo(); 11742 11743 if (Info->isEntryFunction()) { 11744 // Callable functions have fixed registers used for stack access. 11745 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11746 } 11747 11748 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11749 Info->getStackPtrOffsetReg())); 11750 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11751 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11752 11753 // We need to worry about replacing the default register with itself in case 11754 // of MIR testcases missing the MFI. 11755 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11756 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11757 11758 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11759 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11760 11761 Info->limitOccupancy(MF); 11762 11763 if (ST.isWave32() && !MF.empty()) { 11764 for (auto &MBB : MF) { 11765 for (auto &MI : MBB) { 11766 TII->fixImplicitOperands(MI); 11767 } 11768 } 11769 } 11770 11771 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11772 // classes if required. Ideally the register class constraints would differ 11773 // per-subtarget, but there's no easy way to achieve that right now. This is 11774 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11775 // from using them as the register class for legal types. 11776 if (ST.needsAlignedVGPRs()) { 11777 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11778 const Register Reg = Register::index2VirtReg(I); 11779 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11780 if (!RC) 11781 continue; 11782 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11783 if (NewClassID != -1) 11784 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11785 } 11786 } 11787 11788 TargetLoweringBase::finalizeLowering(MF); 11789 11790 // Allocate a VGPR for future SGPR Spill if 11791 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11792 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11793 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11794 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11795 Info->reserveVGPRforSGPRSpills(MF); 11796 } 11797 11798 void SITargetLowering::computeKnownBitsForFrameIndex( 11799 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11800 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11801 11802 // Set the high bits to zero based on the maximum allowed scratch size per 11803 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11804 // calculation won't overflow, so assume the sign bit is never set. 11805 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11806 } 11807 11808 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11809 KnownBits &Known, unsigned Dim) { 11810 unsigned MaxValue = 11811 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11812 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11813 } 11814 11815 void SITargetLowering::computeKnownBitsForTargetInstr( 11816 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11817 const MachineRegisterInfo &MRI, unsigned Depth) const { 11818 const MachineInstr *MI = MRI.getVRegDef(R); 11819 switch (MI->getOpcode()) { 11820 case AMDGPU::G_INTRINSIC: { 11821 switch (MI->getIntrinsicID()) { 11822 case Intrinsic::amdgcn_workitem_id_x: 11823 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11824 break; 11825 case Intrinsic::amdgcn_workitem_id_y: 11826 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11827 break; 11828 case Intrinsic::amdgcn_workitem_id_z: 11829 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11830 break; 11831 case Intrinsic::amdgcn_mbcnt_lo: 11832 case Intrinsic::amdgcn_mbcnt_hi: { 11833 // These return at most the wavefront size - 1. 11834 unsigned Size = MRI.getType(R).getSizeInBits(); 11835 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11836 break; 11837 } 11838 case Intrinsic::amdgcn_groupstaticsize: { 11839 // We can report everything over the maximum size as 0. We can't report 11840 // based on the actual size because we don't know if it's accurate or not 11841 // at any given point. 11842 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11843 break; 11844 } 11845 } 11846 break; 11847 } 11848 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11849 Known.Zero.setHighBits(24); 11850 break; 11851 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11852 Known.Zero.setHighBits(16); 11853 break; 11854 } 11855 } 11856 11857 Align SITargetLowering::computeKnownAlignForTargetInstr( 11858 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11859 unsigned Depth) const { 11860 const MachineInstr *MI = MRI.getVRegDef(R); 11861 switch (MI->getOpcode()) { 11862 case AMDGPU::G_INTRINSIC: 11863 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11864 // FIXME: Can this move to generic code? What about the case where the call 11865 // site specifies a lower alignment? 11866 Intrinsic::ID IID = MI->getIntrinsicID(); 11867 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11868 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11869 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11870 return *RetAlign; 11871 return Align(1); 11872 } 11873 default: 11874 return Align(1); 11875 } 11876 } 11877 11878 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11879 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11880 const Align CacheLineAlign = Align(64); 11881 11882 // Pre-GFX10 target did not benefit from loop alignment 11883 if (!ML || DisableLoopAlignment || 11884 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11885 getSubtarget()->hasInstFwdPrefetchBug()) 11886 return PrefAlign; 11887 11888 // On GFX10 I$ is 4 x 64 bytes cache lines. 11889 // By default prefetcher keeps one cache line behind and reads two ahead. 11890 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11891 // behind and one ahead. 11892 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11893 // If loop fits 64 bytes it always spans no more than two cache lines and 11894 // does not need an alignment. 11895 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11896 // Else if loop is less or equal 192 bytes we need two lines behind. 11897 11898 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11899 const MachineBasicBlock *Header = ML->getHeader(); 11900 if (Header->getAlignment() != PrefAlign) 11901 return Header->getAlignment(); // Already processed. 11902 11903 unsigned LoopSize = 0; 11904 for (const MachineBasicBlock *MBB : ML->blocks()) { 11905 // If inner loop block is aligned assume in average half of the alignment 11906 // size to be added as nops. 11907 if (MBB != Header) 11908 LoopSize += MBB->getAlignment().value() / 2; 11909 11910 for (const MachineInstr &MI : *MBB) { 11911 LoopSize += TII->getInstSizeInBytes(MI); 11912 if (LoopSize > 192) 11913 return PrefAlign; 11914 } 11915 } 11916 11917 if (LoopSize <= 64) 11918 return PrefAlign; 11919 11920 if (LoopSize <= 128) 11921 return CacheLineAlign; 11922 11923 // If any of parent loops is surrounded by prefetch instructions do not 11924 // insert new for inner loop, which would reset parent's settings. 11925 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11926 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11927 auto I = Exit->getFirstNonDebugInstr(); 11928 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11929 return CacheLineAlign; 11930 } 11931 } 11932 11933 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11934 MachineBasicBlock *Exit = ML->getExitBlock(); 11935 11936 if (Pre && Exit) { 11937 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11938 TII->get(AMDGPU::S_INST_PREFETCH)) 11939 .addImm(1); // prefetch 2 lines behind PC 11940 11941 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11942 TII->get(AMDGPU::S_INST_PREFETCH)) 11943 .addImm(2); // prefetch 1 line behind PC 11944 } 11945 11946 return CacheLineAlign; 11947 } 11948 11949 LLVM_ATTRIBUTE_UNUSED 11950 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11951 assert(N->getOpcode() == ISD::CopyFromReg); 11952 do { 11953 // Follow the chain until we find an INLINEASM node. 11954 N = N->getOperand(0).getNode(); 11955 if (N->getOpcode() == ISD::INLINEASM || 11956 N->getOpcode() == ISD::INLINEASM_BR) 11957 return true; 11958 } while (N->getOpcode() == ISD::CopyFromReg); 11959 return false; 11960 } 11961 11962 bool SITargetLowering::isSDNodeSourceOfDivergence( 11963 const SDNode *N, FunctionLoweringInfo *FLI, 11964 LegacyDivergenceAnalysis *KDA) const { 11965 switch (N->getOpcode()) { 11966 case ISD::CopyFromReg: { 11967 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11968 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11969 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11970 Register Reg = R->getReg(); 11971 11972 // FIXME: Why does this need to consider isLiveIn? 11973 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11974 return !TRI->isSGPRReg(MRI, Reg); 11975 11976 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11977 return KDA->isDivergent(V); 11978 11979 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11980 return !TRI->isSGPRReg(MRI, Reg); 11981 } 11982 case ISD::LOAD: { 11983 const LoadSDNode *L = cast<LoadSDNode>(N); 11984 unsigned AS = L->getAddressSpace(); 11985 // A flat load may access private memory. 11986 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11987 } 11988 case ISD::CALLSEQ_END: 11989 return true; 11990 case ISD::INTRINSIC_WO_CHAIN: 11991 return AMDGPU::isIntrinsicSourceOfDivergence( 11992 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11993 case ISD::INTRINSIC_W_CHAIN: 11994 return AMDGPU::isIntrinsicSourceOfDivergence( 11995 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11996 case AMDGPUISD::ATOMIC_CMP_SWAP: 11997 case AMDGPUISD::ATOMIC_INC: 11998 case AMDGPUISD::ATOMIC_DEC: 11999 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12000 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12001 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12002 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12003 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12004 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12005 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12006 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12007 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12008 case AMDGPUISD::BUFFER_ATOMIC_AND: 12009 case AMDGPUISD::BUFFER_ATOMIC_OR: 12010 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12011 case AMDGPUISD::BUFFER_ATOMIC_INC: 12012 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12013 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12014 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12015 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12016 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12017 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12018 // Target-specific read-modify-write atomics are sources of divergence. 12019 return true; 12020 default: 12021 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12022 // Generic read-modify-write atomics are sources of divergence. 12023 return A->readMem() && A->writeMem(); 12024 } 12025 return false; 12026 } 12027 } 12028 12029 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12030 EVT VT) const { 12031 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12032 case MVT::f32: 12033 return hasFP32Denormals(DAG.getMachineFunction()); 12034 case MVT::f64: 12035 case MVT::f16: 12036 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12037 default: 12038 return false; 12039 } 12040 } 12041 12042 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12043 MachineFunction &MF) const { 12044 switch (Ty.getScalarSizeInBits()) { 12045 case 32: 12046 return hasFP32Denormals(MF); 12047 case 64: 12048 case 16: 12049 return hasFP64FP16Denormals(MF); 12050 default: 12051 return false; 12052 } 12053 } 12054 12055 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12056 const SelectionDAG &DAG, 12057 bool SNaN, 12058 unsigned Depth) const { 12059 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12060 const MachineFunction &MF = DAG.getMachineFunction(); 12061 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12062 12063 if (Info->getMode().DX10Clamp) 12064 return true; // Clamped to 0. 12065 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12066 } 12067 12068 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12069 SNaN, Depth); 12070 } 12071 12072 // Global FP atomic instructions have a hardcoded FP mode and do not support 12073 // FP32 denormals, and only support v2f16 denormals. 12074 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12075 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12076 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12077 if (&Flt == &APFloat::IEEEsingle()) 12078 return DenormMode == DenormalMode::getPreserveSign(); 12079 return DenormMode == DenormalMode::getIEEE(); 12080 } 12081 12082 TargetLowering::AtomicExpansionKind 12083 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12084 switch (RMW->getOperation()) { 12085 case AtomicRMWInst::FAdd: { 12086 Type *Ty = RMW->getType(); 12087 12088 // We don't have a way to support 16-bit atomics now, so just leave them 12089 // as-is. 12090 if (Ty->isHalfTy()) 12091 return AtomicExpansionKind::None; 12092 12093 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12094 return AtomicExpansionKind::CmpXChg; 12095 12096 unsigned AS = RMW->getPointerAddressSpace(); 12097 12098 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12099 Subtarget->hasAtomicFaddInsts()) { 12100 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12101 // floating point atomic instructions. May generate more efficient code, 12102 // but may not respect rounding and denormal modes, and may give incorrect 12103 // results for certain memory destinations. 12104 if (RMW->getFunction() 12105 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12106 .getValueAsString() != "true") 12107 return AtomicExpansionKind::CmpXChg; 12108 12109 if (Subtarget->hasGFX90AInsts()) { 12110 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12111 return AtomicExpansionKind::CmpXChg; 12112 12113 auto SSID = RMW->getSyncScopeID(); 12114 if (SSID == SyncScope::System || 12115 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12116 return AtomicExpansionKind::CmpXChg; 12117 12118 return AtomicExpansionKind::None; 12119 } 12120 12121 if (AS == AMDGPUAS::FLAT_ADDRESS) 12122 return AtomicExpansionKind::CmpXChg; 12123 12124 return RMW->use_empty() ? AtomicExpansionKind::None 12125 : AtomicExpansionKind::CmpXChg; 12126 } 12127 12128 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12129 // to round-to-nearest-even. 12130 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12131 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 12132 if (!Ty->isDoubleTy()) 12133 return AtomicExpansionKind::None; 12134 12135 return (fpModeMatchesGlobalFPAtomicMode(RMW) || 12136 RMW->getFunction() 12137 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12138 .getValueAsString() == "true") 12139 ? AtomicExpansionKind::None 12140 : AtomicExpansionKind::CmpXChg; 12141 } 12142 12143 return AtomicExpansionKind::CmpXChg; 12144 } 12145 default: 12146 break; 12147 } 12148 12149 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12150 } 12151 12152 const TargetRegisterClass * 12153 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12154 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12155 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12156 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12157 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12158 : &AMDGPU::SReg_32RegClass; 12159 if (!TRI->isSGPRClass(RC) && !isDivergent) 12160 return TRI->getEquivalentSGPRClass(RC); 12161 else if (TRI->isSGPRClass(RC) && isDivergent) 12162 return TRI->getEquivalentVGPRClass(RC); 12163 12164 return RC; 12165 } 12166 12167 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12168 // uniform values (as produced by the mask results of control flow intrinsics) 12169 // used outside of divergent blocks. The phi users need to also be treated as 12170 // always uniform. 12171 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12172 unsigned WaveSize) { 12173 // FIXME: We asssume we never cast the mask results of a control flow 12174 // intrinsic. 12175 // Early exit if the type won't be consistent as a compile time hack. 12176 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12177 if (!IT || IT->getBitWidth() != WaveSize) 12178 return false; 12179 12180 if (!isa<Instruction>(V)) 12181 return false; 12182 if (!Visited.insert(V).second) 12183 return false; 12184 bool Result = false; 12185 for (auto U : V->users()) { 12186 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12187 if (V == U->getOperand(1)) { 12188 switch (Intrinsic->getIntrinsicID()) { 12189 default: 12190 Result = false; 12191 break; 12192 case Intrinsic::amdgcn_if_break: 12193 case Intrinsic::amdgcn_if: 12194 case Intrinsic::amdgcn_else: 12195 Result = true; 12196 break; 12197 } 12198 } 12199 if (V == U->getOperand(0)) { 12200 switch (Intrinsic->getIntrinsicID()) { 12201 default: 12202 Result = false; 12203 break; 12204 case Intrinsic::amdgcn_end_cf: 12205 case Intrinsic::amdgcn_loop: 12206 Result = true; 12207 break; 12208 } 12209 } 12210 } else { 12211 Result = hasCFUser(U, Visited, WaveSize); 12212 } 12213 if (Result) 12214 break; 12215 } 12216 return Result; 12217 } 12218 12219 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12220 const Value *V) const { 12221 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12222 if (CI->isInlineAsm()) { 12223 // FIXME: This cannot give a correct answer. This should only trigger in 12224 // the case where inline asm returns mixed SGPR and VGPR results, used 12225 // outside the defining block. We don't have a specific result to 12226 // consider, so this assumes if any value is SGPR, the overall register 12227 // also needs to be SGPR. 12228 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12229 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12230 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12231 for (auto &TC : TargetConstraints) { 12232 if (TC.Type == InlineAsm::isOutput) { 12233 ComputeConstraintToUse(TC, SDValue()); 12234 unsigned AssignedReg; 12235 const TargetRegisterClass *RC; 12236 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12237 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12238 if (RC) { 12239 MachineRegisterInfo &MRI = MF.getRegInfo(); 12240 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12241 return true; 12242 else if (SIRI->isSGPRClass(RC)) 12243 return true; 12244 } 12245 } 12246 } 12247 } 12248 } 12249 SmallPtrSet<const Value *, 16> Visited; 12250 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12251 } 12252 12253 std::pair<InstructionCost, MVT> 12254 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12255 Type *Ty) const { 12256 std::pair<InstructionCost, MVT> Cost = 12257 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12258 auto Size = DL.getTypeSizeInBits(Ty); 12259 // Maximum load or store can handle 8 dwords for scalar and 4 for 12260 // vector ALU. Let's assume anything above 8 dwords is expensive 12261 // even if legal. 12262 if (Size <= 256) 12263 return Cost; 12264 12265 Cost.first = (Size + 255) / 256; 12266 return Cost; 12267 } 12268