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/FloatingPointMode.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/BinaryFormat/ELF.h" 25 #include "llvm/CodeGen/Analysis.h" 26 #include "llvm/CodeGen/FunctionLoweringInfo.h" 27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineLoopInfo.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/IntrinsicInst.h" 33 #include "llvm/IR/IntrinsicsAMDGPU.h" 34 #include "llvm/IR/IntrinsicsR600.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/KnownBits.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "si-lower" 41 42 STATISTIC(NumTailCalls, "Number of tail calls"); 43 44 static cl::opt<bool> DisableLoopAlignment( 45 "amdgpu-disable-loop-alignment", 46 cl::desc("Do not align and prefetch loops"), 47 cl::init(false)); 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 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 140 } 141 142 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 143 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 144 145 computeRegisterProperties(Subtarget->getRegisterInfo()); 146 147 // The boolean content concept here is too inflexible. Compares only ever 148 // really produce a 1-bit result. Any copy/extend from these will turn into a 149 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 150 // it's what most targets use. 151 setBooleanContents(ZeroOrOneBooleanContent); 152 setBooleanVectorContents(ZeroOrOneBooleanContent); 153 154 // We need to custom lower vector stores from local memory 155 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 174 setOperationAction(ISD::STORE, MVT::i1, Custom); 175 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 176 177 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 178 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 179 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 180 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 181 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 182 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 183 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 184 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 185 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 186 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 187 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 188 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 189 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 190 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 191 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 192 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 193 194 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 195 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 196 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 197 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 200 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 201 202 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 203 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 204 205 setOperationAction(ISD::SELECT, MVT::i1, Promote); 206 setOperationAction(ISD::SELECT, MVT::i64, Custom); 207 setOperationAction(ISD::SELECT, MVT::f64, Promote); 208 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 209 210 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 215 216 setOperationAction(ISD::SETCC, MVT::i1, Promote); 217 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 218 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 219 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 220 221 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 222 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 223 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 224 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 225 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 227 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 228 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 229 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 230 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 231 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 232 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 233 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 234 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 235 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 236 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 237 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 246 247 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 248 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 249 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 251 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 253 254 setOperationAction(ISD::UADDO, MVT::i32, Legal); 255 setOperationAction(ISD::USUBO, MVT::i32, Legal); 256 257 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 258 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 259 260 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 261 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 263 264 #if 0 265 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 266 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 267 #endif 268 269 // We only support LOAD/STORE and vector manipulation ops for vectors 270 // with > 4 elements. 271 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 272 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 273 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 274 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 275 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 276 MVT::v32i32, MVT::v32f32 }) { 277 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 278 switch (Op) { 279 case ISD::LOAD: 280 case ISD::STORE: 281 case ISD::BUILD_VECTOR: 282 case ISD::BITCAST: 283 case ISD::EXTRACT_VECTOR_ELT: 284 case ISD::INSERT_VECTOR_ELT: 285 case ISD::EXTRACT_SUBVECTOR: 286 case ISD::SCALAR_TO_VECTOR: 287 break; 288 case ISD::INSERT_SUBVECTOR: 289 case ISD::CONCAT_VECTORS: 290 setOperationAction(Op, VT, Custom); 291 break; 292 default: 293 setOperationAction(Op, VT, Expand); 294 break; 295 } 296 } 297 } 298 299 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 300 301 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 302 // is expanded to avoid having two separate loops in case the index is a VGPR. 303 304 // Most operations are naturally 32-bit vector operations. We only support 305 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 306 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 307 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 308 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 309 310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 311 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 312 313 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 314 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 315 316 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 317 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 318 } 319 320 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 321 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 322 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 323 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 325 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 326 327 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 328 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 329 330 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 331 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 332 } 333 334 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 335 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 336 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 337 338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 339 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 340 341 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 342 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 343 344 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 345 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 346 } 347 348 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 349 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 350 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 351 352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 353 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 354 355 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 356 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 357 358 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 359 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 360 } 361 362 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 363 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 364 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 365 366 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 367 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 368 369 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 370 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 371 372 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 373 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 374 } 375 376 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 380 381 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 382 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 383 384 // Avoid stack access for these. 385 // TODO: Generalize to more vector types. 386 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 388 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 390 391 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 394 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 397 398 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 400 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 402 403 // Deal with vec3 vector operations when widened to vec4. 404 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 408 409 // Deal with vec5/6/7 vector operations when widened to vec8. 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 418 419 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 420 // and output demarshalling 421 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 423 424 // We can't return success/failure, only the old value, 425 // let LLVM add the comparison 426 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 428 429 if (Subtarget->hasFlatAddressSpace()) { 430 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 432 } 433 434 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 435 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 436 437 // FIXME: This should be narrowed to i32, but that only happens if i64 is 438 // illegal. 439 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 440 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 441 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 442 443 // On SI this is s_memtime and s_memrealtime on VI. 444 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 445 setOperationAction(ISD::TRAP, MVT::Other, Custom); 446 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 447 448 if (Subtarget->has16BitInsts()) { 449 setOperationAction(ISD::FPOW, MVT::f16, Promote); 450 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 451 setOperationAction(ISD::FLOG, MVT::f16, Custom); 452 setOperationAction(ISD::FEXP, MVT::f16, Custom); 453 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 454 } 455 456 if (Subtarget->hasMadMacF32Insts()) 457 setOperationAction(ISD::FMAD, MVT::f32, Legal); 458 459 if (!Subtarget->hasBFI()) { 460 // fcopysign can be done in a single instruction with BFI. 461 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 462 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 463 } 464 465 if (!Subtarget->hasBCNT(32)) 466 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 467 468 if (!Subtarget->hasBCNT(64)) 469 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 470 471 if (Subtarget->hasFFBH()) { 472 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 473 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 474 } 475 476 if (Subtarget->hasFFBL()) { 477 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 479 } 480 481 // We only really have 32-bit BFE instructions (and 16-bit on VI). 482 // 483 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 484 // effort to match them now. We want this to be false for i64 cases when the 485 // extraction isn't restricted to the upper or lower half. Ideally we would 486 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 487 // span the midpoint are probably relatively rare, so don't worry about them 488 // for now. 489 if (Subtarget->hasBFE()) 490 setHasExtractBitsInsn(true); 491 492 // Clamp modifier on add/sub 493 if (Subtarget->hasIntClamp()) { 494 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 495 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 496 } 497 498 if (Subtarget->hasAddNoCarry()) { 499 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 500 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 501 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 502 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 503 } 504 505 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 506 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 507 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 508 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 509 510 511 // These are really only legal for ieee_mode functions. We should be avoiding 512 // them for functions that don't have ieee_mode enabled, so just say they are 513 // legal. 514 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 515 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 516 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 517 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 518 519 520 if (Subtarget->haveRoundOpsF64()) { 521 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 522 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 523 setOperationAction(ISD::FRINT, MVT::f64, Legal); 524 } else { 525 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 526 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 527 setOperationAction(ISD::FRINT, MVT::f64, Custom); 528 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 529 } 530 531 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 532 533 setOperationAction(ISD::FSIN, MVT::f32, Custom); 534 setOperationAction(ISD::FCOS, MVT::f32, Custom); 535 setOperationAction(ISD::FDIV, MVT::f32, Custom); 536 setOperationAction(ISD::FDIV, MVT::f64, Custom); 537 538 if (Subtarget->has16BitInsts()) { 539 setOperationAction(ISD::Constant, MVT::i16, Legal); 540 541 setOperationAction(ISD::SMIN, MVT::i16, Legal); 542 setOperationAction(ISD::SMAX, MVT::i16, Legal); 543 544 setOperationAction(ISD::UMIN, MVT::i16, Legal); 545 setOperationAction(ISD::UMAX, MVT::i16, Legal); 546 547 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 548 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 549 550 setOperationAction(ISD::ROTR, MVT::i16, Expand); 551 setOperationAction(ISD::ROTL, MVT::i16, Expand); 552 553 setOperationAction(ISD::SDIV, MVT::i16, Promote); 554 setOperationAction(ISD::UDIV, MVT::i16, Promote); 555 setOperationAction(ISD::SREM, MVT::i16, Promote); 556 setOperationAction(ISD::UREM, MVT::i16, Promote); 557 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 558 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 559 560 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 561 562 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 564 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 566 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 567 568 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 569 570 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 571 572 setOperationAction(ISD::LOAD, MVT::i16, Custom); 573 574 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 575 576 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 577 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 578 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 579 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 580 581 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 582 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 583 584 // F16 - Constant Actions. 585 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 586 587 // F16 - Load/Store Actions. 588 setOperationAction(ISD::LOAD, MVT::f16, Promote); 589 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 590 setOperationAction(ISD::STORE, MVT::f16, Promote); 591 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 592 593 // F16 - VOP1 Actions. 594 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 595 setOperationAction(ISD::FCOS, MVT::f16, Custom); 596 setOperationAction(ISD::FSIN, MVT::f16, Custom); 597 598 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 599 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 600 601 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 602 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 603 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 604 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 605 setOperationAction(ISD::FROUND, MVT::f16, Custom); 606 setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom); 607 608 // F16 - VOP2 Actions. 609 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 610 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 611 612 setOperationAction(ISD::FDIV, MVT::f16, Custom); 613 614 // F16 - VOP3 Actions. 615 setOperationAction(ISD::FMA, MVT::f16, Legal); 616 if (STI.hasMadF16()) 617 setOperationAction(ISD::FMAD, MVT::f16, Legal); 618 619 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 620 MVT::v8f16}) { 621 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 622 switch (Op) { 623 case ISD::LOAD: 624 case ISD::STORE: 625 case ISD::BUILD_VECTOR: 626 case ISD::BITCAST: 627 case ISD::EXTRACT_VECTOR_ELT: 628 case ISD::INSERT_VECTOR_ELT: 629 case ISD::INSERT_SUBVECTOR: 630 case ISD::EXTRACT_SUBVECTOR: 631 case ISD::SCALAR_TO_VECTOR: 632 break; 633 case ISD::CONCAT_VECTORS: 634 setOperationAction(Op, VT, Custom); 635 break; 636 default: 637 setOperationAction(Op, VT, Expand); 638 break; 639 } 640 } 641 } 642 643 // v_perm_b32 can handle either of these. 644 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 645 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 646 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 647 648 // XXX - Do these do anything? Vector constants turn into build_vector. 649 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 650 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 651 652 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 653 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 654 655 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 656 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 657 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 658 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 659 660 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 661 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 662 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 663 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 664 665 setOperationAction(ISD::AND, MVT::v2i16, Promote); 666 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 667 setOperationAction(ISD::OR, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 669 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 670 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 671 672 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 673 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 674 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 675 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 676 677 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 678 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 679 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 680 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 681 682 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 683 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 684 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 685 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 686 687 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 688 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 689 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 690 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 691 692 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 693 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 694 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 695 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 696 697 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 698 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 699 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 700 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 701 702 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 703 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 704 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 705 706 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand); 707 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand); 708 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand); 709 710 if (!Subtarget->hasVOP3PInsts()) { 711 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 713 } 714 715 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 716 // This isn't really legal, but this avoids the legalizer unrolling it (and 717 // allows matching fneg (fabs x) patterns) 718 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 719 720 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 721 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 722 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 723 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 724 725 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 726 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom); 728 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom); 729 730 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 731 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 732 setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand); 733 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand); 734 735 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 736 setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom); 737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom); 738 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 739 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand); 740 } 741 } 742 743 if (Subtarget->hasVOP3PInsts()) { 744 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 745 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 746 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 747 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 750 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 751 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 753 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 754 755 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 756 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 759 760 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 761 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 763 764 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 765 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 766 767 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 768 769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 771 772 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 776 777 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 778 // Split vector operations. 779 setOperationAction(ISD::SHL, VT, Custom); 780 setOperationAction(ISD::SRA, VT, Custom); 781 setOperationAction(ISD::SRL, VT, Custom); 782 setOperationAction(ISD::ADD, VT, Custom); 783 setOperationAction(ISD::SUB, VT, Custom); 784 setOperationAction(ISD::MUL, VT, Custom); 785 786 setOperationAction(ISD::SMIN, VT, Custom); 787 setOperationAction(ISD::SMAX, VT, Custom); 788 setOperationAction(ISD::UMIN, VT, Custom); 789 setOperationAction(ISD::UMAX, VT, Custom); 790 791 setOperationAction(ISD::UADDSAT, VT, Custom); 792 setOperationAction(ISD::SADDSAT, VT, Custom); 793 setOperationAction(ISD::USUBSAT, VT, Custom); 794 setOperationAction(ISD::SSUBSAT, VT, Custom); 795 } 796 797 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 798 // Split vector operations. 799 setOperationAction(ISD::FADD, VT, Custom); 800 setOperationAction(ISD::FMUL, VT, Custom); 801 setOperationAction(ISD::FMA, VT, Custom); 802 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 803 } 804 805 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 806 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 807 808 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 809 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 810 811 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 812 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 814 815 if (Subtarget->hasPackedFP32Ops()) { 816 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 817 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 819 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 820 821 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 822 setOperationAction(ISD::FADD, VT, Custom); 823 setOperationAction(ISD::FMUL, VT, Custom); 824 setOperationAction(ISD::FMA, VT, Custom); 825 } 826 } 827 } 828 829 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 830 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 831 832 if (Subtarget->has16BitInsts()) { 833 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 834 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 835 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 836 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 837 } else { 838 // Legalization hack. 839 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 840 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 841 842 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 843 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 844 } 845 846 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 847 MVT::v8i16, MVT::v8f16 }) { 848 setOperationAction(ISD::SELECT, VT, Custom); 849 } 850 851 setOperationAction(ISD::SMULO, MVT::i64, Custom); 852 setOperationAction(ISD::UMULO, MVT::i64, Custom); 853 854 if (Subtarget->hasMad64_32()) { 855 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 856 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 857 } 858 859 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 866 867 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 878 879 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 889 890 setTargetDAGCombine(ISD::ADD); 891 setTargetDAGCombine(ISD::ADDCARRY); 892 setTargetDAGCombine(ISD::SUB); 893 setTargetDAGCombine(ISD::SUBCARRY); 894 setTargetDAGCombine(ISD::FADD); 895 setTargetDAGCombine(ISD::FSUB); 896 setTargetDAGCombine(ISD::FMINNUM); 897 setTargetDAGCombine(ISD::FMAXNUM); 898 setTargetDAGCombine(ISD::FMINNUM_IEEE); 899 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 900 setTargetDAGCombine(ISD::FMA); 901 setTargetDAGCombine(ISD::SMIN); 902 setTargetDAGCombine(ISD::SMAX); 903 setTargetDAGCombine(ISD::UMIN); 904 setTargetDAGCombine(ISD::UMAX); 905 setTargetDAGCombine(ISD::SETCC); 906 setTargetDAGCombine(ISD::AND); 907 setTargetDAGCombine(ISD::OR); 908 setTargetDAGCombine(ISD::XOR); 909 setTargetDAGCombine(ISD::SINT_TO_FP); 910 setTargetDAGCombine(ISD::UINT_TO_FP); 911 setTargetDAGCombine(ISD::FCANONICALIZE); 912 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 913 setTargetDAGCombine(ISD::ZERO_EXTEND); 914 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 915 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 916 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 917 918 // All memory operations. Some folding on the pointer operand is done to help 919 // matching the constant offsets in the addressing modes. 920 setTargetDAGCombine(ISD::LOAD); 921 setTargetDAGCombine(ISD::STORE); 922 setTargetDAGCombine(ISD::ATOMIC_LOAD); 923 setTargetDAGCombine(ISD::ATOMIC_STORE); 924 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 925 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 926 setTargetDAGCombine(ISD::ATOMIC_SWAP); 927 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 928 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 929 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 930 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 931 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 932 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 933 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 934 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 935 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 936 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 937 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 938 setTargetDAGCombine(ISD::INTRINSIC_VOID); 939 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 940 941 // FIXME: In other contexts we pretend this is a per-function property. 942 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 943 944 setSchedulingPreference(Sched::RegPressure); 945 } 946 947 const GCNSubtarget *SITargetLowering::getSubtarget() const { 948 return Subtarget; 949 } 950 951 //===----------------------------------------------------------------------===// 952 // TargetLowering queries 953 //===----------------------------------------------------------------------===// 954 955 // v_mad_mix* support a conversion from f16 to f32. 956 // 957 // There is only one special case when denormals are enabled we don't currently, 958 // where this is OK to use. 959 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 960 EVT DestVT, EVT SrcVT) const { 961 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 962 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 963 DestVT.getScalarType() == MVT::f32 && 964 SrcVT.getScalarType() == MVT::f16 && 965 // TODO: This probably only requires no input flushing? 966 !hasFP32Denormals(DAG.getMachineFunction()); 967 } 968 969 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 970 LLT DestTy, LLT SrcTy) const { 971 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 972 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 973 DestTy.getScalarSizeInBits() == 32 && 974 SrcTy.getScalarSizeInBits() == 16 && 975 // TODO: This probably only requires no input flushing? 976 !hasFP32Denormals(*MI.getMF()); 977 } 978 979 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 980 // SI has some legal vector types, but no legal vector operations. Say no 981 // shuffles are legal in order to prefer scalarizing some vector operations. 982 return false; 983 } 984 985 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 986 CallingConv::ID CC, 987 EVT VT) const { 988 if (CC == CallingConv::AMDGPU_KERNEL) 989 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 990 991 if (VT.isVector()) { 992 EVT ScalarVT = VT.getScalarType(); 993 unsigned Size = ScalarVT.getSizeInBits(); 994 if (Size == 16) { 995 if (Subtarget->has16BitInsts()) 996 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 997 return VT.isInteger() ? MVT::i32 : MVT::f32; 998 } 999 1000 if (Size < 16) 1001 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1002 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1003 } 1004 1005 if (VT.getSizeInBits() > 32) 1006 return MVT::i32; 1007 1008 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1009 } 1010 1011 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1012 CallingConv::ID CC, 1013 EVT VT) const { 1014 if (CC == CallingConv::AMDGPU_KERNEL) 1015 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1016 1017 if (VT.isVector()) { 1018 unsigned NumElts = VT.getVectorNumElements(); 1019 EVT ScalarVT = VT.getScalarType(); 1020 unsigned Size = ScalarVT.getSizeInBits(); 1021 1022 // FIXME: Should probably promote 8-bit vectors to i16. 1023 if (Size == 16 && Subtarget->has16BitInsts()) 1024 return (NumElts + 1) / 2; 1025 1026 if (Size <= 32) 1027 return NumElts; 1028 1029 if (Size > 32) 1030 return NumElts * ((Size + 31) / 32); 1031 } else if (VT.getSizeInBits() > 32) 1032 return (VT.getSizeInBits() + 31) / 32; 1033 1034 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1035 } 1036 1037 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1038 LLVMContext &Context, CallingConv::ID CC, 1039 EVT VT, EVT &IntermediateVT, 1040 unsigned &NumIntermediates, MVT &RegisterVT) const { 1041 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1042 unsigned NumElts = VT.getVectorNumElements(); 1043 EVT ScalarVT = VT.getScalarType(); 1044 unsigned Size = ScalarVT.getSizeInBits(); 1045 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1046 // support, but unless we can properly handle 3-vectors, it will be still be 1047 // inconsistent. 1048 if (Size == 16 && Subtarget->has16BitInsts()) { 1049 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1050 IntermediateVT = RegisterVT; 1051 NumIntermediates = (NumElts + 1) / 2; 1052 return NumIntermediates; 1053 } 1054 1055 if (Size == 32) { 1056 RegisterVT = ScalarVT.getSimpleVT(); 1057 IntermediateVT = RegisterVT; 1058 NumIntermediates = NumElts; 1059 return NumIntermediates; 1060 } 1061 1062 if (Size < 16 && Subtarget->has16BitInsts()) { 1063 // FIXME: Should probably form v2i16 pieces 1064 RegisterVT = MVT::i16; 1065 IntermediateVT = ScalarVT; 1066 NumIntermediates = NumElts; 1067 return NumIntermediates; 1068 } 1069 1070 1071 if (Size != 16 && Size <= 32) { 1072 RegisterVT = MVT::i32; 1073 IntermediateVT = ScalarVT; 1074 NumIntermediates = NumElts; 1075 return NumIntermediates; 1076 } 1077 1078 if (Size > 32) { 1079 RegisterVT = MVT::i32; 1080 IntermediateVT = RegisterVT; 1081 NumIntermediates = NumElts * ((Size + 31) / 32); 1082 return NumIntermediates; 1083 } 1084 } 1085 1086 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1087 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1088 } 1089 1090 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1091 assert(DMaskLanes != 0); 1092 1093 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1094 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1095 return EVT::getVectorVT(Ty->getContext(), 1096 EVT::getEVT(VT->getElementType()), 1097 NumElts); 1098 } 1099 1100 return EVT::getEVT(Ty); 1101 } 1102 1103 // Peek through TFE struct returns to only use the data size. 1104 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1105 auto *ST = dyn_cast<StructType>(Ty); 1106 if (!ST) 1107 return memVTFromImageData(Ty, DMaskLanes); 1108 1109 // Some intrinsics return an aggregate type - special case to work out the 1110 // correct memVT. 1111 // 1112 // Only limited forms of aggregate type currently expected. 1113 if (ST->getNumContainedTypes() != 2 || 1114 !ST->getContainedType(1)->isIntegerTy(32)) 1115 return EVT(); 1116 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1117 } 1118 1119 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1120 const CallInst &CI, 1121 MachineFunction &MF, 1122 unsigned IntrID) const { 1123 Info.flags = MachineMemOperand::MONone; 1124 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1125 Info.flags |= MachineMemOperand::MOInvariant; 1126 1127 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1128 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1129 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1130 (Intrinsic::ID)IntrID); 1131 if (Attr.hasFnAttr(Attribute::ReadNone)) 1132 return false; 1133 1134 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1135 1136 if (RsrcIntr->IsImage) { 1137 Info.ptrVal = 1138 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1139 Info.align.reset(); 1140 } else { 1141 Info.ptrVal = 1142 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1143 } 1144 1145 Info.flags |= MachineMemOperand::MODereferenceable; 1146 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1147 unsigned DMaskLanes = 4; 1148 1149 if (RsrcIntr->IsImage) { 1150 const AMDGPU::ImageDimIntrinsicInfo *Intr 1151 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1152 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1153 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1154 1155 if (!BaseOpcode->Gather4) { 1156 // If this isn't a gather, we may have excess loaded elements in the 1157 // IR type. Check the dmask for the real number of elements loaded. 1158 unsigned DMask 1159 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1160 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1161 } 1162 1163 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1164 } else 1165 Info.memVT = EVT::getEVT(CI.getType()); 1166 1167 // FIXME: What does alignment mean for an image? 1168 Info.opc = ISD::INTRINSIC_W_CHAIN; 1169 Info.flags |= MachineMemOperand::MOLoad; 1170 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1171 Info.opc = ISD::INTRINSIC_VOID; 1172 1173 Type *DataTy = CI.getArgOperand(0)->getType(); 1174 if (RsrcIntr->IsImage) { 1175 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1176 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1177 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1178 } else 1179 Info.memVT = EVT::getEVT(DataTy); 1180 1181 Info.flags |= MachineMemOperand::MOStore; 1182 } else { 1183 // Atomic 1184 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1185 ISD::INTRINSIC_W_CHAIN; 1186 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1187 Info.flags |= MachineMemOperand::MOLoad | 1188 MachineMemOperand::MOStore | 1189 MachineMemOperand::MODereferenceable; 1190 1191 // XXX - Should this be volatile without known ordering? 1192 Info.flags |= MachineMemOperand::MOVolatile; 1193 } 1194 return true; 1195 } 1196 1197 switch (IntrID) { 1198 case Intrinsic::amdgcn_atomic_inc: 1199 case Intrinsic::amdgcn_atomic_dec: 1200 case Intrinsic::amdgcn_ds_ordered_add: 1201 case Intrinsic::amdgcn_ds_ordered_swap: 1202 case Intrinsic::amdgcn_ds_fadd: 1203 case Intrinsic::amdgcn_ds_fmin: 1204 case Intrinsic::amdgcn_ds_fmax: { 1205 Info.opc = ISD::INTRINSIC_W_CHAIN; 1206 Info.memVT = MVT::getVT(CI.getType()); 1207 Info.ptrVal = CI.getOperand(0); 1208 Info.align.reset(); 1209 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1210 1211 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1212 if (!Vol->isZero()) 1213 Info.flags |= MachineMemOperand::MOVolatile; 1214 1215 return true; 1216 } 1217 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1218 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1219 1220 Info.opc = ISD::INTRINSIC_W_CHAIN; 1221 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1222 Info.ptrVal = 1223 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1224 Info.align.reset(); 1225 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1226 1227 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1228 if (!Vol || !Vol->isZero()) 1229 Info.flags |= MachineMemOperand::MOVolatile; 1230 1231 return true; 1232 } 1233 case Intrinsic::amdgcn_ds_append: 1234 case Intrinsic::amdgcn_ds_consume: { 1235 Info.opc = ISD::INTRINSIC_W_CHAIN; 1236 Info.memVT = MVT::getVT(CI.getType()); 1237 Info.ptrVal = CI.getOperand(0); 1238 Info.align.reset(); 1239 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1240 1241 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1242 if (!Vol->isZero()) 1243 Info.flags |= MachineMemOperand::MOVolatile; 1244 1245 return true; 1246 } 1247 case Intrinsic::amdgcn_global_atomic_csub: { 1248 Info.opc = ISD::INTRINSIC_W_CHAIN; 1249 Info.memVT = MVT::getVT(CI.getType()); 1250 Info.ptrVal = CI.getOperand(0); 1251 Info.align.reset(); 1252 Info.flags |= MachineMemOperand::MOLoad | 1253 MachineMemOperand::MOStore | 1254 MachineMemOperand::MOVolatile; 1255 return true; 1256 } 1257 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1258 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1259 Info.opc = ISD::INTRINSIC_W_CHAIN; 1260 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1261 Info.ptrVal = 1262 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1263 Info.align.reset(); 1264 Info.flags |= MachineMemOperand::MOLoad | 1265 MachineMemOperand::MODereferenceable; 1266 return true; 1267 } 1268 case Intrinsic::amdgcn_global_atomic_fadd: 1269 case Intrinsic::amdgcn_global_atomic_fmin: 1270 case Intrinsic::amdgcn_global_atomic_fmax: 1271 case Intrinsic::amdgcn_flat_atomic_fadd: 1272 case Intrinsic::amdgcn_flat_atomic_fmin: 1273 case Intrinsic::amdgcn_flat_atomic_fmax: 1274 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1275 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1276 Info.opc = ISD::INTRINSIC_W_CHAIN; 1277 Info.memVT = MVT::getVT(CI.getType()); 1278 Info.ptrVal = CI.getOperand(0); 1279 Info.align.reset(); 1280 Info.flags |= MachineMemOperand::MOLoad | 1281 MachineMemOperand::MOStore | 1282 MachineMemOperand::MODereferenceable | 1283 MachineMemOperand::MOVolatile; 1284 return true; 1285 } 1286 case Intrinsic::amdgcn_ds_gws_init: 1287 case Intrinsic::amdgcn_ds_gws_barrier: 1288 case Intrinsic::amdgcn_ds_gws_sema_v: 1289 case Intrinsic::amdgcn_ds_gws_sema_br: 1290 case Intrinsic::amdgcn_ds_gws_sema_p: 1291 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1292 Info.opc = ISD::INTRINSIC_VOID; 1293 1294 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1295 Info.ptrVal = 1296 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1297 1298 // This is an abstract access, but we need to specify a type and size. 1299 Info.memVT = MVT::i32; 1300 Info.size = 4; 1301 Info.align = Align(4); 1302 1303 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1304 Info.flags |= MachineMemOperand::MOLoad; 1305 else 1306 Info.flags |= MachineMemOperand::MOStore; 1307 return true; 1308 } 1309 default: 1310 return false; 1311 } 1312 } 1313 1314 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1315 SmallVectorImpl<Value*> &Ops, 1316 Type *&AccessTy) const { 1317 switch (II->getIntrinsicID()) { 1318 case Intrinsic::amdgcn_atomic_inc: 1319 case Intrinsic::amdgcn_atomic_dec: 1320 case Intrinsic::amdgcn_ds_ordered_add: 1321 case Intrinsic::amdgcn_ds_ordered_swap: 1322 case Intrinsic::amdgcn_ds_append: 1323 case Intrinsic::amdgcn_ds_consume: 1324 case Intrinsic::amdgcn_ds_fadd: 1325 case Intrinsic::amdgcn_ds_fmin: 1326 case Intrinsic::amdgcn_ds_fmax: 1327 case Intrinsic::amdgcn_global_atomic_fadd: 1328 case Intrinsic::amdgcn_flat_atomic_fadd: 1329 case Intrinsic::amdgcn_flat_atomic_fmin: 1330 case Intrinsic::amdgcn_flat_atomic_fmax: 1331 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1332 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1333 case Intrinsic::amdgcn_global_atomic_csub: { 1334 Value *Ptr = II->getArgOperand(0); 1335 AccessTy = II->getType(); 1336 Ops.push_back(Ptr); 1337 return true; 1338 } 1339 default: 1340 return false; 1341 } 1342 } 1343 1344 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1345 if (!Subtarget->hasFlatInstOffsets()) { 1346 // Flat instructions do not have offsets, and only have the register 1347 // address. 1348 return AM.BaseOffs == 0 && AM.Scale == 0; 1349 } 1350 1351 return AM.Scale == 0 && 1352 (AM.BaseOffs == 0 || 1353 Subtarget->getInstrInfo()->isLegalFLATOffset( 1354 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1355 } 1356 1357 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1358 if (Subtarget->hasFlatGlobalInsts()) 1359 return AM.Scale == 0 && 1360 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1361 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1362 SIInstrFlags::FlatGlobal)); 1363 1364 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1365 // Assume the we will use FLAT for all global memory accesses 1366 // on VI. 1367 // FIXME: This assumption is currently wrong. On VI we still use 1368 // MUBUF instructions for the r + i addressing mode. As currently 1369 // implemented, the MUBUF instructions only work on buffer < 4GB. 1370 // It may be possible to support > 4GB buffers with MUBUF instructions, 1371 // by setting the stride value in the resource descriptor which would 1372 // increase the size limit to (stride * 4GB). However, this is risky, 1373 // because it has never been validated. 1374 return isLegalFlatAddressingMode(AM); 1375 } 1376 1377 return isLegalMUBUFAddressingMode(AM); 1378 } 1379 1380 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1381 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1382 // additionally can do r + r + i with addr64. 32-bit has more addressing 1383 // mode options. Depending on the resource constant, it can also do 1384 // (i64 r0) + (i32 r1) * (i14 i). 1385 // 1386 // Private arrays end up using a scratch buffer most of the time, so also 1387 // assume those use MUBUF instructions. Scratch loads / stores are currently 1388 // implemented as mubuf instructions with offen bit set, so slightly 1389 // different than the normal addr64. 1390 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1391 return false; 1392 1393 // FIXME: Since we can split immediate into soffset and immediate offset, 1394 // would it make sense to allow any immediate? 1395 1396 switch (AM.Scale) { 1397 case 0: // r + i or just i, depending on HasBaseReg. 1398 return true; 1399 case 1: 1400 return true; // We have r + r or r + i. 1401 case 2: 1402 if (AM.HasBaseReg) { 1403 // Reject 2 * r + r. 1404 return false; 1405 } 1406 1407 // Allow 2 * r as r + r 1408 // Or 2 * r + i is allowed as r + r + i. 1409 return true; 1410 default: // Don't allow n * r 1411 return false; 1412 } 1413 } 1414 1415 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1416 const AddrMode &AM, Type *Ty, 1417 unsigned AS, Instruction *I) const { 1418 // No global is ever allowed as a base. 1419 if (AM.BaseGV) 1420 return false; 1421 1422 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1423 return isLegalGlobalAddressingMode(AM); 1424 1425 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1426 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1427 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1428 // If the offset isn't a multiple of 4, it probably isn't going to be 1429 // correctly aligned. 1430 // FIXME: Can we get the real alignment here? 1431 if (AM.BaseOffs % 4 != 0) 1432 return isLegalMUBUFAddressingMode(AM); 1433 1434 // There are no SMRD extloads, so if we have to do a small type access we 1435 // will use a MUBUF load. 1436 // FIXME?: We also need to do this if unaligned, but we don't know the 1437 // alignment here. 1438 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1439 return isLegalGlobalAddressingMode(AM); 1440 1441 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1442 // SMRD instructions have an 8-bit, dword offset on SI. 1443 if (!isUInt<8>(AM.BaseOffs / 4)) 1444 return false; 1445 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1446 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1447 // in 8-bits, it can use a smaller encoding. 1448 if (!isUInt<32>(AM.BaseOffs / 4)) 1449 return false; 1450 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1451 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1452 if (!isUInt<20>(AM.BaseOffs)) 1453 return false; 1454 } else 1455 llvm_unreachable("unhandled generation"); 1456 1457 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1458 return true; 1459 1460 if (AM.Scale == 1 && AM.HasBaseReg) 1461 return true; 1462 1463 return false; 1464 1465 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1466 return isLegalMUBUFAddressingMode(AM); 1467 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1468 AS == AMDGPUAS::REGION_ADDRESS) { 1469 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1470 // field. 1471 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1472 // an 8-bit dword offset but we don't know the alignment here. 1473 if (!isUInt<16>(AM.BaseOffs)) 1474 return false; 1475 1476 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1477 return true; 1478 1479 if (AM.Scale == 1 && AM.HasBaseReg) 1480 return true; 1481 1482 return false; 1483 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1484 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1485 // For an unknown address space, this usually means that this is for some 1486 // reason being used for pure arithmetic, and not based on some addressing 1487 // computation. We don't have instructions that compute pointers with any 1488 // addressing modes, so treat them as having no offset like flat 1489 // instructions. 1490 return isLegalFlatAddressingMode(AM); 1491 } 1492 1493 // Assume a user alias of global for unknown address spaces. 1494 return isLegalGlobalAddressingMode(AM); 1495 } 1496 1497 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1498 const MachineFunction &MF) const { 1499 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1500 return (MemVT.getSizeInBits() <= 4 * 32); 1501 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1502 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1503 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1504 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1505 return (MemVT.getSizeInBits() <= 2 * 32); 1506 } 1507 return true; 1508 } 1509 1510 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1511 unsigned Size, unsigned AddrSpace, Align Alignment, 1512 MachineMemOperand::Flags Flags, bool *IsFast) const { 1513 if (IsFast) 1514 *IsFast = false; 1515 1516 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1517 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1518 // Check if alignment requirements for ds_read/write instructions are 1519 // disabled. 1520 if (Subtarget->hasUnalignedDSAccessEnabled() && 1521 !Subtarget->hasLDSMisalignedBug()) { 1522 if (IsFast) 1523 *IsFast = Alignment != Align(2); 1524 return true; 1525 } 1526 1527 // Either, the alignment requirements are "enabled", or there is an 1528 // unaligned LDS access related hardware bug though alignment requirements 1529 // are "disabled". In either case, we need to check for proper alignment 1530 // requirements. 1531 // 1532 if (Size == 64) { 1533 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1534 // can do a 4 byte aligned, 8 byte access in a single operation using 1535 // ds_read2/write2_b32 with adjacent offsets. 1536 bool AlignedBy4 = Alignment >= Align(4); 1537 if (IsFast) 1538 *IsFast = AlignedBy4; 1539 1540 return AlignedBy4; 1541 } 1542 if (Size == 96) { 1543 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1544 // gfx8 and older. 1545 bool AlignedBy16 = Alignment >= Align(16); 1546 if (IsFast) 1547 *IsFast = AlignedBy16; 1548 1549 return AlignedBy16; 1550 } 1551 if (Size == 128) { 1552 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1553 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1554 // single operation using ds_read2/write2_b64. 1555 bool AlignedBy8 = Alignment >= Align(8); 1556 if (IsFast) 1557 *IsFast = AlignedBy8; 1558 1559 return AlignedBy8; 1560 } 1561 } 1562 1563 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1564 bool AlignedBy4 = Alignment >= Align(4); 1565 if (IsFast) 1566 *IsFast = AlignedBy4; 1567 1568 return AlignedBy4 || 1569 Subtarget->enableFlatScratch() || 1570 Subtarget->hasUnalignedScratchAccess(); 1571 } 1572 1573 // FIXME: We have to be conservative here and assume that flat operations 1574 // will access scratch. If we had access to the IR function, then we 1575 // could determine if any private memory was used in the function. 1576 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1577 !Subtarget->hasUnalignedScratchAccess()) { 1578 bool AlignedBy4 = Alignment >= Align(4); 1579 if (IsFast) 1580 *IsFast = AlignedBy4; 1581 1582 return AlignedBy4; 1583 } 1584 1585 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1586 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1587 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1588 // If we have a uniform constant load, it still requires using a slow 1589 // buffer instruction if unaligned. 1590 if (IsFast) { 1591 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1592 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1593 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1594 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1595 Alignment >= Align(4) : Alignment != Align(2); 1596 } 1597 1598 return true; 1599 } 1600 1601 // Smaller than dword value must be aligned. 1602 if (Size < 32) 1603 return false; 1604 1605 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1606 // byte-address are ignored, thus forcing Dword alignment. 1607 // This applies to private, global, and constant memory. 1608 if (IsFast) 1609 *IsFast = true; 1610 1611 return Size >= 32 && Alignment >= Align(4); 1612 } 1613 1614 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1615 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1616 bool *IsFast) const { 1617 if (IsFast) 1618 *IsFast = false; 1619 1620 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1621 // which isn't a simple VT. 1622 // Until MVT is extended to handle this, simply check for the size and 1623 // rely on the condition below: allow accesses if the size is a multiple of 4. 1624 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1625 VT.getStoreSize() > 16)) { 1626 return false; 1627 } 1628 1629 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1630 Alignment, Flags, IsFast); 1631 } 1632 1633 EVT SITargetLowering::getOptimalMemOpType( 1634 const MemOp &Op, const AttributeList &FuncAttributes) const { 1635 // FIXME: Should account for address space here. 1636 1637 // The default fallback uses the private pointer size as a guess for a type to 1638 // use. Make sure we switch these to 64-bit accesses. 1639 1640 if (Op.size() >= 16 && 1641 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1642 return MVT::v4i32; 1643 1644 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1645 return MVT::v2i32; 1646 1647 // Use the default. 1648 return MVT::Other; 1649 } 1650 1651 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1652 const MemSDNode *MemNode = cast<MemSDNode>(N); 1653 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1654 } 1655 1656 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1657 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1658 AS == AMDGPUAS::PRIVATE_ADDRESS; 1659 } 1660 1661 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1662 unsigned DestAS) const { 1663 // Flat -> private/local is a simple truncate. 1664 // Flat -> global is no-op 1665 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1666 return true; 1667 1668 const GCNTargetMachine &TM = 1669 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1670 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1671 } 1672 1673 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1674 const MemSDNode *MemNode = cast<MemSDNode>(N); 1675 1676 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1677 } 1678 1679 TargetLoweringBase::LegalizeTypeAction 1680 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1681 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1682 VT.getScalarType().bitsLE(MVT::i16)) 1683 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1684 return TargetLoweringBase::getPreferredVectorAction(VT); 1685 } 1686 1687 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1688 Type *Ty) const { 1689 // FIXME: Could be smarter if called for vector constants. 1690 return true; 1691 } 1692 1693 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1694 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1695 switch (Op) { 1696 case ISD::LOAD: 1697 case ISD::STORE: 1698 1699 // These operations are done with 32-bit instructions anyway. 1700 case ISD::AND: 1701 case ISD::OR: 1702 case ISD::XOR: 1703 case ISD::SELECT: 1704 // TODO: Extensions? 1705 return true; 1706 default: 1707 return false; 1708 } 1709 } 1710 1711 // SimplifySetCC uses this function to determine whether or not it should 1712 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1713 if (VT == MVT::i1 && Op == ISD::SETCC) 1714 return false; 1715 1716 return TargetLowering::isTypeDesirableForOp(Op, VT); 1717 } 1718 1719 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1720 const SDLoc &SL, 1721 SDValue Chain, 1722 uint64_t Offset) const { 1723 const DataLayout &DL = DAG.getDataLayout(); 1724 MachineFunction &MF = DAG.getMachineFunction(); 1725 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1726 1727 const ArgDescriptor *InputPtrReg; 1728 const TargetRegisterClass *RC; 1729 LLT ArgTy; 1730 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1731 1732 std::tie(InputPtrReg, RC, ArgTy) = 1733 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1734 1735 // We may not have the kernarg segment argument if we have no kernel 1736 // arguments. 1737 if (!InputPtrReg) 1738 return DAG.getConstant(0, SL, PtrVT); 1739 1740 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1741 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1742 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1743 1744 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1745 } 1746 1747 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1748 const SDLoc &SL) const { 1749 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1750 FIRST_IMPLICIT); 1751 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1752 } 1753 1754 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1755 const SDLoc &SL, SDValue Val, 1756 bool Signed, 1757 const ISD::InputArg *Arg) const { 1758 // First, if it is a widened vector, narrow it. 1759 if (VT.isVector() && 1760 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1761 EVT NarrowedVT = 1762 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1763 VT.getVectorNumElements()); 1764 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1765 DAG.getConstant(0, SL, MVT::i32)); 1766 } 1767 1768 // Then convert the vector elements or scalar value. 1769 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1770 VT.bitsLT(MemVT)) { 1771 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1772 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1773 } 1774 1775 if (MemVT.isFloatingPoint()) 1776 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1777 else if (Signed) 1778 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1779 else 1780 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1781 1782 return Val; 1783 } 1784 1785 SDValue SITargetLowering::lowerKernargMemParameter( 1786 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1787 uint64_t Offset, Align Alignment, bool Signed, 1788 const ISD::InputArg *Arg) const { 1789 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1790 1791 // Try to avoid using an extload by loading earlier than the argument address, 1792 // and extracting the relevant bits. The load should hopefully be merged with 1793 // the previous argument. 1794 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1795 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1796 int64_t AlignDownOffset = alignDown(Offset, 4); 1797 int64_t OffsetDiff = Offset - AlignDownOffset; 1798 1799 EVT IntVT = MemVT.changeTypeToInteger(); 1800 1801 // TODO: If we passed in the base kernel offset we could have a better 1802 // alignment than 4, but we don't really need it. 1803 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1804 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1805 MachineMemOperand::MODereferenceable | 1806 MachineMemOperand::MOInvariant); 1807 1808 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1809 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1810 1811 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1812 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1813 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1814 1815 1816 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1817 } 1818 1819 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1820 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1821 MachineMemOperand::MODereferenceable | 1822 MachineMemOperand::MOInvariant); 1823 1824 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1825 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1826 } 1827 1828 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1829 const SDLoc &SL, SDValue Chain, 1830 const ISD::InputArg &Arg) const { 1831 MachineFunction &MF = DAG.getMachineFunction(); 1832 MachineFrameInfo &MFI = MF.getFrameInfo(); 1833 1834 if (Arg.Flags.isByVal()) { 1835 unsigned Size = Arg.Flags.getByValSize(); 1836 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1837 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1838 } 1839 1840 unsigned ArgOffset = VA.getLocMemOffset(); 1841 unsigned ArgSize = VA.getValVT().getStoreSize(); 1842 1843 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1844 1845 // Create load nodes to retrieve arguments from the stack. 1846 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1847 SDValue ArgValue; 1848 1849 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1850 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1851 MVT MemVT = VA.getValVT(); 1852 1853 switch (VA.getLocInfo()) { 1854 default: 1855 break; 1856 case CCValAssign::BCvt: 1857 MemVT = VA.getLocVT(); 1858 break; 1859 case CCValAssign::SExt: 1860 ExtType = ISD::SEXTLOAD; 1861 break; 1862 case CCValAssign::ZExt: 1863 ExtType = ISD::ZEXTLOAD; 1864 break; 1865 case CCValAssign::AExt: 1866 ExtType = ISD::EXTLOAD; 1867 break; 1868 } 1869 1870 ArgValue = DAG.getExtLoad( 1871 ExtType, SL, VA.getLocVT(), Chain, FIN, 1872 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1873 MemVT); 1874 return ArgValue; 1875 } 1876 1877 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1878 const SIMachineFunctionInfo &MFI, 1879 EVT VT, 1880 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1881 const ArgDescriptor *Reg; 1882 const TargetRegisterClass *RC; 1883 LLT Ty; 1884 1885 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1886 if (!Reg) { 1887 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1888 // It's possible for a kernarg intrinsic call to appear in a kernel with 1889 // no allocated segment, in which case we do not add the user sgpr 1890 // argument, so just return null. 1891 return DAG.getConstant(0, SDLoc(), VT); 1892 } 1893 1894 // It's undefined behavior if a function marked with the amdgpu-no-* 1895 // attributes uses the corresponding intrinsic. 1896 return DAG.getUNDEF(VT); 1897 } 1898 1899 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1900 } 1901 1902 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1903 CallingConv::ID CallConv, 1904 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1905 FunctionType *FType, 1906 SIMachineFunctionInfo *Info) { 1907 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1908 const ISD::InputArg *Arg = &Ins[I]; 1909 1910 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1911 "vector type argument should have been split"); 1912 1913 // First check if it's a PS input addr. 1914 if (CallConv == CallingConv::AMDGPU_PS && 1915 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1916 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1917 1918 // Inconveniently only the first part of the split is marked as isSplit, 1919 // so skip to the end. We only want to increment PSInputNum once for the 1920 // entire split argument. 1921 if (Arg->Flags.isSplit()) { 1922 while (!Arg->Flags.isSplitEnd()) { 1923 assert((!Arg->VT.isVector() || 1924 Arg->VT.getScalarSizeInBits() == 16) && 1925 "unexpected vector split in ps argument type"); 1926 if (!SkipArg) 1927 Splits.push_back(*Arg); 1928 Arg = &Ins[++I]; 1929 } 1930 } 1931 1932 if (SkipArg) { 1933 // We can safely skip PS inputs. 1934 Skipped.set(Arg->getOrigArgIndex()); 1935 ++PSInputNum; 1936 continue; 1937 } 1938 1939 Info->markPSInputAllocated(PSInputNum); 1940 if (Arg->Used) 1941 Info->markPSInputEnabled(PSInputNum); 1942 1943 ++PSInputNum; 1944 } 1945 1946 Splits.push_back(*Arg); 1947 } 1948 } 1949 1950 // Allocate special inputs passed in VGPRs. 1951 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1952 MachineFunction &MF, 1953 const SIRegisterInfo &TRI, 1954 SIMachineFunctionInfo &Info) const { 1955 const LLT S32 = LLT::scalar(32); 1956 MachineRegisterInfo &MRI = MF.getRegInfo(); 1957 1958 if (Info.hasWorkItemIDX()) { 1959 Register Reg = AMDGPU::VGPR0; 1960 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1961 1962 CCInfo.AllocateReg(Reg); 1963 unsigned Mask = (Subtarget->hasPackedTID() && 1964 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1965 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1966 } 1967 1968 if (Info.hasWorkItemIDY()) { 1969 assert(Info.hasWorkItemIDX()); 1970 if (Subtarget->hasPackedTID()) { 1971 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1972 0x3ff << 10)); 1973 } else { 1974 unsigned Reg = AMDGPU::VGPR1; 1975 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1976 1977 CCInfo.AllocateReg(Reg); 1978 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1979 } 1980 } 1981 1982 if (Info.hasWorkItemIDZ()) { 1983 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1984 if (Subtarget->hasPackedTID()) { 1985 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1986 0x3ff << 20)); 1987 } else { 1988 unsigned Reg = AMDGPU::VGPR2; 1989 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1990 1991 CCInfo.AllocateReg(Reg); 1992 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1993 } 1994 } 1995 } 1996 1997 // Try to allocate a VGPR at the end of the argument list, or if no argument 1998 // VGPRs are left allocating a stack slot. 1999 // If \p Mask is is given it indicates bitfield position in the register. 2000 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2001 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2002 ArgDescriptor Arg = ArgDescriptor()) { 2003 if (Arg.isSet()) 2004 return ArgDescriptor::createArg(Arg, Mask); 2005 2006 ArrayRef<MCPhysReg> ArgVGPRs 2007 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2008 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2009 if (RegIdx == ArgVGPRs.size()) { 2010 // Spill to stack required. 2011 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2012 2013 return ArgDescriptor::createStack(Offset, Mask); 2014 } 2015 2016 unsigned Reg = ArgVGPRs[RegIdx]; 2017 Reg = CCInfo.AllocateReg(Reg); 2018 assert(Reg != AMDGPU::NoRegister); 2019 2020 MachineFunction &MF = CCInfo.getMachineFunction(); 2021 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2022 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2023 return ArgDescriptor::createRegister(Reg, Mask); 2024 } 2025 2026 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2027 const TargetRegisterClass *RC, 2028 unsigned NumArgRegs) { 2029 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2030 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2031 if (RegIdx == ArgSGPRs.size()) 2032 report_fatal_error("ran out of SGPRs for arguments"); 2033 2034 unsigned Reg = ArgSGPRs[RegIdx]; 2035 Reg = CCInfo.AllocateReg(Reg); 2036 assert(Reg != AMDGPU::NoRegister); 2037 2038 MachineFunction &MF = CCInfo.getMachineFunction(); 2039 MF.addLiveIn(Reg, RC); 2040 return ArgDescriptor::createRegister(Reg); 2041 } 2042 2043 // If this has a fixed position, we still should allocate the register in the 2044 // CCInfo state. Technically we could get away with this for values passed 2045 // outside of the normal argument range. 2046 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2047 const TargetRegisterClass *RC, 2048 MCRegister Reg) { 2049 Reg = CCInfo.AllocateReg(Reg); 2050 assert(Reg != AMDGPU::NoRegister); 2051 MachineFunction &MF = CCInfo.getMachineFunction(); 2052 MF.addLiveIn(Reg, RC); 2053 } 2054 2055 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2056 if (Arg) { 2057 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2058 Arg.getRegister()); 2059 } else 2060 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2061 } 2062 2063 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2064 if (Arg) { 2065 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2066 Arg.getRegister()); 2067 } else 2068 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2069 } 2070 2071 /// Allocate implicit function VGPR arguments at the end of allocated user 2072 /// arguments. 2073 void SITargetLowering::allocateSpecialInputVGPRs( 2074 CCState &CCInfo, MachineFunction &MF, 2075 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2076 const unsigned Mask = 0x3ff; 2077 ArgDescriptor Arg; 2078 2079 if (Info.hasWorkItemIDX()) { 2080 Arg = allocateVGPR32Input(CCInfo, Mask); 2081 Info.setWorkItemIDX(Arg); 2082 } 2083 2084 if (Info.hasWorkItemIDY()) { 2085 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2086 Info.setWorkItemIDY(Arg); 2087 } 2088 2089 if (Info.hasWorkItemIDZ()) 2090 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2091 } 2092 2093 /// Allocate implicit function VGPR arguments in fixed registers. 2094 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2095 CCState &CCInfo, MachineFunction &MF, 2096 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2097 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2098 if (!Reg) 2099 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2100 2101 const unsigned Mask = 0x3ff; 2102 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2103 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2104 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2105 } 2106 2107 void SITargetLowering::allocateSpecialInputSGPRs( 2108 CCState &CCInfo, 2109 MachineFunction &MF, 2110 const SIRegisterInfo &TRI, 2111 SIMachineFunctionInfo &Info) const { 2112 auto &ArgInfo = Info.getArgInfo(); 2113 2114 // TODO: Unify handling with private memory pointers. 2115 if (Info.hasDispatchPtr()) 2116 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2117 2118 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2119 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2120 2121 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2122 // constant offset from the kernarg segment. 2123 if (Info.hasImplicitArgPtr()) 2124 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2125 2126 if (Info.hasDispatchID()) 2127 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2128 2129 // flat_scratch_init is not applicable for non-kernel functions. 2130 2131 if (Info.hasWorkGroupIDX()) 2132 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2133 2134 if (Info.hasWorkGroupIDY()) 2135 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2136 2137 if (Info.hasWorkGroupIDZ()) 2138 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2139 } 2140 2141 // Allocate special inputs passed in user SGPRs. 2142 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2143 MachineFunction &MF, 2144 const SIRegisterInfo &TRI, 2145 SIMachineFunctionInfo &Info) const { 2146 if (Info.hasImplicitBufferPtr()) { 2147 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2148 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2149 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2150 } 2151 2152 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2153 if (Info.hasPrivateSegmentBuffer()) { 2154 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2155 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2156 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2157 } 2158 2159 if (Info.hasDispatchPtr()) { 2160 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2161 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2162 CCInfo.AllocateReg(DispatchPtrReg); 2163 } 2164 2165 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2166 Register QueuePtrReg = Info.addQueuePtr(TRI); 2167 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2168 CCInfo.AllocateReg(QueuePtrReg); 2169 } 2170 2171 if (Info.hasKernargSegmentPtr()) { 2172 MachineRegisterInfo &MRI = MF.getRegInfo(); 2173 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2174 CCInfo.AllocateReg(InputPtrReg); 2175 2176 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2177 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2178 } 2179 2180 if (Info.hasDispatchID()) { 2181 Register DispatchIDReg = Info.addDispatchID(TRI); 2182 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2183 CCInfo.AllocateReg(DispatchIDReg); 2184 } 2185 2186 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2187 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2188 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2189 CCInfo.AllocateReg(FlatScratchInitReg); 2190 } 2191 2192 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2193 // these from the dispatch pointer. 2194 } 2195 2196 // Allocate special input registers that are initialized per-wave. 2197 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2198 MachineFunction &MF, 2199 SIMachineFunctionInfo &Info, 2200 CallingConv::ID CallConv, 2201 bool IsShader) const { 2202 if (Info.hasWorkGroupIDX()) { 2203 Register Reg = Info.addWorkGroupIDX(); 2204 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2205 CCInfo.AllocateReg(Reg); 2206 } 2207 2208 if (Info.hasWorkGroupIDY()) { 2209 Register Reg = Info.addWorkGroupIDY(); 2210 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2211 CCInfo.AllocateReg(Reg); 2212 } 2213 2214 if (Info.hasWorkGroupIDZ()) { 2215 Register Reg = Info.addWorkGroupIDZ(); 2216 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2217 CCInfo.AllocateReg(Reg); 2218 } 2219 2220 if (Info.hasWorkGroupInfo()) { 2221 Register Reg = Info.addWorkGroupInfo(); 2222 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2223 CCInfo.AllocateReg(Reg); 2224 } 2225 2226 if (Info.hasPrivateSegmentWaveByteOffset()) { 2227 // Scratch wave offset passed in system SGPR. 2228 unsigned PrivateSegmentWaveByteOffsetReg; 2229 2230 if (IsShader) { 2231 PrivateSegmentWaveByteOffsetReg = 2232 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2233 2234 // This is true if the scratch wave byte offset doesn't have a fixed 2235 // location. 2236 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2237 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2238 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2239 } 2240 } else 2241 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2242 2243 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2244 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2245 } 2246 } 2247 2248 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2249 MachineFunction &MF, 2250 const SIRegisterInfo &TRI, 2251 SIMachineFunctionInfo &Info) { 2252 // Now that we've figured out where the scratch register inputs are, see if 2253 // should reserve the arguments and use them directly. 2254 MachineFrameInfo &MFI = MF.getFrameInfo(); 2255 bool HasStackObjects = MFI.hasStackObjects(); 2256 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2257 2258 // Record that we know we have non-spill stack objects so we don't need to 2259 // check all stack objects later. 2260 if (HasStackObjects) 2261 Info.setHasNonSpillStackObjects(true); 2262 2263 // Everything live out of a block is spilled with fast regalloc, so it's 2264 // almost certain that spilling will be required. 2265 if (TM.getOptLevel() == CodeGenOpt::None) 2266 HasStackObjects = true; 2267 2268 // For now assume stack access is needed in any callee functions, so we need 2269 // the scratch registers to pass in. 2270 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2271 2272 if (!ST.enableFlatScratch()) { 2273 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2274 // If we have stack objects, we unquestionably need the private buffer 2275 // resource. For the Code Object V2 ABI, this will be the first 4 user 2276 // SGPR inputs. We can reserve those and use them directly. 2277 2278 Register PrivateSegmentBufferReg = 2279 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2280 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2281 } else { 2282 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2283 // We tentatively reserve the last registers (skipping the last registers 2284 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2285 // we'll replace these with the ones immediately after those which were 2286 // really allocated. In the prologue copies will be inserted from the 2287 // argument to these reserved registers. 2288 2289 // Without HSA, relocations are used for the scratch pointer and the 2290 // buffer resource setup is always inserted in the prologue. Scratch wave 2291 // offset is still in an input SGPR. 2292 Info.setScratchRSrcReg(ReservedBufferReg); 2293 } 2294 } 2295 2296 MachineRegisterInfo &MRI = MF.getRegInfo(); 2297 2298 // For entry functions we have to set up the stack pointer if we use it, 2299 // whereas non-entry functions get this "for free". This means there is no 2300 // intrinsic advantage to using S32 over S34 in cases where we do not have 2301 // calls but do need a frame pointer (i.e. if we are requested to have one 2302 // because frame pointer elimination is disabled). To keep things simple we 2303 // only ever use S32 as the call ABI stack pointer, and so using it does not 2304 // imply we need a separate frame pointer. 2305 // 2306 // Try to use s32 as the SP, but move it if it would interfere with input 2307 // arguments. This won't work with calls though. 2308 // 2309 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2310 // registers. 2311 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2312 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2313 } else { 2314 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2315 2316 if (MFI.hasCalls()) 2317 report_fatal_error("call in graphics shader with too many input SGPRs"); 2318 2319 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2320 if (!MRI.isLiveIn(Reg)) { 2321 Info.setStackPtrOffsetReg(Reg); 2322 break; 2323 } 2324 } 2325 2326 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2327 report_fatal_error("failed to find register for SP"); 2328 } 2329 2330 // hasFP should be accurate for entry functions even before the frame is 2331 // finalized, because it does not rely on the known stack size, only 2332 // properties like whether variable sized objects are present. 2333 if (ST.getFrameLowering()->hasFP(MF)) { 2334 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2335 } 2336 } 2337 2338 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2339 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2340 return !Info->isEntryFunction(); 2341 } 2342 2343 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2344 2345 } 2346 2347 void SITargetLowering::insertCopiesSplitCSR( 2348 MachineBasicBlock *Entry, 2349 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2350 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2351 2352 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2353 if (!IStart) 2354 return; 2355 2356 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2357 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2358 MachineBasicBlock::iterator MBBI = Entry->begin(); 2359 for (const MCPhysReg *I = IStart; *I; ++I) { 2360 const TargetRegisterClass *RC = nullptr; 2361 if (AMDGPU::SReg_64RegClass.contains(*I)) 2362 RC = &AMDGPU::SGPR_64RegClass; 2363 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2364 RC = &AMDGPU::SGPR_32RegClass; 2365 else 2366 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2367 2368 Register NewVR = MRI->createVirtualRegister(RC); 2369 // Create copy from CSR to a virtual register. 2370 Entry->addLiveIn(*I); 2371 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2372 .addReg(*I); 2373 2374 // Insert the copy-back instructions right before the terminator. 2375 for (auto *Exit : Exits) 2376 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2377 TII->get(TargetOpcode::COPY), *I) 2378 .addReg(NewVR); 2379 } 2380 } 2381 2382 SDValue SITargetLowering::LowerFormalArguments( 2383 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2384 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2385 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2386 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2387 2388 MachineFunction &MF = DAG.getMachineFunction(); 2389 const Function &Fn = MF.getFunction(); 2390 FunctionType *FType = MF.getFunction().getFunctionType(); 2391 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2392 2393 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2394 DiagnosticInfoUnsupported NoGraphicsHSA( 2395 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2396 DAG.getContext()->diagnose(NoGraphicsHSA); 2397 return DAG.getEntryNode(); 2398 } 2399 2400 Info->allocateModuleLDSGlobal(Fn.getParent()); 2401 2402 SmallVector<ISD::InputArg, 16> Splits; 2403 SmallVector<CCValAssign, 16> ArgLocs; 2404 BitVector Skipped(Ins.size()); 2405 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2406 *DAG.getContext()); 2407 2408 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2409 bool IsKernel = AMDGPU::isKernel(CallConv); 2410 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2411 2412 if (IsGraphics) { 2413 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2414 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2415 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2416 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2417 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2418 !Info->hasWorkItemIDZ()); 2419 } 2420 2421 if (CallConv == CallingConv::AMDGPU_PS) { 2422 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2423 2424 // At least one interpolation mode must be enabled or else the GPU will 2425 // hang. 2426 // 2427 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2428 // set PSInputAddr, the user wants to enable some bits after the compilation 2429 // based on run-time states. Since we can't know what the final PSInputEna 2430 // will look like, so we shouldn't do anything here and the user should take 2431 // responsibility for the correct programming. 2432 // 2433 // Otherwise, the following restrictions apply: 2434 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2435 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2436 // enabled too. 2437 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2438 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2439 CCInfo.AllocateReg(AMDGPU::VGPR0); 2440 CCInfo.AllocateReg(AMDGPU::VGPR1); 2441 Info->markPSInputAllocated(0); 2442 Info->markPSInputEnabled(0); 2443 } 2444 if (Subtarget->isAmdPalOS()) { 2445 // For isAmdPalOS, the user does not enable some bits after compilation 2446 // based on run-time states; the register values being generated here are 2447 // the final ones set in hardware. Therefore we need to apply the 2448 // workaround to PSInputAddr and PSInputEnable together. (The case where 2449 // a bit is set in PSInputAddr but not PSInputEnable is where the 2450 // frontend set up an input arg for a particular interpolation mode, but 2451 // nothing uses that input arg. Really we should have an earlier pass 2452 // that removes such an arg.) 2453 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2454 if ((PsInputBits & 0x7F) == 0 || 2455 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2456 Info->markPSInputEnabled( 2457 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2458 } 2459 } else if (IsKernel) { 2460 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2461 } else { 2462 Splits.append(Ins.begin(), Ins.end()); 2463 } 2464 2465 if (IsEntryFunc) { 2466 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2467 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2468 } else if (!IsGraphics) { 2469 // For the fixed ABI, pass workitem IDs in the last argument register. 2470 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2471 } 2472 2473 if (IsKernel) { 2474 analyzeFormalArgumentsCompute(CCInfo, Ins); 2475 } else { 2476 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2477 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2478 } 2479 2480 SmallVector<SDValue, 16> Chains; 2481 2482 // FIXME: This is the minimum kernel argument alignment. We should improve 2483 // this to the maximum alignment of the arguments. 2484 // 2485 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2486 // kern arg offset. 2487 const Align KernelArgBaseAlign = Align(16); 2488 2489 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2490 const ISD::InputArg &Arg = Ins[i]; 2491 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2492 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2493 continue; 2494 } 2495 2496 CCValAssign &VA = ArgLocs[ArgIdx++]; 2497 MVT VT = VA.getLocVT(); 2498 2499 if (IsEntryFunc && VA.isMemLoc()) { 2500 VT = Ins[i].VT; 2501 EVT MemVT = VA.getLocVT(); 2502 2503 const uint64_t Offset = VA.getLocMemOffset(); 2504 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2505 2506 if (Arg.Flags.isByRef()) { 2507 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2508 2509 const GCNTargetMachine &TM = 2510 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2511 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2512 Arg.Flags.getPointerAddrSpace())) { 2513 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2514 Arg.Flags.getPointerAddrSpace()); 2515 } 2516 2517 InVals.push_back(Ptr); 2518 continue; 2519 } 2520 2521 SDValue Arg = lowerKernargMemParameter( 2522 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2523 Chains.push_back(Arg.getValue(1)); 2524 2525 auto *ParamTy = 2526 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2527 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2528 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2529 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2530 // On SI local pointers are just offsets into LDS, so they are always 2531 // less than 16-bits. On CI and newer they could potentially be 2532 // real pointers, so we can't guarantee their size. 2533 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2534 DAG.getValueType(MVT::i16)); 2535 } 2536 2537 InVals.push_back(Arg); 2538 continue; 2539 } else if (!IsEntryFunc && VA.isMemLoc()) { 2540 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2541 InVals.push_back(Val); 2542 if (!Arg.Flags.isByVal()) 2543 Chains.push_back(Val.getValue(1)); 2544 continue; 2545 } 2546 2547 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2548 2549 Register Reg = VA.getLocReg(); 2550 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2551 EVT ValVT = VA.getValVT(); 2552 2553 Reg = MF.addLiveIn(Reg, RC); 2554 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2555 2556 if (Arg.Flags.isSRet()) { 2557 // The return object should be reasonably addressable. 2558 2559 // FIXME: This helps when the return is a real sret. If it is a 2560 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2561 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2562 unsigned NumBits 2563 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2564 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2565 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2566 } 2567 2568 // If this is an 8 or 16-bit value, it is really passed promoted 2569 // to 32 bits. Insert an assert[sz]ext to capture this, then 2570 // truncate to the right size. 2571 switch (VA.getLocInfo()) { 2572 case CCValAssign::Full: 2573 break; 2574 case CCValAssign::BCvt: 2575 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2576 break; 2577 case CCValAssign::SExt: 2578 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2579 DAG.getValueType(ValVT)); 2580 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2581 break; 2582 case CCValAssign::ZExt: 2583 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2584 DAG.getValueType(ValVT)); 2585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2586 break; 2587 case CCValAssign::AExt: 2588 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2589 break; 2590 default: 2591 llvm_unreachable("Unknown loc info!"); 2592 } 2593 2594 InVals.push_back(Val); 2595 } 2596 2597 // Start adding system SGPRs. 2598 if (IsEntryFunc) { 2599 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2600 } else { 2601 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2602 if (!IsGraphics) 2603 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2604 } 2605 2606 auto &ArgUsageInfo = 2607 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2608 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2609 2610 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2611 Info->setBytesInStackArgArea(StackArgSize); 2612 2613 return Chains.empty() ? Chain : 2614 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2615 } 2616 2617 // TODO: If return values can't fit in registers, we should return as many as 2618 // possible in registers before passing on stack. 2619 bool SITargetLowering::CanLowerReturn( 2620 CallingConv::ID CallConv, 2621 MachineFunction &MF, bool IsVarArg, 2622 const SmallVectorImpl<ISD::OutputArg> &Outs, 2623 LLVMContext &Context) const { 2624 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2625 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2626 // for shaders. Vector types should be explicitly handled by CC. 2627 if (AMDGPU::isEntryFunctionCC(CallConv)) 2628 return true; 2629 2630 SmallVector<CCValAssign, 16> RVLocs; 2631 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2632 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2633 } 2634 2635 SDValue 2636 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2637 bool isVarArg, 2638 const SmallVectorImpl<ISD::OutputArg> &Outs, 2639 const SmallVectorImpl<SDValue> &OutVals, 2640 const SDLoc &DL, SelectionDAG &DAG) const { 2641 MachineFunction &MF = DAG.getMachineFunction(); 2642 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2643 2644 if (AMDGPU::isKernel(CallConv)) { 2645 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2646 OutVals, DL, DAG); 2647 } 2648 2649 bool IsShader = AMDGPU::isShader(CallConv); 2650 2651 Info->setIfReturnsVoid(Outs.empty()); 2652 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2653 2654 // CCValAssign - represent the assignment of the return value to a location. 2655 SmallVector<CCValAssign, 48> RVLocs; 2656 SmallVector<ISD::OutputArg, 48> Splits; 2657 2658 // CCState - Info about the registers and stack slots. 2659 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2660 *DAG.getContext()); 2661 2662 // Analyze outgoing return values. 2663 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2664 2665 SDValue Flag; 2666 SmallVector<SDValue, 48> RetOps; 2667 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2668 2669 // Copy the result values into the output registers. 2670 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2671 ++I, ++RealRVLocIdx) { 2672 CCValAssign &VA = RVLocs[I]; 2673 assert(VA.isRegLoc() && "Can only return in registers!"); 2674 // TODO: Partially return in registers if return values don't fit. 2675 SDValue Arg = OutVals[RealRVLocIdx]; 2676 2677 // Copied from other backends. 2678 switch (VA.getLocInfo()) { 2679 case CCValAssign::Full: 2680 break; 2681 case CCValAssign::BCvt: 2682 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2683 break; 2684 case CCValAssign::SExt: 2685 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2686 break; 2687 case CCValAssign::ZExt: 2688 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2689 break; 2690 case CCValAssign::AExt: 2691 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2692 break; 2693 default: 2694 llvm_unreachable("Unknown loc info!"); 2695 } 2696 2697 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2698 Flag = Chain.getValue(1); 2699 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2700 } 2701 2702 // FIXME: Does sret work properly? 2703 if (!Info->isEntryFunction()) { 2704 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2705 const MCPhysReg *I = 2706 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2707 if (I) { 2708 for (; *I; ++I) { 2709 if (AMDGPU::SReg_64RegClass.contains(*I)) 2710 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2711 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2712 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2713 else 2714 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2715 } 2716 } 2717 } 2718 2719 // Update chain and glue. 2720 RetOps[0] = Chain; 2721 if (Flag.getNode()) 2722 RetOps.push_back(Flag); 2723 2724 unsigned Opc = AMDGPUISD::ENDPGM; 2725 if (!IsWaveEnd) 2726 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2727 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2728 } 2729 2730 SDValue SITargetLowering::LowerCallResult( 2731 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2732 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2733 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2734 SDValue ThisVal) const { 2735 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2736 2737 // Assign locations to each value returned by this call. 2738 SmallVector<CCValAssign, 16> RVLocs; 2739 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2740 *DAG.getContext()); 2741 CCInfo.AnalyzeCallResult(Ins, RetCC); 2742 2743 // Copy all of the result registers out of their specified physreg. 2744 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2745 CCValAssign VA = RVLocs[i]; 2746 SDValue Val; 2747 2748 if (VA.isRegLoc()) { 2749 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2750 Chain = Val.getValue(1); 2751 InFlag = Val.getValue(2); 2752 } else if (VA.isMemLoc()) { 2753 report_fatal_error("TODO: return values in memory"); 2754 } else 2755 llvm_unreachable("unknown argument location type"); 2756 2757 switch (VA.getLocInfo()) { 2758 case CCValAssign::Full: 2759 break; 2760 case CCValAssign::BCvt: 2761 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2762 break; 2763 case CCValAssign::ZExt: 2764 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2765 DAG.getValueType(VA.getValVT())); 2766 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2767 break; 2768 case CCValAssign::SExt: 2769 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2770 DAG.getValueType(VA.getValVT())); 2771 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2772 break; 2773 case CCValAssign::AExt: 2774 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2775 break; 2776 default: 2777 llvm_unreachable("Unknown loc info!"); 2778 } 2779 2780 InVals.push_back(Val); 2781 } 2782 2783 return Chain; 2784 } 2785 2786 // Add code to pass special inputs required depending on used features separate 2787 // from the explicit user arguments present in the IR. 2788 void SITargetLowering::passSpecialInputs( 2789 CallLoweringInfo &CLI, 2790 CCState &CCInfo, 2791 const SIMachineFunctionInfo &Info, 2792 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2793 SmallVectorImpl<SDValue> &MemOpChains, 2794 SDValue Chain) const { 2795 // If we don't have a call site, this was a call inserted by 2796 // legalization. These can never use special inputs. 2797 if (!CLI.CB) 2798 return; 2799 2800 SelectionDAG &DAG = CLI.DAG; 2801 const SDLoc &DL = CLI.DL; 2802 const Function &F = DAG.getMachineFunction().getFunction(); 2803 2804 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2805 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2806 2807 const AMDGPUFunctionArgInfo *CalleeArgInfo 2808 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2809 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2810 auto &ArgUsageInfo = 2811 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2812 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2813 } 2814 2815 // TODO: Unify with private memory register handling. This is complicated by 2816 // the fact that at least in kernels, the input argument is not necessarily 2817 // in the same location as the input. 2818 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2819 StringLiteral> ImplicitAttrs[] = { 2820 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2821 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2822 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2823 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2824 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2825 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2826 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2827 }; 2828 2829 for (auto Attr : ImplicitAttrs) { 2830 const ArgDescriptor *OutgoingArg; 2831 const TargetRegisterClass *ArgRC; 2832 LLT ArgTy; 2833 2834 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2835 2836 // If the callee does not use the attribute value, skip copying the value. 2837 if (CLI.CB->hasFnAttr(Attr.second)) 2838 continue; 2839 2840 std::tie(OutgoingArg, ArgRC, ArgTy) = 2841 CalleeArgInfo->getPreloadedValue(InputID); 2842 if (!OutgoingArg) 2843 continue; 2844 2845 const ArgDescriptor *IncomingArg; 2846 const TargetRegisterClass *IncomingArgRC; 2847 LLT Ty; 2848 std::tie(IncomingArg, IncomingArgRC, Ty) = 2849 CallerArgInfo.getPreloadedValue(InputID); 2850 assert(IncomingArgRC == ArgRC); 2851 2852 // All special arguments are ints for now. 2853 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2854 SDValue InputReg; 2855 2856 if (IncomingArg) { 2857 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2858 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2859 // The implicit arg ptr is special because it doesn't have a corresponding 2860 // input for kernels, and is computed from the kernarg segment pointer. 2861 InputReg = getImplicitArgPtr(DAG, DL); 2862 } else { 2863 // We may have proven the input wasn't needed, although the ABI is 2864 // requiring it. We just need to allocate the register appropriately. 2865 InputReg = DAG.getUNDEF(ArgVT); 2866 } 2867 2868 if (OutgoingArg->isRegister()) { 2869 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2870 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2871 report_fatal_error("failed to allocate implicit input argument"); 2872 } else { 2873 unsigned SpecialArgOffset = 2874 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2875 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2876 SpecialArgOffset); 2877 MemOpChains.push_back(ArgStore); 2878 } 2879 } 2880 2881 // Pack workitem IDs into a single register or pass it as is if already 2882 // packed. 2883 const ArgDescriptor *OutgoingArg; 2884 const TargetRegisterClass *ArgRC; 2885 LLT Ty; 2886 2887 std::tie(OutgoingArg, ArgRC, Ty) = 2888 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2889 if (!OutgoingArg) 2890 std::tie(OutgoingArg, ArgRC, Ty) = 2891 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2892 if (!OutgoingArg) 2893 std::tie(OutgoingArg, ArgRC, Ty) = 2894 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2895 if (!OutgoingArg) 2896 return; 2897 2898 const ArgDescriptor *IncomingArgX = std::get<0>( 2899 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2900 const ArgDescriptor *IncomingArgY = std::get<0>( 2901 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2902 const ArgDescriptor *IncomingArgZ = std::get<0>( 2903 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2904 2905 SDValue InputReg; 2906 SDLoc SL; 2907 2908 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2909 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2910 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2911 2912 // If incoming ids are not packed we need to pack them. 2913 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2914 NeedWorkItemIDX) { 2915 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2916 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2917 } else { 2918 InputReg = DAG.getConstant(0, DL, MVT::i32); 2919 } 2920 } 2921 2922 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2923 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2924 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2925 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2926 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2927 InputReg = InputReg.getNode() ? 2928 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2929 } 2930 2931 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2932 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2933 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2934 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2935 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2936 InputReg = InputReg.getNode() ? 2937 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2938 } 2939 2940 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2941 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2942 // We're in a situation where the outgoing function requires the workitem 2943 // ID, but the calling function does not have it (e.g a graphics function 2944 // calling a C calling convention function). This is illegal, but we need 2945 // to produce something. 2946 InputReg = DAG.getUNDEF(MVT::i32); 2947 } else { 2948 // Workitem ids are already packed, any of present incoming arguments 2949 // will carry all required fields. 2950 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2951 IncomingArgX ? *IncomingArgX : 2952 IncomingArgY ? *IncomingArgY : 2953 *IncomingArgZ, ~0u); 2954 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2955 } 2956 } 2957 2958 if (OutgoingArg->isRegister()) { 2959 if (InputReg) 2960 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2961 2962 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2963 } else { 2964 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2965 if (InputReg) { 2966 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2967 SpecialArgOffset); 2968 MemOpChains.push_back(ArgStore); 2969 } 2970 } 2971 } 2972 2973 static bool canGuaranteeTCO(CallingConv::ID CC) { 2974 return CC == CallingConv::Fast; 2975 } 2976 2977 /// Return true if we might ever do TCO for calls with this calling convention. 2978 static bool mayTailCallThisCC(CallingConv::ID CC) { 2979 switch (CC) { 2980 case CallingConv::C: 2981 case CallingConv::AMDGPU_Gfx: 2982 return true; 2983 default: 2984 return canGuaranteeTCO(CC); 2985 } 2986 } 2987 2988 bool SITargetLowering::isEligibleForTailCallOptimization( 2989 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2990 const SmallVectorImpl<ISD::OutputArg> &Outs, 2991 const SmallVectorImpl<SDValue> &OutVals, 2992 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2993 if (!mayTailCallThisCC(CalleeCC)) 2994 return false; 2995 2996 // For a divergent call target, we need to do a waterfall loop over the 2997 // possible callees which precludes us from using a simple jump. 2998 if (Callee->isDivergent()) 2999 return false; 3000 3001 MachineFunction &MF = DAG.getMachineFunction(); 3002 const Function &CallerF = MF.getFunction(); 3003 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3004 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3005 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3006 3007 // Kernels aren't callable, and don't have a live in return address so it 3008 // doesn't make sense to do a tail call with entry functions. 3009 if (!CallerPreserved) 3010 return false; 3011 3012 bool CCMatch = CallerCC == CalleeCC; 3013 3014 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3015 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3016 return true; 3017 return false; 3018 } 3019 3020 // TODO: Can we handle var args? 3021 if (IsVarArg) 3022 return false; 3023 3024 for (const Argument &Arg : CallerF.args()) { 3025 if (Arg.hasByValAttr()) 3026 return false; 3027 } 3028 3029 LLVMContext &Ctx = *DAG.getContext(); 3030 3031 // Check that the call results are passed in the same way. 3032 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3033 CCAssignFnForCall(CalleeCC, IsVarArg), 3034 CCAssignFnForCall(CallerCC, IsVarArg))) 3035 return false; 3036 3037 // The callee has to preserve all registers the caller needs to preserve. 3038 if (!CCMatch) { 3039 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3040 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3041 return false; 3042 } 3043 3044 // Nothing more to check if the callee is taking no arguments. 3045 if (Outs.empty()) 3046 return true; 3047 3048 SmallVector<CCValAssign, 16> ArgLocs; 3049 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3050 3051 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3052 3053 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3054 // If the stack arguments for this call do not fit into our own save area then 3055 // the call cannot be made tail. 3056 // TODO: Is this really necessary? 3057 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3058 return false; 3059 3060 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3061 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3062 } 3063 3064 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3065 if (!CI->isTailCall()) 3066 return false; 3067 3068 const Function *ParentFn = CI->getParent()->getParent(); 3069 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3070 return false; 3071 return true; 3072 } 3073 3074 // The wave scratch offset register is used as the global base pointer. 3075 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3076 SmallVectorImpl<SDValue> &InVals) const { 3077 SelectionDAG &DAG = CLI.DAG; 3078 const SDLoc &DL = CLI.DL; 3079 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3080 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3081 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3082 SDValue Chain = CLI.Chain; 3083 SDValue Callee = CLI.Callee; 3084 bool &IsTailCall = CLI.IsTailCall; 3085 CallingConv::ID CallConv = CLI.CallConv; 3086 bool IsVarArg = CLI.IsVarArg; 3087 bool IsSibCall = false; 3088 bool IsThisReturn = false; 3089 MachineFunction &MF = DAG.getMachineFunction(); 3090 3091 if (Callee.isUndef() || isNullConstant(Callee)) { 3092 if (!CLI.IsTailCall) { 3093 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3094 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3095 } 3096 3097 return Chain; 3098 } 3099 3100 if (IsVarArg) { 3101 return lowerUnhandledCall(CLI, InVals, 3102 "unsupported call to variadic function "); 3103 } 3104 3105 if (!CLI.CB) 3106 report_fatal_error("unsupported libcall legalization"); 3107 3108 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3109 return lowerUnhandledCall(CLI, InVals, 3110 "unsupported required tail call to function "); 3111 } 3112 3113 if (AMDGPU::isShader(CallConv)) { 3114 // Note the issue is with the CC of the called function, not of the call 3115 // itself. 3116 return lowerUnhandledCall(CLI, InVals, 3117 "unsupported call to a shader function "); 3118 } 3119 3120 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3121 CallConv != CallingConv::AMDGPU_Gfx) { 3122 // Only allow calls with specific calling conventions. 3123 return lowerUnhandledCall(CLI, InVals, 3124 "unsupported calling convention for call from " 3125 "graphics shader of function "); 3126 } 3127 3128 if (IsTailCall) { 3129 IsTailCall = isEligibleForTailCallOptimization( 3130 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3131 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3132 report_fatal_error("failed to perform tail call elimination on a call " 3133 "site marked musttail"); 3134 } 3135 3136 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3137 3138 // A sibling call is one where we're under the usual C ABI and not planning 3139 // to change that but can still do a tail call: 3140 if (!TailCallOpt && IsTailCall) 3141 IsSibCall = true; 3142 3143 if (IsTailCall) 3144 ++NumTailCalls; 3145 } 3146 3147 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3148 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3149 SmallVector<SDValue, 8> MemOpChains; 3150 3151 // Analyze operands of the call, assigning locations to each operand. 3152 SmallVector<CCValAssign, 16> ArgLocs; 3153 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3154 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3155 3156 if (CallConv != CallingConv::AMDGPU_Gfx) { 3157 // With a fixed ABI, allocate fixed registers before user arguments. 3158 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3159 } 3160 3161 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3162 3163 // Get a count of how many bytes are to be pushed on the stack. 3164 unsigned NumBytes = CCInfo.getNextStackOffset(); 3165 3166 if (IsSibCall) { 3167 // Since we're not changing the ABI to make this a tail call, the memory 3168 // operands are already available in the caller's incoming argument space. 3169 NumBytes = 0; 3170 } 3171 3172 // FPDiff is the byte offset of the call's argument area from the callee's. 3173 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3174 // by this amount for a tail call. In a sibling call it must be 0 because the 3175 // caller will deallocate the entire stack and the callee still expects its 3176 // arguments to begin at SP+0. Completely unused for non-tail calls. 3177 int32_t FPDiff = 0; 3178 MachineFrameInfo &MFI = MF.getFrameInfo(); 3179 3180 // Adjust the stack pointer for the new arguments... 3181 // These operations are automatically eliminated by the prolog/epilog pass 3182 if (!IsSibCall) { 3183 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3184 3185 if (!Subtarget->enableFlatScratch()) { 3186 SmallVector<SDValue, 4> CopyFromChains; 3187 3188 // In the HSA case, this should be an identity copy. 3189 SDValue ScratchRSrcReg 3190 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3191 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3192 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3193 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3194 } 3195 } 3196 3197 MVT PtrVT = MVT::i32; 3198 3199 // Walk the register/memloc assignments, inserting copies/loads. 3200 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3201 CCValAssign &VA = ArgLocs[i]; 3202 SDValue Arg = OutVals[i]; 3203 3204 // Promote the value if needed. 3205 switch (VA.getLocInfo()) { 3206 case CCValAssign::Full: 3207 break; 3208 case CCValAssign::BCvt: 3209 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3210 break; 3211 case CCValAssign::ZExt: 3212 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3213 break; 3214 case CCValAssign::SExt: 3215 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3216 break; 3217 case CCValAssign::AExt: 3218 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3219 break; 3220 case CCValAssign::FPExt: 3221 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3222 break; 3223 default: 3224 llvm_unreachable("Unknown loc info!"); 3225 } 3226 3227 if (VA.isRegLoc()) { 3228 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3229 } else { 3230 assert(VA.isMemLoc()); 3231 3232 SDValue DstAddr; 3233 MachinePointerInfo DstInfo; 3234 3235 unsigned LocMemOffset = VA.getLocMemOffset(); 3236 int32_t Offset = LocMemOffset; 3237 3238 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3239 MaybeAlign Alignment; 3240 3241 if (IsTailCall) { 3242 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3243 unsigned OpSize = Flags.isByVal() ? 3244 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3245 3246 // FIXME: We can have better than the minimum byval required alignment. 3247 Alignment = 3248 Flags.isByVal() 3249 ? Flags.getNonZeroByValAlign() 3250 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3251 3252 Offset = Offset + FPDiff; 3253 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3254 3255 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3256 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3257 3258 // Make sure any stack arguments overlapping with where we're storing 3259 // are loaded before this eventual operation. Otherwise they'll be 3260 // clobbered. 3261 3262 // FIXME: Why is this really necessary? This seems to just result in a 3263 // lot of code to copy the stack and write them back to the same 3264 // locations, which are supposed to be immutable? 3265 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3266 } else { 3267 // Stores to the argument stack area are relative to the stack pointer. 3268 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3269 MVT::i32); 3270 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3271 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3272 Alignment = 3273 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3274 } 3275 3276 if (Outs[i].Flags.isByVal()) { 3277 SDValue SizeNode = 3278 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3279 SDValue Cpy = 3280 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3281 Outs[i].Flags.getNonZeroByValAlign(), 3282 /*isVol = */ false, /*AlwaysInline = */ true, 3283 /*isTailCall = */ false, DstInfo, 3284 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3285 3286 MemOpChains.push_back(Cpy); 3287 } else { 3288 SDValue Store = 3289 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3290 MemOpChains.push_back(Store); 3291 } 3292 } 3293 } 3294 3295 if (!MemOpChains.empty()) 3296 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3297 3298 // Build a sequence of copy-to-reg nodes chained together with token chain 3299 // and flag operands which copy the outgoing args into the appropriate regs. 3300 SDValue InFlag; 3301 for (auto &RegToPass : RegsToPass) { 3302 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3303 RegToPass.second, InFlag); 3304 InFlag = Chain.getValue(1); 3305 } 3306 3307 3308 // We don't usually want to end the call-sequence here because we would tidy 3309 // the frame up *after* the call, however in the ABI-changing tail-call case 3310 // we've carefully laid out the parameters so that when sp is reset they'll be 3311 // in the correct location. 3312 if (IsTailCall && !IsSibCall) { 3313 Chain = DAG.getCALLSEQ_END(Chain, 3314 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3315 DAG.getTargetConstant(0, DL, MVT::i32), 3316 InFlag, DL); 3317 InFlag = Chain.getValue(1); 3318 } 3319 3320 std::vector<SDValue> Ops; 3321 Ops.push_back(Chain); 3322 Ops.push_back(Callee); 3323 // Add a redundant copy of the callee global which will not be legalized, as 3324 // we need direct access to the callee later. 3325 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3326 const GlobalValue *GV = GSD->getGlobal(); 3327 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3328 } else { 3329 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3330 } 3331 3332 if (IsTailCall) { 3333 // Each tail call may have to adjust the stack by a different amount, so 3334 // this information must travel along with the operation for eventual 3335 // consumption by emitEpilogue. 3336 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3337 } 3338 3339 // Add argument registers to the end of the list so that they are known live 3340 // into the call. 3341 for (auto &RegToPass : RegsToPass) { 3342 Ops.push_back(DAG.getRegister(RegToPass.first, 3343 RegToPass.second.getValueType())); 3344 } 3345 3346 // Add a register mask operand representing the call-preserved registers. 3347 3348 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3349 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3350 assert(Mask && "Missing call preserved mask for calling convention"); 3351 Ops.push_back(DAG.getRegisterMask(Mask)); 3352 3353 if (InFlag.getNode()) 3354 Ops.push_back(InFlag); 3355 3356 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3357 3358 // If we're doing a tall call, use a TC_RETURN here rather than an 3359 // actual call instruction. 3360 if (IsTailCall) { 3361 MFI.setHasTailCall(); 3362 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3363 } 3364 3365 // Returns a chain and a flag for retval copy to use. 3366 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3367 Chain = Call.getValue(0); 3368 InFlag = Call.getValue(1); 3369 3370 uint64_t CalleePopBytes = NumBytes; 3371 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3372 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3373 InFlag, DL); 3374 if (!Ins.empty()) 3375 InFlag = Chain.getValue(1); 3376 3377 // Handle result values, copying them out of physregs into vregs that we 3378 // return. 3379 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3380 InVals, IsThisReturn, 3381 IsThisReturn ? OutVals[0] : SDValue()); 3382 } 3383 3384 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3385 // except for applying the wave size scale to the increment amount. 3386 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3387 SDValue Op, SelectionDAG &DAG) const { 3388 const MachineFunction &MF = DAG.getMachineFunction(); 3389 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3390 3391 SDLoc dl(Op); 3392 EVT VT = Op.getValueType(); 3393 SDValue Tmp1 = Op; 3394 SDValue Tmp2 = Op.getValue(1); 3395 SDValue Tmp3 = Op.getOperand(2); 3396 SDValue Chain = Tmp1.getOperand(0); 3397 3398 Register SPReg = Info->getStackPtrOffsetReg(); 3399 3400 // Chain the dynamic stack allocation so that it doesn't modify the stack 3401 // pointer when other instructions are using the stack. 3402 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3403 3404 SDValue Size = Tmp2.getOperand(1); 3405 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3406 Chain = SP.getValue(1); 3407 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3408 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3409 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3410 unsigned Opc = 3411 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3412 ISD::ADD : ISD::SUB; 3413 3414 SDValue ScaledSize = DAG.getNode( 3415 ISD::SHL, dl, VT, Size, 3416 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3417 3418 Align StackAlign = TFL->getStackAlign(); 3419 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3420 if (Alignment && *Alignment > StackAlign) { 3421 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3422 DAG.getConstant(-(uint64_t)Alignment->value() 3423 << ST.getWavefrontSizeLog2(), 3424 dl, VT)); 3425 } 3426 3427 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3428 Tmp2 = DAG.getCALLSEQ_END( 3429 Chain, DAG.getIntPtrConstant(0, dl, true), 3430 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3431 3432 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3433 } 3434 3435 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3436 SelectionDAG &DAG) const { 3437 // We only handle constant sizes here to allow non-entry block, static sized 3438 // allocas. A truly dynamic value is more difficult to support because we 3439 // don't know if the size value is uniform or not. If the size isn't uniform, 3440 // we would need to do a wave reduction to get the maximum size to know how 3441 // much to increment the uniform stack pointer. 3442 SDValue Size = Op.getOperand(1); 3443 if (isa<ConstantSDNode>(Size)) 3444 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3445 3446 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3447 } 3448 3449 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3450 const MachineFunction &MF) const { 3451 Register Reg = StringSwitch<Register>(RegName) 3452 .Case("m0", AMDGPU::M0) 3453 .Case("exec", AMDGPU::EXEC) 3454 .Case("exec_lo", AMDGPU::EXEC_LO) 3455 .Case("exec_hi", AMDGPU::EXEC_HI) 3456 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3457 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3458 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3459 .Default(Register()); 3460 3461 if (Reg == AMDGPU::NoRegister) { 3462 report_fatal_error(Twine("invalid register name \"" 3463 + StringRef(RegName) + "\".")); 3464 3465 } 3466 3467 if (!Subtarget->hasFlatScrRegister() && 3468 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3469 report_fatal_error(Twine("invalid register \"" 3470 + StringRef(RegName) + "\" for subtarget.")); 3471 } 3472 3473 switch (Reg) { 3474 case AMDGPU::M0: 3475 case AMDGPU::EXEC_LO: 3476 case AMDGPU::EXEC_HI: 3477 case AMDGPU::FLAT_SCR_LO: 3478 case AMDGPU::FLAT_SCR_HI: 3479 if (VT.getSizeInBits() == 32) 3480 return Reg; 3481 break; 3482 case AMDGPU::EXEC: 3483 case AMDGPU::FLAT_SCR: 3484 if (VT.getSizeInBits() == 64) 3485 return Reg; 3486 break; 3487 default: 3488 llvm_unreachable("missing register type checking"); 3489 } 3490 3491 report_fatal_error(Twine("invalid type for register \"" 3492 + StringRef(RegName) + "\".")); 3493 } 3494 3495 // If kill is not the last instruction, split the block so kill is always a 3496 // proper terminator. 3497 MachineBasicBlock * 3498 SITargetLowering::splitKillBlock(MachineInstr &MI, 3499 MachineBasicBlock *BB) const { 3500 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3501 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3502 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3503 return SplitBB; 3504 } 3505 3506 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3507 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3508 // be the first instruction in the remainder block. 3509 // 3510 /// \returns { LoopBody, Remainder } 3511 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3512 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3513 MachineFunction *MF = MBB.getParent(); 3514 MachineBasicBlock::iterator I(&MI); 3515 3516 // To insert the loop we need to split the block. Move everything after this 3517 // point to a new block, and insert a new empty block between the two. 3518 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3519 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3520 MachineFunction::iterator MBBI(MBB); 3521 ++MBBI; 3522 3523 MF->insert(MBBI, LoopBB); 3524 MF->insert(MBBI, RemainderBB); 3525 3526 LoopBB->addSuccessor(LoopBB); 3527 LoopBB->addSuccessor(RemainderBB); 3528 3529 // Move the rest of the block into a new block. 3530 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3531 3532 if (InstInLoop) { 3533 auto Next = std::next(I); 3534 3535 // Move instruction to loop body. 3536 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3537 3538 // Move the rest of the block. 3539 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3540 } else { 3541 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3542 } 3543 3544 MBB.addSuccessor(LoopBB); 3545 3546 return std::make_pair(LoopBB, RemainderBB); 3547 } 3548 3549 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3550 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3551 MachineBasicBlock *MBB = MI.getParent(); 3552 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3553 auto I = MI.getIterator(); 3554 auto E = std::next(I); 3555 3556 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3557 .addImm(0); 3558 3559 MIBundleBuilder Bundler(*MBB, I, E); 3560 finalizeBundle(*MBB, Bundler.begin()); 3561 } 3562 3563 MachineBasicBlock * 3564 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3565 MachineBasicBlock *BB) const { 3566 const DebugLoc &DL = MI.getDebugLoc(); 3567 3568 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3569 3570 MachineBasicBlock *LoopBB; 3571 MachineBasicBlock *RemainderBB; 3572 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3573 3574 // Apparently kill flags are only valid if the def is in the same block? 3575 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3576 Src->setIsKill(false); 3577 3578 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3579 3580 MachineBasicBlock::iterator I = LoopBB->end(); 3581 3582 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3583 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3584 3585 // Clear TRAP_STS.MEM_VIOL 3586 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3587 .addImm(0) 3588 .addImm(EncodedReg); 3589 3590 bundleInstWithWaitcnt(MI); 3591 3592 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3593 3594 // Load and check TRAP_STS.MEM_VIOL 3595 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3596 .addImm(EncodedReg); 3597 3598 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3599 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3600 .addReg(Reg, RegState::Kill) 3601 .addImm(0); 3602 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3603 .addMBB(LoopBB); 3604 3605 return RemainderBB; 3606 } 3607 3608 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3609 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3610 // will only do one iteration. In the worst case, this will loop 64 times. 3611 // 3612 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3613 static MachineBasicBlock::iterator 3614 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3615 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3616 const DebugLoc &DL, const MachineOperand &Idx, 3617 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3618 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3619 Register &SGPRIdxReg) { 3620 3621 MachineFunction *MF = OrigBB.getParent(); 3622 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3623 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3624 MachineBasicBlock::iterator I = LoopBB.begin(); 3625 3626 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3627 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3628 Register NewExec = MRI.createVirtualRegister(BoolRC); 3629 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3630 Register CondReg = MRI.createVirtualRegister(BoolRC); 3631 3632 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3633 .addReg(InitReg) 3634 .addMBB(&OrigBB) 3635 .addReg(ResultReg) 3636 .addMBB(&LoopBB); 3637 3638 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3639 .addReg(InitSaveExecReg) 3640 .addMBB(&OrigBB) 3641 .addReg(NewExec) 3642 .addMBB(&LoopBB); 3643 3644 // Read the next variant <- also loop target. 3645 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3646 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3647 3648 // Compare the just read M0 value to all possible Idx values. 3649 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3650 .addReg(CurrentIdxReg) 3651 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3652 3653 // Update EXEC, save the original EXEC value to VCC. 3654 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3655 : AMDGPU::S_AND_SAVEEXEC_B64), 3656 NewExec) 3657 .addReg(CondReg, RegState::Kill); 3658 3659 MRI.setSimpleHint(NewExec, CondReg); 3660 3661 if (UseGPRIdxMode) { 3662 if (Offset == 0) { 3663 SGPRIdxReg = CurrentIdxReg; 3664 } else { 3665 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3666 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3667 .addReg(CurrentIdxReg, RegState::Kill) 3668 .addImm(Offset); 3669 } 3670 } else { 3671 // Move index from VCC into M0 3672 if (Offset == 0) { 3673 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3674 .addReg(CurrentIdxReg, RegState::Kill); 3675 } else { 3676 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3677 .addReg(CurrentIdxReg, RegState::Kill) 3678 .addImm(Offset); 3679 } 3680 } 3681 3682 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3683 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3684 MachineInstr *InsertPt = 3685 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3686 : AMDGPU::S_XOR_B64_term), Exec) 3687 .addReg(Exec) 3688 .addReg(NewExec); 3689 3690 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3691 // s_cbranch_scc0? 3692 3693 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3694 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3695 .addMBB(&LoopBB); 3696 3697 return InsertPt->getIterator(); 3698 } 3699 3700 // This has slightly sub-optimal regalloc when the source vector is killed by 3701 // the read. The register allocator does not understand that the kill is 3702 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3703 // subregister from it, using 1 more VGPR than necessary. This was saved when 3704 // this was expanded after register allocation. 3705 static MachineBasicBlock::iterator 3706 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3707 unsigned InitResultReg, unsigned PhiReg, int Offset, 3708 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3709 MachineFunction *MF = MBB.getParent(); 3710 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3711 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3712 MachineRegisterInfo &MRI = MF->getRegInfo(); 3713 const DebugLoc &DL = MI.getDebugLoc(); 3714 MachineBasicBlock::iterator I(&MI); 3715 3716 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3717 Register DstReg = MI.getOperand(0).getReg(); 3718 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3719 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3720 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3721 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3722 3723 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3724 3725 // Save the EXEC mask 3726 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3727 .addReg(Exec); 3728 3729 MachineBasicBlock *LoopBB; 3730 MachineBasicBlock *RemainderBB; 3731 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3732 3733 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3734 3735 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3736 InitResultReg, DstReg, PhiReg, TmpExec, 3737 Offset, UseGPRIdxMode, SGPRIdxReg); 3738 3739 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3740 MachineFunction::iterator MBBI(LoopBB); 3741 ++MBBI; 3742 MF->insert(MBBI, LandingPad); 3743 LoopBB->removeSuccessor(RemainderBB); 3744 LandingPad->addSuccessor(RemainderBB); 3745 LoopBB->addSuccessor(LandingPad); 3746 MachineBasicBlock::iterator First = LandingPad->begin(); 3747 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3748 .addReg(SaveExec); 3749 3750 return InsPt; 3751 } 3752 3753 // Returns subreg index, offset 3754 static std::pair<unsigned, int> 3755 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3756 const TargetRegisterClass *SuperRC, 3757 unsigned VecReg, 3758 int Offset) { 3759 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3760 3761 // Skip out of bounds offsets, or else we would end up using an undefined 3762 // register. 3763 if (Offset >= NumElts || Offset < 0) 3764 return std::make_pair(AMDGPU::sub0, Offset); 3765 3766 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3767 } 3768 3769 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3770 MachineRegisterInfo &MRI, MachineInstr &MI, 3771 int Offset) { 3772 MachineBasicBlock *MBB = MI.getParent(); 3773 const DebugLoc &DL = MI.getDebugLoc(); 3774 MachineBasicBlock::iterator I(&MI); 3775 3776 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3777 3778 assert(Idx->getReg() != AMDGPU::NoRegister); 3779 3780 if (Offset == 0) { 3781 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3782 } else { 3783 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3784 .add(*Idx) 3785 .addImm(Offset); 3786 } 3787 } 3788 3789 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3790 MachineRegisterInfo &MRI, MachineInstr &MI, 3791 int Offset) { 3792 MachineBasicBlock *MBB = MI.getParent(); 3793 const DebugLoc &DL = MI.getDebugLoc(); 3794 MachineBasicBlock::iterator I(&MI); 3795 3796 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3797 3798 if (Offset == 0) 3799 return Idx->getReg(); 3800 3801 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3802 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3803 .add(*Idx) 3804 .addImm(Offset); 3805 return Tmp; 3806 } 3807 3808 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3809 MachineBasicBlock &MBB, 3810 const GCNSubtarget &ST) { 3811 const SIInstrInfo *TII = ST.getInstrInfo(); 3812 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3813 MachineFunction *MF = MBB.getParent(); 3814 MachineRegisterInfo &MRI = MF->getRegInfo(); 3815 3816 Register Dst = MI.getOperand(0).getReg(); 3817 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3818 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3819 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3820 3821 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3822 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3823 3824 unsigned SubReg; 3825 std::tie(SubReg, Offset) 3826 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3827 3828 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3829 3830 // Check for a SGPR index. 3831 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3832 MachineBasicBlock::iterator I(&MI); 3833 const DebugLoc &DL = MI.getDebugLoc(); 3834 3835 if (UseGPRIdxMode) { 3836 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3837 // to avoid interfering with other uses, so probably requires a new 3838 // optimization pass. 3839 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3840 3841 const MCInstrDesc &GPRIDXDesc = 3842 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3843 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3844 .addReg(SrcReg) 3845 .addReg(Idx) 3846 .addImm(SubReg); 3847 } else { 3848 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3849 3850 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3851 .addReg(SrcReg, 0, SubReg) 3852 .addReg(SrcReg, RegState::Implicit); 3853 } 3854 3855 MI.eraseFromParent(); 3856 3857 return &MBB; 3858 } 3859 3860 // Control flow needs to be inserted if indexing with a VGPR. 3861 const DebugLoc &DL = MI.getDebugLoc(); 3862 MachineBasicBlock::iterator I(&MI); 3863 3864 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3865 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3866 3867 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3868 3869 Register SGPRIdxReg; 3870 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3871 UseGPRIdxMode, SGPRIdxReg); 3872 3873 MachineBasicBlock *LoopBB = InsPt->getParent(); 3874 3875 if (UseGPRIdxMode) { 3876 const MCInstrDesc &GPRIDXDesc = 3877 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3878 3879 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3880 .addReg(SrcReg) 3881 .addReg(SGPRIdxReg) 3882 .addImm(SubReg); 3883 } else { 3884 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3885 .addReg(SrcReg, 0, SubReg) 3886 .addReg(SrcReg, RegState::Implicit); 3887 } 3888 3889 MI.eraseFromParent(); 3890 3891 return LoopBB; 3892 } 3893 3894 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3895 MachineBasicBlock &MBB, 3896 const GCNSubtarget &ST) { 3897 const SIInstrInfo *TII = ST.getInstrInfo(); 3898 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3899 MachineFunction *MF = MBB.getParent(); 3900 MachineRegisterInfo &MRI = MF->getRegInfo(); 3901 3902 Register Dst = MI.getOperand(0).getReg(); 3903 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3904 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3905 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3906 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3907 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3908 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3909 3910 // This can be an immediate, but will be folded later. 3911 assert(Val->getReg()); 3912 3913 unsigned SubReg; 3914 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3915 SrcVec->getReg(), 3916 Offset); 3917 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3918 3919 if (Idx->getReg() == AMDGPU::NoRegister) { 3920 MachineBasicBlock::iterator I(&MI); 3921 const DebugLoc &DL = MI.getDebugLoc(); 3922 3923 assert(Offset == 0); 3924 3925 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3926 .add(*SrcVec) 3927 .add(*Val) 3928 .addImm(SubReg); 3929 3930 MI.eraseFromParent(); 3931 return &MBB; 3932 } 3933 3934 // Check for a SGPR index. 3935 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3936 MachineBasicBlock::iterator I(&MI); 3937 const DebugLoc &DL = MI.getDebugLoc(); 3938 3939 if (UseGPRIdxMode) { 3940 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3941 3942 const MCInstrDesc &GPRIDXDesc = 3943 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3944 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3945 .addReg(SrcVec->getReg()) 3946 .add(*Val) 3947 .addReg(Idx) 3948 .addImm(SubReg); 3949 } else { 3950 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3951 3952 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3953 TRI.getRegSizeInBits(*VecRC), 32, false); 3954 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3955 .addReg(SrcVec->getReg()) 3956 .add(*Val) 3957 .addImm(SubReg); 3958 } 3959 MI.eraseFromParent(); 3960 return &MBB; 3961 } 3962 3963 // Control flow needs to be inserted if indexing with a VGPR. 3964 if (Val->isReg()) 3965 MRI.clearKillFlags(Val->getReg()); 3966 3967 const DebugLoc &DL = MI.getDebugLoc(); 3968 3969 Register PhiReg = MRI.createVirtualRegister(VecRC); 3970 3971 Register SGPRIdxReg; 3972 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3973 UseGPRIdxMode, SGPRIdxReg); 3974 MachineBasicBlock *LoopBB = InsPt->getParent(); 3975 3976 if (UseGPRIdxMode) { 3977 const MCInstrDesc &GPRIDXDesc = 3978 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3979 3980 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3981 .addReg(PhiReg) 3982 .add(*Val) 3983 .addReg(SGPRIdxReg) 3984 .addImm(AMDGPU::sub0); 3985 } else { 3986 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3987 TRI.getRegSizeInBits(*VecRC), 32, false); 3988 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3989 .addReg(PhiReg) 3990 .add(*Val) 3991 .addImm(AMDGPU::sub0); 3992 } 3993 3994 MI.eraseFromParent(); 3995 return LoopBB; 3996 } 3997 3998 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3999 MachineInstr &MI, MachineBasicBlock *BB) const { 4000 4001 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4002 MachineFunction *MF = BB->getParent(); 4003 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4004 4005 switch (MI.getOpcode()) { 4006 case AMDGPU::S_UADDO_PSEUDO: 4007 case AMDGPU::S_USUBO_PSEUDO: { 4008 const DebugLoc &DL = MI.getDebugLoc(); 4009 MachineOperand &Dest0 = MI.getOperand(0); 4010 MachineOperand &Dest1 = MI.getOperand(1); 4011 MachineOperand &Src0 = MI.getOperand(2); 4012 MachineOperand &Src1 = MI.getOperand(3); 4013 4014 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4015 ? AMDGPU::S_ADD_I32 4016 : AMDGPU::S_SUB_I32; 4017 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4018 4019 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4020 .addImm(1) 4021 .addImm(0); 4022 4023 MI.eraseFromParent(); 4024 return BB; 4025 } 4026 case AMDGPU::S_ADD_U64_PSEUDO: 4027 case AMDGPU::S_SUB_U64_PSEUDO: { 4028 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4029 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4030 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4031 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4032 const DebugLoc &DL = MI.getDebugLoc(); 4033 4034 MachineOperand &Dest = MI.getOperand(0); 4035 MachineOperand &Src0 = MI.getOperand(1); 4036 MachineOperand &Src1 = MI.getOperand(2); 4037 4038 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4039 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4040 4041 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4042 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4043 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4044 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4045 4046 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4047 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4048 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4049 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4050 4051 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4052 4053 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4054 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4055 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4056 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4057 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4058 .addReg(DestSub0) 4059 .addImm(AMDGPU::sub0) 4060 .addReg(DestSub1) 4061 .addImm(AMDGPU::sub1); 4062 MI.eraseFromParent(); 4063 return BB; 4064 } 4065 case AMDGPU::V_ADD_U64_PSEUDO: 4066 case AMDGPU::V_SUB_U64_PSEUDO: { 4067 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4068 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4069 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4070 const DebugLoc &DL = MI.getDebugLoc(); 4071 4072 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4073 4074 MachineOperand &Dest = MI.getOperand(0); 4075 MachineOperand &Src0 = MI.getOperand(1); 4076 MachineOperand &Src1 = MI.getOperand(2); 4077 4078 if (IsAdd && ST.hasLshlAddB64()) { 4079 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4080 Dest.getReg()) 4081 .add(Src0) 4082 .addImm(0) 4083 .add(Src1); 4084 TII->legalizeOperands(*Add); 4085 MI.eraseFromParent(); 4086 return BB; 4087 } 4088 4089 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4090 4091 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4092 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4093 4094 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4095 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4096 4097 const TargetRegisterClass *Src0RC = Src0.isReg() 4098 ? MRI.getRegClass(Src0.getReg()) 4099 : &AMDGPU::VReg_64RegClass; 4100 const TargetRegisterClass *Src1RC = Src1.isReg() 4101 ? MRI.getRegClass(Src1.getReg()) 4102 : &AMDGPU::VReg_64RegClass; 4103 4104 const TargetRegisterClass *Src0SubRC = 4105 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4106 const TargetRegisterClass *Src1SubRC = 4107 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4108 4109 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4110 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4111 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4112 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4113 4114 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4115 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4116 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4117 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4118 4119 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4120 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4121 .addReg(CarryReg, RegState::Define) 4122 .add(SrcReg0Sub0) 4123 .add(SrcReg1Sub0) 4124 .addImm(0); // clamp bit 4125 4126 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4127 MachineInstr *HiHalf = 4128 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4129 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4130 .add(SrcReg0Sub1) 4131 .add(SrcReg1Sub1) 4132 .addReg(CarryReg, RegState::Kill) 4133 .addImm(0); // clamp bit 4134 4135 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4136 .addReg(DestSub0) 4137 .addImm(AMDGPU::sub0) 4138 .addReg(DestSub1) 4139 .addImm(AMDGPU::sub1); 4140 TII->legalizeOperands(*LoHalf); 4141 TII->legalizeOperands(*HiHalf); 4142 MI.eraseFromParent(); 4143 return BB; 4144 } 4145 case AMDGPU::S_ADD_CO_PSEUDO: 4146 case AMDGPU::S_SUB_CO_PSEUDO: { 4147 // This pseudo has a chance to be selected 4148 // only from uniform add/subcarry node. All the VGPR operands 4149 // therefore assumed to be splat vectors. 4150 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4151 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4152 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4153 MachineBasicBlock::iterator MII = MI; 4154 const DebugLoc &DL = MI.getDebugLoc(); 4155 MachineOperand &Dest = MI.getOperand(0); 4156 MachineOperand &CarryDest = MI.getOperand(1); 4157 MachineOperand &Src0 = MI.getOperand(2); 4158 MachineOperand &Src1 = MI.getOperand(3); 4159 MachineOperand &Src2 = MI.getOperand(4); 4160 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4161 ? AMDGPU::S_ADDC_U32 4162 : AMDGPU::S_SUBB_U32; 4163 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4164 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4165 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4166 .addReg(Src0.getReg()); 4167 Src0.setReg(RegOp0); 4168 } 4169 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4170 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4171 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4172 .addReg(Src1.getReg()); 4173 Src1.setReg(RegOp1); 4174 } 4175 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4176 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4177 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4178 .addReg(Src2.getReg()); 4179 Src2.setReg(RegOp2); 4180 } 4181 4182 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4183 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4184 assert(WaveSize == 64 || WaveSize == 32); 4185 4186 if (WaveSize == 64) { 4187 if (ST.hasScalarCompareEq64()) { 4188 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4189 .addReg(Src2.getReg()) 4190 .addImm(0); 4191 } else { 4192 const TargetRegisterClass *SubRC = 4193 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4194 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4195 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4196 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4197 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4198 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4199 4200 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4201 .add(Src2Sub0) 4202 .add(Src2Sub1); 4203 4204 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4205 .addReg(Src2_32, RegState::Kill) 4206 .addImm(0); 4207 } 4208 } else { 4209 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4210 .addReg(Src2.getReg()) 4211 .addImm(0); 4212 } 4213 4214 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4215 4216 unsigned SelOpc = 4217 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4218 4219 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4220 .addImm(-1) 4221 .addImm(0); 4222 4223 MI.eraseFromParent(); 4224 return BB; 4225 } 4226 case AMDGPU::SI_INIT_M0: { 4227 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4228 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4229 .add(MI.getOperand(0)); 4230 MI.eraseFromParent(); 4231 return BB; 4232 } 4233 case AMDGPU::GET_GROUPSTATICSIZE: { 4234 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4235 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4236 DebugLoc DL = MI.getDebugLoc(); 4237 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4238 .add(MI.getOperand(0)) 4239 .addImm(MFI->getLDSSize()); 4240 MI.eraseFromParent(); 4241 return BB; 4242 } 4243 case AMDGPU::SI_INDIRECT_SRC_V1: 4244 case AMDGPU::SI_INDIRECT_SRC_V2: 4245 case AMDGPU::SI_INDIRECT_SRC_V4: 4246 case AMDGPU::SI_INDIRECT_SRC_V8: 4247 case AMDGPU::SI_INDIRECT_SRC_V16: 4248 case AMDGPU::SI_INDIRECT_SRC_V32: 4249 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4250 case AMDGPU::SI_INDIRECT_DST_V1: 4251 case AMDGPU::SI_INDIRECT_DST_V2: 4252 case AMDGPU::SI_INDIRECT_DST_V4: 4253 case AMDGPU::SI_INDIRECT_DST_V8: 4254 case AMDGPU::SI_INDIRECT_DST_V16: 4255 case AMDGPU::SI_INDIRECT_DST_V32: 4256 return emitIndirectDst(MI, *BB, *getSubtarget()); 4257 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4258 case AMDGPU::SI_KILL_I1_PSEUDO: 4259 return splitKillBlock(MI, BB); 4260 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4261 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4262 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4263 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4264 4265 Register Dst = MI.getOperand(0).getReg(); 4266 Register Src0 = MI.getOperand(1).getReg(); 4267 Register Src1 = MI.getOperand(2).getReg(); 4268 const DebugLoc &DL = MI.getDebugLoc(); 4269 Register SrcCond = MI.getOperand(3).getReg(); 4270 4271 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4272 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4273 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4274 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4275 4276 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4277 .addReg(SrcCond); 4278 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4279 .addImm(0) 4280 .addReg(Src0, 0, AMDGPU::sub0) 4281 .addImm(0) 4282 .addReg(Src1, 0, AMDGPU::sub0) 4283 .addReg(SrcCondCopy); 4284 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4285 .addImm(0) 4286 .addReg(Src0, 0, AMDGPU::sub1) 4287 .addImm(0) 4288 .addReg(Src1, 0, AMDGPU::sub1) 4289 .addReg(SrcCondCopy); 4290 4291 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4292 .addReg(DstLo) 4293 .addImm(AMDGPU::sub0) 4294 .addReg(DstHi) 4295 .addImm(AMDGPU::sub1); 4296 MI.eraseFromParent(); 4297 return BB; 4298 } 4299 case AMDGPU::SI_BR_UNDEF: { 4300 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4301 const DebugLoc &DL = MI.getDebugLoc(); 4302 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4303 .add(MI.getOperand(0)); 4304 Br->getOperand(1).setIsUndef(true); // read undef SCC 4305 MI.eraseFromParent(); 4306 return BB; 4307 } 4308 case AMDGPU::ADJCALLSTACKUP: 4309 case AMDGPU::ADJCALLSTACKDOWN: { 4310 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4311 MachineInstrBuilder MIB(*MF, &MI); 4312 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4313 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4314 return BB; 4315 } 4316 case AMDGPU::SI_CALL_ISEL: { 4317 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4318 const DebugLoc &DL = MI.getDebugLoc(); 4319 4320 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4321 4322 MachineInstrBuilder MIB; 4323 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4324 4325 for (const MachineOperand &MO : MI.operands()) 4326 MIB.add(MO); 4327 4328 MIB.cloneMemRefs(MI); 4329 MI.eraseFromParent(); 4330 return BB; 4331 } 4332 case AMDGPU::V_ADD_CO_U32_e32: 4333 case AMDGPU::V_SUB_CO_U32_e32: 4334 case AMDGPU::V_SUBREV_CO_U32_e32: { 4335 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4336 const DebugLoc &DL = MI.getDebugLoc(); 4337 unsigned Opc = MI.getOpcode(); 4338 4339 bool NeedClampOperand = false; 4340 if (TII->pseudoToMCOpcode(Opc) == -1) { 4341 Opc = AMDGPU::getVOPe64(Opc); 4342 NeedClampOperand = true; 4343 } 4344 4345 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4346 if (TII->isVOP3(*I)) { 4347 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4348 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4349 I.addReg(TRI->getVCC(), RegState::Define); 4350 } 4351 I.add(MI.getOperand(1)) 4352 .add(MI.getOperand(2)); 4353 if (NeedClampOperand) 4354 I.addImm(0); // clamp bit for e64 encoding 4355 4356 TII->legalizeOperands(*I); 4357 4358 MI.eraseFromParent(); 4359 return BB; 4360 } 4361 case AMDGPU::V_ADDC_U32_e32: 4362 case AMDGPU::V_SUBB_U32_e32: 4363 case AMDGPU::V_SUBBREV_U32_e32: 4364 // These instructions have an implicit use of vcc which counts towards the 4365 // constant bus limit. 4366 TII->legalizeOperands(MI); 4367 return BB; 4368 case AMDGPU::DS_GWS_INIT: 4369 case AMDGPU::DS_GWS_SEMA_BR: 4370 case AMDGPU::DS_GWS_BARRIER: 4371 if (Subtarget->needsAlignedVGPRs()) { 4372 // Add implicit aligned super-reg to force alignment on the data operand. 4373 const DebugLoc &DL = MI.getDebugLoc(); 4374 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4375 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4376 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4377 Register DataReg = Op->getReg(); 4378 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4379 Register Undef = MRI.createVirtualRegister( 4380 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4381 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4382 Register NewVR = 4383 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4384 : &AMDGPU::VReg_64_Align2RegClass); 4385 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4386 .addReg(DataReg, 0, Op->getSubReg()) 4387 .addImm(AMDGPU::sub0) 4388 .addReg(Undef) 4389 .addImm(AMDGPU::sub1); 4390 Op->setReg(NewVR); 4391 Op->setSubReg(AMDGPU::sub0); 4392 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4393 } 4394 LLVM_FALLTHROUGH; 4395 case AMDGPU::DS_GWS_SEMA_V: 4396 case AMDGPU::DS_GWS_SEMA_P: 4397 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4398 // A s_waitcnt 0 is required to be the instruction immediately following. 4399 if (getSubtarget()->hasGWSAutoReplay()) { 4400 bundleInstWithWaitcnt(MI); 4401 return BB; 4402 } 4403 4404 return emitGWSMemViolTestLoop(MI, BB); 4405 case AMDGPU::S_SETREG_B32: { 4406 // Try to optimize cases that only set the denormal mode or rounding mode. 4407 // 4408 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4409 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4410 // instead. 4411 // 4412 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4413 // allow you to have a no side effect instruction in the output of a 4414 // sideeffecting pattern. 4415 unsigned ID, Offset, Width; 4416 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4417 if (ID != AMDGPU::Hwreg::ID_MODE) 4418 return BB; 4419 4420 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4421 const unsigned SetMask = WidthMask << Offset; 4422 4423 if (getSubtarget()->hasDenormModeInst()) { 4424 unsigned SetDenormOp = 0; 4425 unsigned SetRoundOp = 0; 4426 4427 // The dedicated instructions can only set the whole denorm or round mode 4428 // at once, not a subset of bits in either. 4429 if (SetMask == 4430 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4431 // If this fully sets both the round and denorm mode, emit the two 4432 // dedicated instructions for these. 4433 SetRoundOp = AMDGPU::S_ROUND_MODE; 4434 SetDenormOp = AMDGPU::S_DENORM_MODE; 4435 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4436 SetRoundOp = AMDGPU::S_ROUND_MODE; 4437 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4438 SetDenormOp = AMDGPU::S_DENORM_MODE; 4439 } 4440 4441 if (SetRoundOp || SetDenormOp) { 4442 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4443 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4444 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4445 unsigned ImmVal = Def->getOperand(1).getImm(); 4446 if (SetRoundOp) { 4447 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4448 .addImm(ImmVal & 0xf); 4449 4450 // If we also have the denorm mode, get just the denorm mode bits. 4451 ImmVal >>= 4; 4452 } 4453 4454 if (SetDenormOp) { 4455 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4456 .addImm(ImmVal & 0xf); 4457 } 4458 4459 MI.eraseFromParent(); 4460 return BB; 4461 } 4462 } 4463 } 4464 4465 // If only FP bits are touched, used the no side effects pseudo. 4466 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4467 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4468 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4469 4470 return BB; 4471 } 4472 default: 4473 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4474 } 4475 } 4476 4477 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4478 return isTypeLegal(VT.getScalarType()); 4479 } 4480 4481 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4482 // This currently forces unfolding various combinations of fsub into fma with 4483 // free fneg'd operands. As long as we have fast FMA (controlled by 4484 // isFMAFasterThanFMulAndFAdd), we should perform these. 4485 4486 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4487 // most of these combines appear to be cycle neutral but save on instruction 4488 // count / code size. 4489 return true; 4490 } 4491 4492 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4493 4494 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4495 EVT VT) const { 4496 if (!VT.isVector()) { 4497 return MVT::i1; 4498 } 4499 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4500 } 4501 4502 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4503 // TODO: Should i16 be used always if legal? For now it would force VALU 4504 // shifts. 4505 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4506 } 4507 4508 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4509 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4510 ? Ty.changeElementSize(16) 4511 : Ty.changeElementSize(32); 4512 } 4513 4514 // Answering this is somewhat tricky and depends on the specific device which 4515 // have different rates for fma or all f64 operations. 4516 // 4517 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4518 // regardless of which device (although the number of cycles differs between 4519 // devices), so it is always profitable for f64. 4520 // 4521 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4522 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4523 // which we can always do even without fused FP ops since it returns the same 4524 // result as the separate operations and since it is always full 4525 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4526 // however does not support denormals, so we do report fma as faster if we have 4527 // a fast fma device and require denormals. 4528 // 4529 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4530 EVT VT) const { 4531 VT = VT.getScalarType(); 4532 4533 switch (VT.getSimpleVT().SimpleTy) { 4534 case MVT::f32: { 4535 // If mad is not available this depends only on if f32 fma is full rate. 4536 if (!Subtarget->hasMadMacF32Insts()) 4537 return Subtarget->hasFastFMAF32(); 4538 4539 // Otherwise f32 mad is always full rate and returns the same result as 4540 // the separate operations so should be preferred over fma. 4541 // However does not support denormals. 4542 if (hasFP32Denormals(MF)) 4543 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4544 4545 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4546 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4547 } 4548 case MVT::f64: 4549 return true; 4550 case MVT::f16: 4551 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4552 default: 4553 break; 4554 } 4555 4556 return false; 4557 } 4558 4559 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4560 LLT Ty) const { 4561 switch (Ty.getScalarSizeInBits()) { 4562 case 16: 4563 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4564 case 32: 4565 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4566 case 64: 4567 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4568 default: 4569 break; 4570 } 4571 4572 return false; 4573 } 4574 4575 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4576 if (!Ty.isScalar()) 4577 return false; 4578 4579 if (Ty.getScalarSizeInBits() == 16) 4580 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4581 if (Ty.getScalarSizeInBits() == 32) 4582 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4583 4584 return false; 4585 } 4586 4587 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4588 const SDNode *N) const { 4589 // TODO: Check future ftz flag 4590 // v_mad_f32/v_mac_f32 do not support denormals. 4591 EVT VT = N->getValueType(0); 4592 if (VT == MVT::f32) 4593 return Subtarget->hasMadMacF32Insts() && 4594 !hasFP32Denormals(DAG.getMachineFunction()); 4595 if (VT == MVT::f16) { 4596 return Subtarget->hasMadF16() && 4597 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4598 } 4599 4600 return false; 4601 } 4602 4603 //===----------------------------------------------------------------------===// 4604 // Custom DAG Lowering Operations 4605 //===----------------------------------------------------------------------===// 4606 4607 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4608 // wider vector type is legal. 4609 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4610 SelectionDAG &DAG) const { 4611 unsigned Opc = Op.getOpcode(); 4612 EVT VT = Op.getValueType(); 4613 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4614 4615 SDValue Lo, Hi; 4616 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4617 4618 SDLoc SL(Op); 4619 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4620 Op->getFlags()); 4621 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4622 Op->getFlags()); 4623 4624 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4625 } 4626 4627 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4628 // wider vector type is legal. 4629 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4630 SelectionDAG &DAG) const { 4631 unsigned Opc = Op.getOpcode(); 4632 EVT VT = Op.getValueType(); 4633 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4634 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4635 VT == MVT::v16f32 || VT == MVT::v32f32); 4636 4637 SDValue Lo0, Hi0; 4638 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4639 SDValue Lo1, Hi1; 4640 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4641 4642 SDLoc SL(Op); 4643 4644 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4645 Op->getFlags()); 4646 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4647 Op->getFlags()); 4648 4649 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4650 } 4651 4652 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4653 SelectionDAG &DAG) const { 4654 unsigned Opc = Op.getOpcode(); 4655 EVT VT = Op.getValueType(); 4656 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4657 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4658 VT == MVT::v16f32 || VT == MVT::v32f32); 4659 4660 SDValue Lo0, Hi0; 4661 SDValue Op0 = Op.getOperand(0); 4662 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4663 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4664 : std::make_pair(Op0, Op0); 4665 SDValue Lo1, Hi1; 4666 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4667 SDValue Lo2, Hi2; 4668 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4669 4670 SDLoc SL(Op); 4671 auto ResVT = DAG.GetSplitDestVTs(VT); 4672 4673 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4674 Op->getFlags()); 4675 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4676 Op->getFlags()); 4677 4678 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4679 } 4680 4681 4682 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4683 switch (Op.getOpcode()) { 4684 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4685 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4686 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4687 case ISD::LOAD: { 4688 SDValue Result = LowerLOAD(Op, DAG); 4689 assert((!Result.getNode() || 4690 Result.getNode()->getNumValues() == 2) && 4691 "Load should return a value and a chain"); 4692 return Result; 4693 } 4694 4695 case ISD::FSIN: 4696 case ISD::FCOS: 4697 return LowerTrig(Op, DAG); 4698 case ISD::SELECT: return LowerSELECT(Op, DAG); 4699 case ISD::FDIV: return LowerFDIV(Op, DAG); 4700 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4701 case ISD::STORE: return LowerSTORE(Op, DAG); 4702 case ISD::GlobalAddress: { 4703 MachineFunction &MF = DAG.getMachineFunction(); 4704 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4705 return LowerGlobalAddress(MFI, Op, DAG); 4706 } 4707 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4708 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4709 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4710 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4711 case ISD::INSERT_SUBVECTOR: 4712 return lowerINSERT_SUBVECTOR(Op, DAG); 4713 case ISD::INSERT_VECTOR_ELT: 4714 return lowerINSERT_VECTOR_ELT(Op, DAG); 4715 case ISD::EXTRACT_VECTOR_ELT: 4716 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4717 case ISD::VECTOR_SHUFFLE: 4718 return lowerVECTOR_SHUFFLE(Op, DAG); 4719 case ISD::BUILD_VECTOR: 4720 return lowerBUILD_VECTOR(Op, DAG); 4721 case ISD::FP_ROUND: 4722 return lowerFP_ROUND(Op, DAG); 4723 case ISD::FPTRUNC_ROUND: { 4724 unsigned Opc; 4725 SDLoc DL(Op); 4726 4727 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4728 return SDValue(); 4729 4730 // Get the rounding mode from the last operand 4731 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4732 if (RoundMode == (int)RoundingMode::TowardPositive) 4733 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4734 else if (RoundMode == (int)RoundingMode::TowardNegative) 4735 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4736 else 4737 return SDValue(); 4738 4739 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4740 } 4741 case ISD::TRAP: 4742 return lowerTRAP(Op, DAG); 4743 case ISD::DEBUGTRAP: 4744 return lowerDEBUGTRAP(Op, DAG); 4745 case ISD::FABS: 4746 case ISD::FNEG: 4747 case ISD::FCANONICALIZE: 4748 case ISD::BSWAP: 4749 return splitUnaryVectorOp(Op, DAG); 4750 case ISD::FMINNUM: 4751 case ISD::FMAXNUM: 4752 return lowerFMINNUM_FMAXNUM(Op, DAG); 4753 case ISD::FMA: 4754 return splitTernaryVectorOp(Op, DAG); 4755 case ISD::FP_TO_SINT: 4756 case ISD::FP_TO_UINT: 4757 return LowerFP_TO_INT(Op, DAG); 4758 case ISD::SHL: 4759 case ISD::SRA: 4760 case ISD::SRL: 4761 case ISD::ADD: 4762 case ISD::SUB: 4763 case ISD::MUL: 4764 case ISD::SMIN: 4765 case ISD::SMAX: 4766 case ISD::UMIN: 4767 case ISD::UMAX: 4768 case ISD::FADD: 4769 case ISD::FMUL: 4770 case ISD::FMINNUM_IEEE: 4771 case ISD::FMAXNUM_IEEE: 4772 case ISD::UADDSAT: 4773 case ISD::USUBSAT: 4774 case ISD::SADDSAT: 4775 case ISD::SSUBSAT: 4776 return splitBinaryVectorOp(Op, DAG); 4777 case ISD::SMULO: 4778 case ISD::UMULO: 4779 return lowerXMULO(Op, DAG); 4780 case ISD::SMUL_LOHI: 4781 case ISD::UMUL_LOHI: 4782 return lowerXMUL_LOHI(Op, DAG); 4783 case ISD::DYNAMIC_STACKALLOC: 4784 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4785 } 4786 return SDValue(); 4787 } 4788 4789 // Used for D16: Casts the result of an instruction into the right vector, 4790 // packs values if loads return unpacked values. 4791 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4792 const SDLoc &DL, 4793 SelectionDAG &DAG, bool Unpacked) { 4794 if (!LoadVT.isVector()) 4795 return Result; 4796 4797 // Cast back to the original packed type or to a larger type that is a 4798 // multiple of 32 bit for D16. Widening the return type is a required for 4799 // legalization. 4800 EVT FittingLoadVT = LoadVT; 4801 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4802 FittingLoadVT = 4803 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4804 LoadVT.getVectorNumElements() + 1); 4805 } 4806 4807 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4808 // Truncate to v2i16/v4i16. 4809 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4810 4811 // Workaround legalizer not scalarizing truncate after vector op 4812 // legalization but not creating intermediate vector trunc. 4813 SmallVector<SDValue, 4> Elts; 4814 DAG.ExtractVectorElements(Result, Elts); 4815 for (SDValue &Elt : Elts) 4816 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4817 4818 // Pad illegal v1i16/v3fi6 to v4i16 4819 if ((LoadVT.getVectorNumElements() % 2) == 1) 4820 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4821 4822 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4823 4824 // Bitcast to original type (v2f16/v4f16). 4825 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4826 } 4827 4828 // Cast back to the original packed type. 4829 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4830 } 4831 4832 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4833 MemSDNode *M, 4834 SelectionDAG &DAG, 4835 ArrayRef<SDValue> Ops, 4836 bool IsIntrinsic) const { 4837 SDLoc DL(M); 4838 4839 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4840 EVT LoadVT = M->getValueType(0); 4841 4842 EVT EquivLoadVT = LoadVT; 4843 if (LoadVT.isVector()) { 4844 if (Unpacked) { 4845 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4846 LoadVT.getVectorNumElements()); 4847 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4848 // Widen v3f16 to legal type 4849 EquivLoadVT = 4850 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4851 LoadVT.getVectorNumElements() + 1); 4852 } 4853 } 4854 4855 // Change from v4f16/v2f16 to EquivLoadVT. 4856 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4857 4858 SDValue Load 4859 = DAG.getMemIntrinsicNode( 4860 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4861 VTList, Ops, M->getMemoryVT(), 4862 M->getMemOperand()); 4863 4864 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4865 4866 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4867 } 4868 4869 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4870 SelectionDAG &DAG, 4871 ArrayRef<SDValue> Ops) const { 4872 SDLoc DL(M); 4873 EVT LoadVT = M->getValueType(0); 4874 EVT EltType = LoadVT.getScalarType(); 4875 EVT IntVT = LoadVT.changeTypeToInteger(); 4876 4877 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4878 4879 unsigned Opc = 4880 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4881 4882 if (IsD16) { 4883 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4884 } 4885 4886 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4887 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4888 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4889 4890 if (isTypeLegal(LoadVT)) { 4891 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4892 M->getMemOperand(), DAG); 4893 } 4894 4895 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4896 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4897 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4898 M->getMemOperand(), DAG); 4899 return DAG.getMergeValues( 4900 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4901 DL); 4902 } 4903 4904 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4905 SDNode *N, SelectionDAG &DAG) { 4906 EVT VT = N->getValueType(0); 4907 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4908 unsigned CondCode = CD->getZExtValue(); 4909 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4910 return DAG.getUNDEF(VT); 4911 4912 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4913 4914 SDValue LHS = N->getOperand(1); 4915 SDValue RHS = N->getOperand(2); 4916 4917 SDLoc DL(N); 4918 4919 EVT CmpVT = LHS.getValueType(); 4920 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4921 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4922 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4923 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4924 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4925 } 4926 4927 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4928 4929 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4930 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4931 4932 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4933 DAG.getCondCode(CCOpcode)); 4934 if (VT.bitsEq(CCVT)) 4935 return SetCC; 4936 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4937 } 4938 4939 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4940 SDNode *N, SelectionDAG &DAG) { 4941 EVT VT = N->getValueType(0); 4942 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4943 4944 unsigned CondCode = CD->getZExtValue(); 4945 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4946 return DAG.getUNDEF(VT); 4947 4948 SDValue Src0 = N->getOperand(1); 4949 SDValue Src1 = N->getOperand(2); 4950 EVT CmpVT = Src0.getValueType(); 4951 SDLoc SL(N); 4952 4953 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4954 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4955 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4956 } 4957 4958 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4959 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4960 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4961 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4962 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4963 Src1, DAG.getCondCode(CCOpcode)); 4964 if (VT.bitsEq(CCVT)) 4965 return SetCC; 4966 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4967 } 4968 4969 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4970 SelectionDAG &DAG) { 4971 EVT VT = N->getValueType(0); 4972 SDValue Src = N->getOperand(1); 4973 SDLoc SL(N); 4974 4975 if (Src.getOpcode() == ISD::SETCC) { 4976 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4977 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4978 Src.getOperand(1), Src.getOperand(2)); 4979 } 4980 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4981 // (ballot 0) -> 0 4982 if (Arg->isZero()) 4983 return DAG.getConstant(0, SL, VT); 4984 4985 // (ballot 1) -> EXEC/EXEC_LO 4986 if (Arg->isOne()) { 4987 Register Exec; 4988 if (VT.getScalarSizeInBits() == 32) 4989 Exec = AMDGPU::EXEC_LO; 4990 else if (VT.getScalarSizeInBits() == 64) 4991 Exec = AMDGPU::EXEC; 4992 else 4993 return SDValue(); 4994 4995 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4996 } 4997 } 4998 4999 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5000 // ISD::SETNE) 5001 return DAG.getNode( 5002 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5003 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5004 } 5005 5006 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5007 SmallVectorImpl<SDValue> &Results, 5008 SelectionDAG &DAG) const { 5009 switch (N->getOpcode()) { 5010 case ISD::INSERT_VECTOR_ELT: { 5011 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5012 Results.push_back(Res); 5013 return; 5014 } 5015 case ISD::EXTRACT_VECTOR_ELT: { 5016 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5017 Results.push_back(Res); 5018 return; 5019 } 5020 case ISD::INTRINSIC_WO_CHAIN: { 5021 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5022 switch (IID) { 5023 case Intrinsic::amdgcn_cvt_pkrtz: { 5024 SDValue Src0 = N->getOperand(1); 5025 SDValue Src1 = N->getOperand(2); 5026 SDLoc SL(N); 5027 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5028 Src0, Src1); 5029 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5030 return; 5031 } 5032 case Intrinsic::amdgcn_cvt_pknorm_i16: 5033 case Intrinsic::amdgcn_cvt_pknorm_u16: 5034 case Intrinsic::amdgcn_cvt_pk_i16: 5035 case Intrinsic::amdgcn_cvt_pk_u16: { 5036 SDValue Src0 = N->getOperand(1); 5037 SDValue Src1 = N->getOperand(2); 5038 SDLoc SL(N); 5039 unsigned Opcode; 5040 5041 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5042 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5043 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5044 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5045 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5046 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5047 else 5048 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5049 5050 EVT VT = N->getValueType(0); 5051 if (isTypeLegal(VT)) 5052 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5053 else { 5054 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5055 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5056 } 5057 return; 5058 } 5059 } 5060 break; 5061 } 5062 case ISD::INTRINSIC_W_CHAIN: { 5063 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5064 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5065 // FIXME: Hacky 5066 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5067 Results.push_back(Res.getOperand(I)); 5068 } 5069 } else { 5070 Results.push_back(Res); 5071 Results.push_back(Res.getValue(1)); 5072 } 5073 return; 5074 } 5075 5076 break; 5077 } 5078 case ISD::SELECT: { 5079 SDLoc SL(N); 5080 EVT VT = N->getValueType(0); 5081 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5082 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5083 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5084 5085 EVT SelectVT = NewVT; 5086 if (NewVT.bitsLT(MVT::i32)) { 5087 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5088 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5089 SelectVT = MVT::i32; 5090 } 5091 5092 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5093 N->getOperand(0), LHS, RHS); 5094 5095 if (NewVT != SelectVT) 5096 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5097 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5098 return; 5099 } 5100 case ISD::FNEG: { 5101 if (N->getValueType(0) != MVT::v2f16) 5102 break; 5103 5104 SDLoc SL(N); 5105 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5106 5107 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5108 BC, 5109 DAG.getConstant(0x80008000, SL, MVT::i32)); 5110 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5111 return; 5112 } 5113 case ISD::FABS: { 5114 if (N->getValueType(0) != MVT::v2f16) 5115 break; 5116 5117 SDLoc SL(N); 5118 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5119 5120 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5121 BC, 5122 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5123 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5124 return; 5125 } 5126 default: 5127 break; 5128 } 5129 } 5130 5131 /// Helper function for LowerBRCOND 5132 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5133 5134 SDNode *Parent = Value.getNode(); 5135 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5136 I != E; ++I) { 5137 5138 if (I.getUse().get() != Value) 5139 continue; 5140 5141 if (I->getOpcode() == Opcode) 5142 return *I; 5143 } 5144 return nullptr; 5145 } 5146 5147 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5148 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5149 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5150 case Intrinsic::amdgcn_if: 5151 return AMDGPUISD::IF; 5152 case Intrinsic::amdgcn_else: 5153 return AMDGPUISD::ELSE; 5154 case Intrinsic::amdgcn_loop: 5155 return AMDGPUISD::LOOP; 5156 case Intrinsic::amdgcn_end_cf: 5157 llvm_unreachable("should not occur"); 5158 default: 5159 return 0; 5160 } 5161 } 5162 5163 // break, if_break, else_break are all only used as inputs to loop, not 5164 // directly as branch conditions. 5165 return 0; 5166 } 5167 5168 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5169 const Triple &TT = getTargetMachine().getTargetTriple(); 5170 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5171 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5172 AMDGPU::shouldEmitConstantsToTextSection(TT); 5173 } 5174 5175 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5176 // FIXME: Either avoid relying on address space here or change the default 5177 // address space for functions to avoid the explicit check. 5178 return (GV->getValueType()->isFunctionTy() || 5179 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5180 !shouldEmitFixup(GV) && 5181 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5182 } 5183 5184 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5185 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5186 } 5187 5188 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5189 if (!GV->hasExternalLinkage()) 5190 return true; 5191 5192 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5193 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5194 } 5195 5196 /// This transforms the control flow intrinsics to get the branch destination as 5197 /// last parameter, also switches branch target with BR if the need arise 5198 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5199 SelectionDAG &DAG) const { 5200 SDLoc DL(BRCOND); 5201 5202 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5203 SDValue Target = BRCOND.getOperand(2); 5204 SDNode *BR = nullptr; 5205 SDNode *SetCC = nullptr; 5206 5207 if (Intr->getOpcode() == ISD::SETCC) { 5208 // As long as we negate the condition everything is fine 5209 SetCC = Intr; 5210 Intr = SetCC->getOperand(0).getNode(); 5211 5212 } else { 5213 // Get the target from BR if we don't negate the condition 5214 BR = findUser(BRCOND, ISD::BR); 5215 assert(BR && "brcond missing unconditional branch user"); 5216 Target = BR->getOperand(1); 5217 } 5218 5219 unsigned CFNode = isCFIntrinsic(Intr); 5220 if (CFNode == 0) { 5221 // This is a uniform branch so we don't need to legalize. 5222 return BRCOND; 5223 } 5224 5225 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5226 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5227 5228 assert(!SetCC || 5229 (SetCC->getConstantOperandVal(1) == 1 && 5230 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5231 ISD::SETNE)); 5232 5233 // operands of the new intrinsic call 5234 SmallVector<SDValue, 4> Ops; 5235 if (HaveChain) 5236 Ops.push_back(BRCOND.getOperand(0)); 5237 5238 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5239 Ops.push_back(Target); 5240 5241 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5242 5243 // build the new intrinsic call 5244 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5245 5246 if (!HaveChain) { 5247 SDValue Ops[] = { 5248 SDValue(Result, 0), 5249 BRCOND.getOperand(0) 5250 }; 5251 5252 Result = DAG.getMergeValues(Ops, DL).getNode(); 5253 } 5254 5255 if (BR) { 5256 // Give the branch instruction our target 5257 SDValue Ops[] = { 5258 BR->getOperand(0), 5259 BRCOND.getOperand(2) 5260 }; 5261 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5262 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5263 } 5264 5265 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5266 5267 // Copy the intrinsic results to registers 5268 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5269 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5270 if (!CopyToReg) 5271 continue; 5272 5273 Chain = DAG.getCopyToReg( 5274 Chain, DL, 5275 CopyToReg->getOperand(1), 5276 SDValue(Result, i - 1), 5277 SDValue()); 5278 5279 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5280 } 5281 5282 // Remove the old intrinsic from the chain 5283 DAG.ReplaceAllUsesOfValueWith( 5284 SDValue(Intr, Intr->getNumValues() - 1), 5285 Intr->getOperand(0)); 5286 5287 return Chain; 5288 } 5289 5290 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 MVT VT = Op.getSimpleValueType(); 5293 SDLoc DL(Op); 5294 // Checking the depth 5295 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5296 return DAG.getConstant(0, DL, VT); 5297 5298 MachineFunction &MF = DAG.getMachineFunction(); 5299 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5300 // Check for kernel and shader functions 5301 if (Info->isEntryFunction()) 5302 return DAG.getConstant(0, DL, VT); 5303 5304 MachineFrameInfo &MFI = MF.getFrameInfo(); 5305 // There is a call to @llvm.returnaddress in this function 5306 MFI.setReturnAddressIsTaken(true); 5307 5308 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5309 // Get the return address reg and mark it as an implicit live-in 5310 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5311 5312 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5313 } 5314 5315 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5316 SDValue Op, 5317 const SDLoc &DL, 5318 EVT VT) const { 5319 return Op.getValueType().bitsLE(VT) ? 5320 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5321 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5322 DAG.getTargetConstant(0, DL, MVT::i32)); 5323 } 5324 5325 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5326 assert(Op.getValueType() == MVT::f16 && 5327 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5328 5329 SDValue Src = Op.getOperand(0); 5330 EVT SrcVT = Src.getValueType(); 5331 if (SrcVT != MVT::f64) 5332 return Op; 5333 5334 SDLoc DL(Op); 5335 5336 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5337 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5338 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5339 } 5340 5341 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5342 SelectionDAG &DAG) const { 5343 EVT VT = Op.getValueType(); 5344 const MachineFunction &MF = DAG.getMachineFunction(); 5345 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5346 bool IsIEEEMode = Info->getMode().IEEE; 5347 5348 // FIXME: Assert during selection that this is only selected for 5349 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5350 // mode functions, but this happens to be OK since it's only done in cases 5351 // where there is known no sNaN. 5352 if (IsIEEEMode) 5353 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5354 5355 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5356 return splitBinaryVectorOp(Op, DAG); 5357 return Op; 5358 } 5359 5360 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5361 EVT VT = Op.getValueType(); 5362 SDLoc SL(Op); 5363 SDValue LHS = Op.getOperand(0); 5364 SDValue RHS = Op.getOperand(1); 5365 bool isSigned = Op.getOpcode() == ISD::SMULO; 5366 5367 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5368 const APInt &C = RHSC->getAPIntValue(); 5369 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5370 if (C.isPowerOf2()) { 5371 // smulo(x, signed_min) is same as umulo(x, signed_min). 5372 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5373 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5374 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5375 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5376 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5377 SL, VT, Result, ShiftAmt), 5378 LHS, ISD::SETNE); 5379 return DAG.getMergeValues({ Result, Overflow }, SL); 5380 } 5381 } 5382 5383 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5384 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5385 SL, VT, LHS, RHS); 5386 5387 SDValue Sign = isSigned 5388 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5389 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5390 : DAG.getConstant(0, SL, VT); 5391 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5392 5393 return DAG.getMergeValues({ Result, Overflow }, SL); 5394 } 5395 5396 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5397 if (Op->isDivergent()) { 5398 // Select to V_MAD_[IU]64_[IU]32. 5399 return Op; 5400 } 5401 if (Subtarget->hasSMulHi()) { 5402 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5403 return SDValue(); 5404 } 5405 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5406 // calculate the high part, so we might as well do the whole thing with 5407 // V_MAD_[IU]64_[IU]32. 5408 return Op; 5409 } 5410 5411 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5412 if (!Subtarget->isTrapHandlerEnabled() || 5413 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5414 return lowerTrapEndpgm(Op, DAG); 5415 5416 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5417 switch (*HsaAbiVer) { 5418 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5419 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5420 return lowerTrapHsaQueuePtr(Op, DAG); 5421 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5422 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5423 return Subtarget->supportsGetDoorbellID() ? 5424 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5425 } 5426 } 5427 5428 llvm_unreachable("Unknown trap handler"); 5429 } 5430 5431 SDValue SITargetLowering::lowerTrapEndpgm( 5432 SDValue Op, SelectionDAG &DAG) const { 5433 SDLoc SL(Op); 5434 SDValue Chain = Op.getOperand(0); 5435 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5436 } 5437 5438 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5439 SDValue Op, SelectionDAG &DAG) const { 5440 SDLoc SL(Op); 5441 SDValue Chain = Op.getOperand(0); 5442 5443 MachineFunction &MF = DAG.getMachineFunction(); 5444 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5445 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5446 5447 SDValue QueuePtr; 5448 if (UserSGPR == AMDGPU::NoRegister) { 5449 // We probably are in a function incorrectly marked with 5450 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5451 // so just use a null pointer. 5452 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5453 } else { 5454 QueuePtr = CreateLiveInRegister( 5455 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5456 } 5457 5458 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5459 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5460 QueuePtr, SDValue()); 5461 5462 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5463 SDValue Ops[] = { 5464 ToReg, 5465 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5466 SGPR01, 5467 ToReg.getValue(1) 5468 }; 5469 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5470 } 5471 5472 SDValue SITargetLowering::lowerTrapHsa( 5473 SDValue Op, SelectionDAG &DAG) const { 5474 SDLoc SL(Op); 5475 SDValue Chain = Op.getOperand(0); 5476 5477 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5478 SDValue Ops[] = { 5479 Chain, 5480 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5481 }; 5482 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5483 } 5484 5485 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5486 SDLoc SL(Op); 5487 SDValue Chain = Op.getOperand(0); 5488 MachineFunction &MF = DAG.getMachineFunction(); 5489 5490 if (!Subtarget->isTrapHandlerEnabled() || 5491 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5492 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5493 "debugtrap handler not supported", 5494 Op.getDebugLoc(), 5495 DS_Warning); 5496 LLVMContext &Ctx = MF.getFunction().getContext(); 5497 Ctx.diagnose(NoTrap); 5498 return Chain; 5499 } 5500 5501 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5502 SDValue Ops[] = { 5503 Chain, 5504 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5505 }; 5506 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5507 } 5508 5509 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5510 SelectionDAG &DAG) const { 5511 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5512 if (Subtarget->hasApertureRegs()) { 5513 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5514 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5515 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5516 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5517 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5518 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5519 unsigned Encoding = 5520 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5521 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5522 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5523 5524 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5525 SDValue ApertureReg = SDValue( 5526 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5527 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5528 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5529 } 5530 5531 MachineFunction &MF = DAG.getMachineFunction(); 5532 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5533 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5534 if (UserSGPR == AMDGPU::NoRegister) { 5535 // We probably are in a function incorrectly marked with 5536 // amdgpu-no-queue-ptr. This is undefined. 5537 return DAG.getUNDEF(MVT::i32); 5538 } 5539 5540 SDValue QueuePtr = CreateLiveInRegister( 5541 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5542 5543 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5544 // private_segment_aperture_base_hi. 5545 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5546 5547 SDValue Ptr = 5548 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5549 5550 // TODO: Use custom target PseudoSourceValue. 5551 // TODO: We should use the value from the IR intrinsic call, but it might not 5552 // be available and how do we get it? 5553 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5554 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5555 commonAlignment(Align(64), StructOffset), 5556 MachineMemOperand::MODereferenceable | 5557 MachineMemOperand::MOInvariant); 5558 } 5559 5560 /// Return true if the value is a known valid address, such that a null check is 5561 /// not necessary. 5562 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5563 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5564 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5565 isa<BasicBlockSDNode>(Val)) 5566 return true; 5567 5568 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5569 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5570 5571 // TODO: Search through arithmetic, handle arguments and loads 5572 // marked nonnull. 5573 return false; 5574 } 5575 5576 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5577 SelectionDAG &DAG) const { 5578 SDLoc SL(Op); 5579 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5580 5581 SDValue Src = ASC->getOperand(0); 5582 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5583 unsigned SrcAS = ASC->getSrcAddressSpace(); 5584 5585 const AMDGPUTargetMachine &TM = 5586 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5587 5588 // flat -> local/private 5589 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5590 unsigned DestAS = ASC->getDestAddressSpace(); 5591 5592 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5593 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5594 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5595 5596 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5597 return Ptr; 5598 5599 unsigned NullVal = TM.getNullPointerValue(DestAS); 5600 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5601 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5602 5603 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5604 SegmentNullPtr); 5605 } 5606 } 5607 5608 // local/private -> flat 5609 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5610 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5611 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5612 5613 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5614 SDValue CvtPtr = 5615 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5616 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5617 5618 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5619 return CvtPtr; 5620 5621 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5622 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5623 5624 SDValue NonNull 5625 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5626 5627 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5628 FlatNullPtr); 5629 } 5630 } 5631 5632 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5633 Op.getValueType() == MVT::i64) { 5634 const SIMachineFunctionInfo *Info = 5635 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5636 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5637 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5638 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5639 } 5640 5641 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5642 Src.getValueType() == MVT::i64) 5643 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5644 5645 // global <-> flat are no-ops and never emitted. 5646 5647 const MachineFunction &MF = DAG.getMachineFunction(); 5648 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5649 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5650 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5651 5652 return DAG.getUNDEF(ASC->getValueType(0)); 5653 } 5654 5655 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5656 // the small vector and inserting them into the big vector. That is better than 5657 // the default expansion of doing it via a stack slot. Even though the use of 5658 // the stack slot would be optimized away afterwards, the stack slot itself 5659 // remains. 5660 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5661 SelectionDAG &DAG) const { 5662 SDValue Vec = Op.getOperand(0); 5663 SDValue Ins = Op.getOperand(1); 5664 SDValue Idx = Op.getOperand(2); 5665 EVT VecVT = Vec.getValueType(); 5666 EVT InsVT = Ins.getValueType(); 5667 EVT EltVT = VecVT.getVectorElementType(); 5668 unsigned InsNumElts = InsVT.getVectorNumElements(); 5669 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5670 SDLoc SL(Op); 5671 5672 for (unsigned I = 0; I != InsNumElts; ++I) { 5673 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5674 DAG.getConstant(I, SL, MVT::i32)); 5675 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5676 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5677 } 5678 return Vec; 5679 } 5680 5681 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5682 SelectionDAG &DAG) const { 5683 SDValue Vec = Op.getOperand(0); 5684 SDValue InsVal = Op.getOperand(1); 5685 SDValue Idx = Op.getOperand(2); 5686 EVT VecVT = Vec.getValueType(); 5687 EVT EltVT = VecVT.getVectorElementType(); 5688 unsigned VecSize = VecVT.getSizeInBits(); 5689 unsigned EltSize = EltVT.getSizeInBits(); 5690 5691 5692 assert(VecSize <= 64); 5693 5694 unsigned NumElts = VecVT.getVectorNumElements(); 5695 SDLoc SL(Op); 5696 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5697 5698 if (NumElts == 4 && EltSize == 16 && KIdx) { 5699 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5700 5701 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5702 DAG.getConstant(0, SL, MVT::i32)); 5703 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5704 DAG.getConstant(1, SL, MVT::i32)); 5705 5706 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5707 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5708 5709 unsigned Idx = KIdx->getZExtValue(); 5710 bool InsertLo = Idx < 2; 5711 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5712 InsertLo ? LoVec : HiVec, 5713 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5714 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5715 5716 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5717 5718 SDValue Concat = InsertLo ? 5719 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5720 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5721 5722 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5723 } 5724 5725 if (isa<ConstantSDNode>(Idx)) 5726 return SDValue(); 5727 5728 MVT IntVT = MVT::getIntegerVT(VecSize); 5729 5730 // Avoid stack access for dynamic indexing. 5731 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5732 5733 // Create a congruent vector with the target value in each element so that 5734 // the required element can be masked and ORed into the target vector. 5735 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5736 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5737 5738 assert(isPowerOf2_32(EltSize)); 5739 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5740 5741 // Convert vector index to bit-index. 5742 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5743 5744 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5745 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5746 DAG.getConstant(0xffff, SL, IntVT), 5747 ScaledIdx); 5748 5749 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5750 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5751 DAG.getNOT(SL, BFM, IntVT), BCVec); 5752 5753 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5754 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5755 } 5756 5757 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5758 SelectionDAG &DAG) const { 5759 SDLoc SL(Op); 5760 5761 EVT ResultVT = Op.getValueType(); 5762 SDValue Vec = Op.getOperand(0); 5763 SDValue Idx = Op.getOperand(1); 5764 EVT VecVT = Vec.getValueType(); 5765 unsigned VecSize = VecVT.getSizeInBits(); 5766 EVT EltVT = VecVT.getVectorElementType(); 5767 5768 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5769 5770 // Make sure we do any optimizations that will make it easier to fold 5771 // source modifiers before obscuring it with bit operations. 5772 5773 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5774 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5775 return Combined; 5776 5777 if (VecSize == 128) { 5778 SDValue Lo, Hi; 5779 EVT LoVT, HiVT; 5780 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5781 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5782 Lo = 5783 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5784 V2, DAG.getConstant(0, SL, MVT::i32))); 5785 Hi = 5786 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5787 V2, DAG.getConstant(1, SL, MVT::i32))); 5788 EVT IdxVT = Idx.getValueType(); 5789 unsigned NElem = VecVT.getVectorNumElements(); 5790 assert(isPowerOf2_32(NElem)); 5791 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5792 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5793 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5794 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5795 } 5796 5797 assert(VecSize <= 64); 5798 5799 unsigned EltSize = EltVT.getSizeInBits(); 5800 assert(isPowerOf2_32(EltSize)); 5801 5802 MVT IntVT = MVT::getIntegerVT(VecSize); 5803 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5804 5805 // Convert vector index to bit-index (* EltSize) 5806 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5807 5808 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5809 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5810 5811 if (ResultVT == MVT::f16) { 5812 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5813 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5814 } 5815 5816 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5817 } 5818 5819 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5820 assert(Elt % 2 == 0); 5821 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5822 } 5823 5824 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5825 SelectionDAG &DAG) const { 5826 SDLoc SL(Op); 5827 EVT ResultVT = Op.getValueType(); 5828 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5829 5830 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5831 EVT EltVT = PackVT.getVectorElementType(); 5832 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5833 5834 // vector_shuffle <0,1,6,7> lhs, rhs 5835 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5836 // 5837 // vector_shuffle <6,7,2,3> lhs, rhs 5838 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5839 // 5840 // vector_shuffle <6,7,0,1> lhs, rhs 5841 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5842 5843 // Avoid scalarizing when both halves are reading from consecutive elements. 5844 SmallVector<SDValue, 4> Pieces; 5845 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5846 if (elementPairIsContiguous(SVN->getMask(), I)) { 5847 const int Idx = SVN->getMaskElt(I); 5848 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5849 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5850 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5851 PackVT, SVN->getOperand(VecIdx), 5852 DAG.getConstant(EltIdx, SL, MVT::i32)); 5853 Pieces.push_back(SubVec); 5854 } else { 5855 const int Idx0 = SVN->getMaskElt(I); 5856 const int Idx1 = SVN->getMaskElt(I + 1); 5857 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5858 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5859 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5860 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5861 5862 SDValue Vec0 = SVN->getOperand(VecIdx0); 5863 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5864 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5865 5866 SDValue Vec1 = SVN->getOperand(VecIdx1); 5867 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5868 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5869 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5870 } 5871 } 5872 5873 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5874 } 5875 5876 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5877 SelectionDAG &DAG) const { 5878 SDLoc SL(Op); 5879 EVT VT = Op.getValueType(); 5880 5881 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5882 VT == MVT::v8i16 || VT == MVT::v8f16) { 5883 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5884 VT.getVectorNumElements() / 2); 5885 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5886 5887 // Turn into pair of packed build_vectors. 5888 // TODO: Special case for constants that can be materialized with s_mov_b64. 5889 SmallVector<SDValue, 4> LoOps, HiOps; 5890 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5891 LoOps.push_back(Op.getOperand(I)); 5892 HiOps.push_back(Op.getOperand(I + E)); 5893 } 5894 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5895 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5896 5897 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5898 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5899 5900 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5901 { CastLo, CastHi }); 5902 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5903 } 5904 5905 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5906 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5907 5908 SDValue Lo = Op.getOperand(0); 5909 SDValue Hi = Op.getOperand(1); 5910 5911 // Avoid adding defined bits with the zero_extend. 5912 if (Hi.isUndef()) { 5913 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5914 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5915 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5916 } 5917 5918 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5919 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5920 5921 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5922 DAG.getConstant(16, SL, MVT::i32)); 5923 if (Lo.isUndef()) 5924 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5925 5926 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5927 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5928 5929 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5930 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5931 } 5932 5933 bool 5934 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5935 // We can fold offsets for anything that doesn't require a GOT relocation. 5936 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5937 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5938 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5939 !shouldEmitGOTReloc(GA->getGlobal()); 5940 } 5941 5942 static SDValue 5943 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5944 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5945 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5946 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5947 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5948 // lowered to the following code sequence: 5949 // 5950 // For constant address space: 5951 // s_getpc_b64 s[0:1] 5952 // s_add_u32 s0, s0, $symbol 5953 // s_addc_u32 s1, s1, 0 5954 // 5955 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5956 // a fixup or relocation is emitted to replace $symbol with a literal 5957 // constant, which is a pc-relative offset from the encoding of the $symbol 5958 // operand to the global variable. 5959 // 5960 // For global address space: 5961 // s_getpc_b64 s[0:1] 5962 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5963 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5964 // 5965 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5966 // fixups or relocations are emitted to replace $symbol@*@lo and 5967 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5968 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5969 // operand to the global variable. 5970 // 5971 // What we want here is an offset from the value returned by s_getpc 5972 // (which is the address of the s_add_u32 instruction) to the global 5973 // variable, but since the encoding of $symbol starts 4 bytes after the start 5974 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5975 // small. This requires us to add 4 to the global variable offset in order to 5976 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5977 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5978 // instruction. 5979 SDValue PtrLo = 5980 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5981 SDValue PtrHi; 5982 if (GAFlags == SIInstrInfo::MO_NONE) { 5983 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5984 } else { 5985 PtrHi = 5986 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5987 } 5988 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5989 } 5990 5991 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5992 SDValue Op, 5993 SelectionDAG &DAG) const { 5994 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5995 SDLoc DL(GSD); 5996 EVT PtrVT = Op.getValueType(); 5997 5998 const GlobalValue *GV = GSD->getGlobal(); 5999 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6000 shouldUseLDSConstAddress(GV)) || 6001 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6002 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6003 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6004 GV->hasExternalLinkage()) { 6005 Type *Ty = GV->getValueType(); 6006 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6007 // zero-sized type in other languages to declare the dynamic shared 6008 // memory which size is not known at the compile time. They will be 6009 // allocated by the runtime and placed directly after the static 6010 // allocated ones. They all share the same offset. 6011 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6012 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6013 // Adjust alignment for that dynamic shared memory array. 6014 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6015 return SDValue( 6016 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6017 } 6018 } 6019 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6020 } 6021 6022 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6023 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6024 SIInstrInfo::MO_ABS32_LO); 6025 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6026 } 6027 6028 if (shouldEmitFixup(GV)) 6029 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6030 else if (shouldEmitPCReloc(GV)) 6031 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6032 SIInstrInfo::MO_REL32); 6033 6034 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6035 SIInstrInfo::MO_GOTPCREL32); 6036 6037 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6038 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6039 const DataLayout &DataLayout = DAG.getDataLayout(); 6040 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6041 MachinePointerInfo PtrInfo 6042 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6043 6044 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6045 MachineMemOperand::MODereferenceable | 6046 MachineMemOperand::MOInvariant); 6047 } 6048 6049 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6050 const SDLoc &DL, SDValue V) const { 6051 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6052 // the destination register. 6053 // 6054 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6055 // so we will end up with redundant moves to m0. 6056 // 6057 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6058 6059 // A Null SDValue creates a glue result. 6060 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6061 V, Chain); 6062 return SDValue(M0, 0); 6063 } 6064 6065 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6066 SDValue Op, 6067 MVT VT, 6068 unsigned Offset) const { 6069 SDLoc SL(Op); 6070 SDValue Param = lowerKernargMemParameter( 6071 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6072 // The local size values will have the hi 16-bits as zero. 6073 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6074 DAG.getValueType(VT)); 6075 } 6076 6077 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6078 EVT VT) { 6079 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6080 "non-hsa intrinsic with hsa target", 6081 DL.getDebugLoc()); 6082 DAG.getContext()->diagnose(BadIntrin); 6083 return DAG.getUNDEF(VT); 6084 } 6085 6086 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6087 EVT VT) { 6088 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6089 "intrinsic not supported on subtarget", 6090 DL.getDebugLoc()); 6091 DAG.getContext()->diagnose(BadIntrin); 6092 return DAG.getUNDEF(VT); 6093 } 6094 6095 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6096 ArrayRef<SDValue> Elts) { 6097 assert(!Elts.empty()); 6098 MVT Type; 6099 unsigned NumElts = Elts.size(); 6100 6101 if (NumElts <= 8) { 6102 Type = MVT::getVectorVT(MVT::f32, NumElts); 6103 } else { 6104 assert(Elts.size() <= 16); 6105 Type = MVT::v16f32; 6106 NumElts = 16; 6107 } 6108 6109 SmallVector<SDValue, 16> VecElts(NumElts); 6110 for (unsigned i = 0; i < Elts.size(); ++i) { 6111 SDValue Elt = Elts[i]; 6112 if (Elt.getValueType() != MVT::f32) 6113 Elt = DAG.getBitcast(MVT::f32, Elt); 6114 VecElts[i] = Elt; 6115 } 6116 for (unsigned i = Elts.size(); i < NumElts; ++i) 6117 VecElts[i] = DAG.getUNDEF(MVT::f32); 6118 6119 if (NumElts == 1) 6120 return VecElts[0]; 6121 return DAG.getBuildVector(Type, DL, VecElts); 6122 } 6123 6124 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6125 SDValue Src, int ExtraElts) { 6126 EVT SrcVT = Src.getValueType(); 6127 6128 SmallVector<SDValue, 8> Elts; 6129 6130 if (SrcVT.isVector()) 6131 DAG.ExtractVectorElements(Src, Elts); 6132 else 6133 Elts.push_back(Src); 6134 6135 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6136 while (ExtraElts--) 6137 Elts.push_back(Undef); 6138 6139 return DAG.getBuildVector(CastVT, DL, Elts); 6140 } 6141 6142 // Re-construct the required return value for a image load intrinsic. 6143 // This is more complicated due to the optional use TexFailCtrl which means the required 6144 // return type is an aggregate 6145 static SDValue constructRetValue(SelectionDAG &DAG, 6146 MachineSDNode *Result, 6147 ArrayRef<EVT> ResultTypes, 6148 bool IsTexFail, bool Unpacked, bool IsD16, 6149 int DMaskPop, int NumVDataDwords, 6150 const SDLoc &DL) { 6151 // Determine the required return type. This is the same regardless of IsTexFail flag 6152 EVT ReqRetVT = ResultTypes[0]; 6153 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6154 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6155 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6156 6157 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6158 DMaskPop : (DMaskPop + 1) / 2; 6159 6160 MVT DataDwordVT = NumDataDwords == 1 ? 6161 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6162 6163 MVT MaskPopVT = MaskPopDwords == 1 ? 6164 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6165 6166 SDValue Data(Result, 0); 6167 SDValue TexFail; 6168 6169 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6170 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6171 if (MaskPopVT.isVector()) { 6172 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6173 SDValue(Result, 0), ZeroIdx); 6174 } else { 6175 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6176 SDValue(Result, 0), ZeroIdx); 6177 } 6178 } 6179 6180 if (DataDwordVT.isVector()) 6181 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6182 NumDataDwords - MaskPopDwords); 6183 6184 if (IsD16) 6185 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6186 6187 EVT LegalReqRetVT = ReqRetVT; 6188 if (!ReqRetVT.isVector()) { 6189 if (!Data.getValueType().isInteger()) 6190 Data = DAG.getNode(ISD::BITCAST, DL, 6191 Data.getValueType().changeTypeToInteger(), Data); 6192 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6193 } else { 6194 // We need to widen the return vector to a legal type 6195 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6196 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6197 LegalReqRetVT = 6198 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6199 ReqRetVT.getVectorNumElements() + 1); 6200 } 6201 } 6202 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6203 6204 if (IsTexFail) { 6205 TexFail = 6206 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6207 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6208 6209 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6210 } 6211 6212 if (Result->getNumValues() == 1) 6213 return Data; 6214 6215 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6216 } 6217 6218 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6219 SDValue *LWE, bool &IsTexFail) { 6220 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6221 6222 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6223 if (Value) { 6224 IsTexFail = true; 6225 } 6226 6227 SDLoc DL(TexFailCtrlConst); 6228 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6229 Value &= ~(uint64_t)0x1; 6230 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6231 Value &= ~(uint64_t)0x2; 6232 6233 return Value == 0; 6234 } 6235 6236 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6237 MVT PackVectorVT, 6238 SmallVectorImpl<SDValue> &PackedAddrs, 6239 unsigned DimIdx, unsigned EndIdx, 6240 unsigned NumGradients) { 6241 SDLoc DL(Op); 6242 for (unsigned I = DimIdx; I < EndIdx; I++) { 6243 SDValue Addr = Op.getOperand(I); 6244 6245 // Gradients are packed with undef for each coordinate. 6246 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6247 // 1D: undef,dx/dh; undef,dx/dv 6248 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6249 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6250 if (((I + 1) >= EndIdx) || 6251 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6252 I == DimIdx + NumGradients - 1))) { 6253 if (Addr.getValueType() != MVT::i16) 6254 Addr = DAG.getBitcast(MVT::i16, Addr); 6255 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6256 } else { 6257 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6258 I++; 6259 } 6260 Addr = DAG.getBitcast(MVT::f32, Addr); 6261 PackedAddrs.push_back(Addr); 6262 } 6263 } 6264 6265 SDValue SITargetLowering::lowerImage(SDValue Op, 6266 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6267 SelectionDAG &DAG, bool WithChain) const { 6268 SDLoc DL(Op); 6269 MachineFunction &MF = DAG.getMachineFunction(); 6270 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6271 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6272 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6273 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6274 unsigned IntrOpcode = Intr->BaseOpcode; 6275 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6276 6277 SmallVector<EVT, 3> ResultTypes(Op->values()); 6278 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6279 bool IsD16 = false; 6280 bool IsG16 = false; 6281 bool IsA16 = false; 6282 SDValue VData; 6283 int NumVDataDwords; 6284 bool AdjustRetType = false; 6285 6286 // Offset of intrinsic arguments 6287 const unsigned ArgOffset = WithChain ? 2 : 1; 6288 6289 unsigned DMask; 6290 unsigned DMaskLanes = 0; 6291 6292 if (BaseOpcode->Atomic) { 6293 VData = Op.getOperand(2); 6294 6295 bool Is64Bit = VData.getValueType() == MVT::i64; 6296 if (BaseOpcode->AtomicX2) { 6297 SDValue VData2 = Op.getOperand(3); 6298 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6299 {VData, VData2}); 6300 if (Is64Bit) 6301 VData = DAG.getBitcast(MVT::v4i32, VData); 6302 6303 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6304 DMask = Is64Bit ? 0xf : 0x3; 6305 NumVDataDwords = Is64Bit ? 4 : 2; 6306 } else { 6307 DMask = Is64Bit ? 0x3 : 0x1; 6308 NumVDataDwords = Is64Bit ? 2 : 1; 6309 } 6310 } else { 6311 auto *DMaskConst = 6312 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6313 DMask = DMaskConst->getZExtValue(); 6314 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6315 6316 if (BaseOpcode->Store) { 6317 VData = Op.getOperand(2); 6318 6319 MVT StoreVT = VData.getSimpleValueType(); 6320 if (StoreVT.getScalarType() == MVT::f16) { 6321 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6322 return Op; // D16 is unsupported for this instruction 6323 6324 IsD16 = true; 6325 VData = handleD16VData(VData, DAG, true); 6326 } 6327 6328 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6329 } else { 6330 // Work out the num dwords based on the dmask popcount and underlying type 6331 // and whether packing is supported. 6332 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6333 if (LoadVT.getScalarType() == MVT::f16) { 6334 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6335 return Op; // D16 is unsupported for this instruction 6336 6337 IsD16 = true; 6338 } 6339 6340 // Confirm that the return type is large enough for the dmask specified 6341 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6342 (!LoadVT.isVector() && DMaskLanes > 1)) 6343 return Op; 6344 6345 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6346 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6347 // instructions. 6348 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6349 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6350 NumVDataDwords = (DMaskLanes + 1) / 2; 6351 else 6352 NumVDataDwords = DMaskLanes; 6353 6354 AdjustRetType = true; 6355 } 6356 } 6357 6358 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6359 SmallVector<SDValue, 4> VAddrs; 6360 6361 // Check for 16 bit addresses or derivatives and pack if true. 6362 MVT VAddrVT = 6363 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6364 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6365 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6366 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6367 6368 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6369 VAddrScalarVT = VAddrVT.getScalarType(); 6370 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6371 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6372 6373 // Push back extra arguments. 6374 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6375 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6376 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6377 // Special handling of bias when A16 is on. Bias is of type half but 6378 // occupies full 32-bit. 6379 SDValue Bias = DAG.getBuildVector( 6380 MVT::v2f16, DL, 6381 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6382 VAddrs.push_back(Bias); 6383 } else { 6384 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6385 "Bias needs to be converted to 16 bit in A16 mode"); 6386 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6387 } 6388 } 6389 6390 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6391 // 16 bit gradients are supported, but are tied to the A16 control 6392 // so both gradients and addresses must be 16 bit 6393 LLVM_DEBUG( 6394 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6395 "require 16 bit args for both gradients and addresses"); 6396 return Op; 6397 } 6398 6399 if (IsA16) { 6400 if (!ST->hasA16()) { 6401 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6402 "support 16 bit addresses\n"); 6403 return Op; 6404 } 6405 } 6406 6407 // We've dealt with incorrect input so we know that if IsA16, IsG16 6408 // are set then we have to compress/pack operands (either address, 6409 // gradient or both) 6410 // In the case where a16 and gradients are tied (no G16 support) then we 6411 // have already verified that both IsA16 and IsG16 are true 6412 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6413 // Activate g16 6414 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6415 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6416 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6417 } 6418 6419 // Add gradients (packed or unpacked) 6420 if (IsG16) { 6421 // Pack the gradients 6422 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6423 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6424 ArgOffset + Intr->GradientStart, 6425 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6426 } else { 6427 for (unsigned I = ArgOffset + Intr->GradientStart; 6428 I < ArgOffset + Intr->CoordStart; I++) 6429 VAddrs.push_back(Op.getOperand(I)); 6430 } 6431 6432 // Add addresses (packed or unpacked) 6433 if (IsA16) { 6434 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6435 ArgOffset + Intr->CoordStart, VAddrEnd, 6436 0 /* No gradients */); 6437 } else { 6438 // Add uncompressed address 6439 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6440 VAddrs.push_back(Op.getOperand(I)); 6441 } 6442 6443 // If the register allocator cannot place the address registers contiguously 6444 // without introducing moves, then using the non-sequential address encoding 6445 // is always preferable, since it saves VALU instructions and is usually a 6446 // wash in terms of code size or even better. 6447 // 6448 // However, we currently have no way of hinting to the register allocator that 6449 // MIMG addresses should be placed contiguously when it is possible to do so, 6450 // so force non-NSA for the common 2-address case as a heuristic. 6451 // 6452 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6453 // allocation when possible. 6454 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6455 VAddrs.size() >= 3 && 6456 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6457 SDValue VAddr; 6458 if (!UseNSA) 6459 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6460 6461 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6462 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6463 SDValue Unorm; 6464 if (!BaseOpcode->Sampler) { 6465 Unorm = True; 6466 } else { 6467 auto UnormConst = 6468 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6469 6470 Unorm = UnormConst->getZExtValue() ? True : False; 6471 } 6472 6473 SDValue TFE; 6474 SDValue LWE; 6475 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6476 bool IsTexFail = false; 6477 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6478 return Op; 6479 6480 if (IsTexFail) { 6481 if (!DMaskLanes) { 6482 // Expecting to get an error flag since TFC is on - and dmask is 0 6483 // Force dmask to be at least 1 otherwise the instruction will fail 6484 DMask = 0x1; 6485 DMaskLanes = 1; 6486 NumVDataDwords = 1; 6487 } 6488 NumVDataDwords += 1; 6489 AdjustRetType = true; 6490 } 6491 6492 // Has something earlier tagged that the return type needs adjusting 6493 // This happens if the instruction is a load or has set TexFailCtrl flags 6494 if (AdjustRetType) { 6495 // NumVDataDwords reflects the true number of dwords required in the return type 6496 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6497 // This is a no-op load. This can be eliminated 6498 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6499 if (isa<MemSDNode>(Op)) 6500 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6501 return Undef; 6502 } 6503 6504 EVT NewVT = NumVDataDwords > 1 ? 6505 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6506 : MVT::i32; 6507 6508 ResultTypes[0] = NewVT; 6509 if (ResultTypes.size() == 3) { 6510 // Original result was aggregate type used for TexFailCtrl results 6511 // The actual instruction returns as a vector type which has now been 6512 // created. Remove the aggregate result. 6513 ResultTypes.erase(&ResultTypes[1]); 6514 } 6515 } 6516 6517 unsigned CPol = cast<ConstantSDNode>( 6518 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6519 if (BaseOpcode->Atomic) 6520 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6521 if (CPol & ~AMDGPU::CPol::ALL) 6522 return Op; 6523 6524 SmallVector<SDValue, 26> Ops; 6525 if (BaseOpcode->Store || BaseOpcode->Atomic) 6526 Ops.push_back(VData); // vdata 6527 if (UseNSA) 6528 append_range(Ops, VAddrs); 6529 else 6530 Ops.push_back(VAddr); 6531 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6532 if (BaseOpcode->Sampler) 6533 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6534 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6535 if (IsGFX10Plus) 6536 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6537 Ops.push_back(Unorm); 6538 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6539 Ops.push_back(IsA16 && // r128, a16 for gfx9 6540 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6541 if (IsGFX10Plus) 6542 Ops.push_back(IsA16 ? True : False); 6543 if (!Subtarget->hasGFX90AInsts()) { 6544 Ops.push_back(TFE); //tfe 6545 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6546 report_fatal_error("TFE is not supported on this GPU"); 6547 } 6548 Ops.push_back(LWE); // lwe 6549 if (!IsGFX10Plus) 6550 Ops.push_back(DimInfo->DA ? True : False); 6551 if (BaseOpcode->HasD16) 6552 Ops.push_back(IsD16 ? True : False); 6553 if (isa<MemSDNode>(Op)) 6554 Ops.push_back(Op.getOperand(0)); // chain 6555 6556 int NumVAddrDwords = 6557 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6558 int Opcode = -1; 6559 6560 if (IsGFX10Plus) { 6561 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6562 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6563 : AMDGPU::MIMGEncGfx10Default, 6564 NumVDataDwords, NumVAddrDwords); 6565 } else { 6566 if (Subtarget->hasGFX90AInsts()) { 6567 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6568 NumVDataDwords, NumVAddrDwords); 6569 if (Opcode == -1) 6570 report_fatal_error( 6571 "requested image instruction is not supported on this GPU"); 6572 } 6573 if (Opcode == -1 && 6574 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6575 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6576 NumVDataDwords, NumVAddrDwords); 6577 if (Opcode == -1) 6578 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6579 NumVDataDwords, NumVAddrDwords); 6580 } 6581 assert(Opcode != -1); 6582 6583 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6584 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6585 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6586 DAG.setNodeMemRefs(NewNode, {MemRef}); 6587 } 6588 6589 if (BaseOpcode->AtomicX2) { 6590 SmallVector<SDValue, 1> Elt; 6591 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6592 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6593 } 6594 if (BaseOpcode->Store) 6595 return SDValue(NewNode, 0); 6596 return constructRetValue(DAG, NewNode, 6597 OrigResultTypes, IsTexFail, 6598 Subtarget->hasUnpackedD16VMem(), IsD16, 6599 DMaskLanes, NumVDataDwords, DL); 6600 } 6601 6602 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6603 SDValue Offset, SDValue CachePolicy, 6604 SelectionDAG &DAG) const { 6605 MachineFunction &MF = DAG.getMachineFunction(); 6606 6607 const DataLayout &DataLayout = DAG.getDataLayout(); 6608 Align Alignment = 6609 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6610 6611 MachineMemOperand *MMO = MF.getMachineMemOperand( 6612 MachinePointerInfo(), 6613 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6614 MachineMemOperand::MOInvariant, 6615 VT.getStoreSize(), Alignment); 6616 6617 if (!Offset->isDivergent()) { 6618 SDValue Ops[] = { 6619 Rsrc, 6620 Offset, // Offset 6621 CachePolicy 6622 }; 6623 6624 // Widen vec3 load to vec4. 6625 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6626 EVT WidenedVT = 6627 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6628 auto WidenedOp = DAG.getMemIntrinsicNode( 6629 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6630 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6631 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6632 DAG.getVectorIdxConstant(0, DL)); 6633 return Subvector; 6634 } 6635 6636 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6637 DAG.getVTList(VT), Ops, VT, MMO); 6638 } 6639 6640 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6641 // assume that the buffer is unswizzled. 6642 SmallVector<SDValue, 4> Loads; 6643 unsigned NumLoads = 1; 6644 MVT LoadVT = VT.getSimpleVT(); 6645 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6646 assert((LoadVT.getScalarType() == MVT::i32 || 6647 LoadVT.getScalarType() == MVT::f32)); 6648 6649 if (NumElts == 8 || NumElts == 16) { 6650 NumLoads = NumElts / 4; 6651 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6652 } 6653 6654 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6655 SDValue Ops[] = { 6656 DAG.getEntryNode(), // Chain 6657 Rsrc, // rsrc 6658 DAG.getConstant(0, DL, MVT::i32), // vindex 6659 {}, // voffset 6660 {}, // soffset 6661 {}, // offset 6662 CachePolicy, // cachepolicy 6663 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6664 }; 6665 6666 // Use the alignment to ensure that the required offsets will fit into the 6667 // immediate offsets. 6668 setBufferOffsets(Offset, DAG, &Ops[3], 6669 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6670 6671 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6672 for (unsigned i = 0; i < NumLoads; ++i) { 6673 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6674 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6675 LoadVT, MMO, DAG)); 6676 } 6677 6678 if (NumElts == 8 || NumElts == 16) 6679 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6680 6681 return Loads[0]; 6682 } 6683 6684 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6685 SelectionDAG &DAG) const { 6686 MachineFunction &MF = DAG.getMachineFunction(); 6687 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6688 6689 EVT VT = Op.getValueType(); 6690 SDLoc DL(Op); 6691 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6692 6693 // TODO: Should this propagate fast-math-flags? 6694 6695 switch (IntrinsicID) { 6696 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6697 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6698 return emitNonHSAIntrinsicError(DAG, DL, VT); 6699 return getPreloadedValue(DAG, *MFI, VT, 6700 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6701 } 6702 case Intrinsic::amdgcn_dispatch_ptr: 6703 case Intrinsic::amdgcn_queue_ptr: { 6704 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6705 DiagnosticInfoUnsupported BadIntrin( 6706 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6707 DL.getDebugLoc()); 6708 DAG.getContext()->diagnose(BadIntrin); 6709 return DAG.getUNDEF(VT); 6710 } 6711 6712 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6713 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6714 return getPreloadedValue(DAG, *MFI, VT, RegID); 6715 } 6716 case Intrinsic::amdgcn_implicitarg_ptr: { 6717 if (MFI->isEntryFunction()) 6718 return getImplicitArgPtr(DAG, DL); 6719 return getPreloadedValue(DAG, *MFI, VT, 6720 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6721 } 6722 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6723 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6724 // This only makes sense to call in a kernel, so just lower to null. 6725 return DAG.getConstant(0, DL, VT); 6726 } 6727 6728 return getPreloadedValue(DAG, *MFI, VT, 6729 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6730 } 6731 case Intrinsic::amdgcn_dispatch_id: { 6732 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6733 } 6734 case Intrinsic::amdgcn_rcp: 6735 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6736 case Intrinsic::amdgcn_rsq: 6737 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6738 case Intrinsic::amdgcn_rsq_legacy: 6739 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6740 return emitRemovedIntrinsicError(DAG, DL, VT); 6741 return SDValue(); 6742 case Intrinsic::amdgcn_rcp_legacy: 6743 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6744 return emitRemovedIntrinsicError(DAG, DL, VT); 6745 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6746 case Intrinsic::amdgcn_rsq_clamp: { 6747 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6748 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6749 6750 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6751 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6752 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6753 6754 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6755 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6756 DAG.getConstantFP(Max, DL, VT)); 6757 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6758 DAG.getConstantFP(Min, DL, VT)); 6759 } 6760 case Intrinsic::r600_read_ngroups_x: 6761 if (Subtarget->isAmdHsaOS()) 6762 return emitNonHSAIntrinsicError(DAG, DL, VT); 6763 6764 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6765 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6766 false); 6767 case Intrinsic::r600_read_ngroups_y: 6768 if (Subtarget->isAmdHsaOS()) 6769 return emitNonHSAIntrinsicError(DAG, DL, VT); 6770 6771 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6772 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6773 false); 6774 case Intrinsic::r600_read_ngroups_z: 6775 if (Subtarget->isAmdHsaOS()) 6776 return emitNonHSAIntrinsicError(DAG, DL, VT); 6777 6778 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6779 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6780 false); 6781 case Intrinsic::r600_read_global_size_x: 6782 if (Subtarget->isAmdHsaOS()) 6783 return emitNonHSAIntrinsicError(DAG, DL, VT); 6784 6785 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6786 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6787 Align(4), false); 6788 case Intrinsic::r600_read_global_size_y: 6789 if (Subtarget->isAmdHsaOS()) 6790 return emitNonHSAIntrinsicError(DAG, DL, VT); 6791 6792 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6793 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6794 Align(4), false); 6795 case Intrinsic::r600_read_global_size_z: 6796 if (Subtarget->isAmdHsaOS()) 6797 return emitNonHSAIntrinsicError(DAG, DL, VT); 6798 6799 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6800 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6801 Align(4), false); 6802 case Intrinsic::r600_read_local_size_x: 6803 if (Subtarget->isAmdHsaOS()) 6804 return emitNonHSAIntrinsicError(DAG, DL, VT); 6805 6806 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6807 SI::KernelInputOffsets::LOCAL_SIZE_X); 6808 case Intrinsic::r600_read_local_size_y: 6809 if (Subtarget->isAmdHsaOS()) 6810 return emitNonHSAIntrinsicError(DAG, DL, VT); 6811 6812 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6813 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6814 case Intrinsic::r600_read_local_size_z: 6815 if (Subtarget->isAmdHsaOS()) 6816 return emitNonHSAIntrinsicError(DAG, DL, VT); 6817 6818 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6819 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6820 case Intrinsic::amdgcn_workgroup_id_x: 6821 return getPreloadedValue(DAG, *MFI, VT, 6822 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6823 case Intrinsic::amdgcn_workgroup_id_y: 6824 return getPreloadedValue(DAG, *MFI, VT, 6825 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6826 case Intrinsic::amdgcn_workgroup_id_z: 6827 return getPreloadedValue(DAG, *MFI, VT, 6828 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6829 case Intrinsic::amdgcn_workitem_id_x: 6830 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0) 6831 return DAG.getConstant(0, DL, MVT::i32); 6832 6833 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6834 SDLoc(DAG.getEntryNode()), 6835 MFI->getArgInfo().WorkItemIDX); 6836 case Intrinsic::amdgcn_workitem_id_y: 6837 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0) 6838 return DAG.getConstant(0, DL, MVT::i32); 6839 6840 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6841 SDLoc(DAG.getEntryNode()), 6842 MFI->getArgInfo().WorkItemIDY); 6843 case Intrinsic::amdgcn_workitem_id_z: 6844 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0) 6845 return DAG.getConstant(0, DL, MVT::i32); 6846 6847 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6848 SDLoc(DAG.getEntryNode()), 6849 MFI->getArgInfo().WorkItemIDZ); 6850 case Intrinsic::amdgcn_wavefrontsize: 6851 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6852 SDLoc(Op), MVT::i32); 6853 case Intrinsic::amdgcn_s_buffer_load: { 6854 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6855 if (CPol & ~AMDGPU::CPol::ALL) 6856 return Op; 6857 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6858 DAG); 6859 } 6860 case Intrinsic::amdgcn_fdiv_fast: 6861 return lowerFDIV_FAST(Op, DAG); 6862 case Intrinsic::amdgcn_sin: 6863 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6864 6865 case Intrinsic::amdgcn_cos: 6866 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6867 6868 case Intrinsic::amdgcn_mul_u24: 6869 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6870 case Intrinsic::amdgcn_mul_i24: 6871 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6872 6873 case Intrinsic::amdgcn_log_clamp: { 6874 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6875 return SDValue(); 6876 6877 return emitRemovedIntrinsicError(DAG, DL, VT); 6878 } 6879 case Intrinsic::amdgcn_ldexp: 6880 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6881 Op.getOperand(1), Op.getOperand(2)); 6882 6883 case Intrinsic::amdgcn_fract: 6884 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6885 6886 case Intrinsic::amdgcn_class: 6887 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6888 Op.getOperand(1), Op.getOperand(2)); 6889 case Intrinsic::amdgcn_div_fmas: 6890 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6891 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6892 Op.getOperand(4)); 6893 6894 case Intrinsic::amdgcn_div_fixup: 6895 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6896 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6897 6898 case Intrinsic::amdgcn_div_scale: { 6899 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6900 6901 // Translate to the operands expected by the machine instruction. The 6902 // first parameter must be the same as the first instruction. 6903 SDValue Numerator = Op.getOperand(1); 6904 SDValue Denominator = Op.getOperand(2); 6905 6906 // Note this order is opposite of the machine instruction's operations, 6907 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6908 // intrinsic has the numerator as the first operand to match a normal 6909 // division operation. 6910 6911 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6912 6913 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6914 Denominator, Numerator); 6915 } 6916 case Intrinsic::amdgcn_icmp: { 6917 // There is a Pat that handles this variant, so return it as-is. 6918 if (Op.getOperand(1).getValueType() == MVT::i1 && 6919 Op.getConstantOperandVal(2) == 0 && 6920 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6921 return Op; 6922 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6923 } 6924 case Intrinsic::amdgcn_fcmp: { 6925 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6926 } 6927 case Intrinsic::amdgcn_ballot: 6928 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6929 case Intrinsic::amdgcn_fmed3: 6930 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6931 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6932 case Intrinsic::amdgcn_fdot2: 6933 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6934 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6935 Op.getOperand(4)); 6936 case Intrinsic::amdgcn_fmul_legacy: 6937 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6938 Op.getOperand(1), Op.getOperand(2)); 6939 case Intrinsic::amdgcn_sffbh: 6940 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6941 case Intrinsic::amdgcn_sbfe: 6942 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6943 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6944 case Intrinsic::amdgcn_ubfe: 6945 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6946 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6947 case Intrinsic::amdgcn_cvt_pkrtz: 6948 case Intrinsic::amdgcn_cvt_pknorm_i16: 6949 case Intrinsic::amdgcn_cvt_pknorm_u16: 6950 case Intrinsic::amdgcn_cvt_pk_i16: 6951 case Intrinsic::amdgcn_cvt_pk_u16: { 6952 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6953 EVT VT = Op.getValueType(); 6954 unsigned Opcode; 6955 6956 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6957 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6958 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6959 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6960 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6961 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6962 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6963 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6964 else 6965 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6966 6967 if (isTypeLegal(VT)) 6968 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6969 6970 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6971 Op.getOperand(1), Op.getOperand(2)); 6972 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6973 } 6974 case Intrinsic::amdgcn_fmad_ftz: 6975 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6976 Op.getOperand(2), Op.getOperand(3)); 6977 6978 case Intrinsic::amdgcn_if_break: 6979 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6980 Op->getOperand(1), Op->getOperand(2)), 0); 6981 6982 case Intrinsic::amdgcn_groupstaticsize: { 6983 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6984 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6985 return Op; 6986 6987 const Module *M = MF.getFunction().getParent(); 6988 const GlobalValue *GV = 6989 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6990 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6991 SIInstrInfo::MO_ABS32_LO); 6992 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6993 } 6994 case Intrinsic::amdgcn_is_shared: 6995 case Intrinsic::amdgcn_is_private: { 6996 SDLoc SL(Op); 6997 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6998 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6999 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7000 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7001 Op.getOperand(1)); 7002 7003 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7004 DAG.getConstant(1, SL, MVT::i32)); 7005 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7006 } 7007 case Intrinsic::amdgcn_perm: 7008 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7009 Op.getOperand(2), Op.getOperand(3)); 7010 case Intrinsic::amdgcn_reloc_constant: { 7011 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7012 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7013 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7014 auto RelocSymbol = cast<GlobalVariable>( 7015 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7016 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7017 SIInstrInfo::MO_ABS32_LO); 7018 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7019 } 7020 default: 7021 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7022 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7023 return lowerImage(Op, ImageDimIntr, DAG, false); 7024 7025 return Op; 7026 } 7027 } 7028 7029 /// Update \p MMO based on the offset inputs to an intrinsic. 7030 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7031 SDValue SOffset, SDValue Offset, 7032 SDValue VIndex = SDValue()) { 7033 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7034 !isa<ConstantSDNode>(Offset)) { 7035 // The combined offset is not known to be constant, so we cannot represent 7036 // it in the MMO. Give up. 7037 MMO->setValue((Value *)nullptr); 7038 return; 7039 } 7040 7041 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7042 !cast<ConstantSDNode>(VIndex)->isZero())) { 7043 // The strided index component of the address is not known to be zero, so we 7044 // cannot represent it in the MMO. Give up. 7045 MMO->setValue((Value *)nullptr); 7046 return; 7047 } 7048 7049 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7050 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7051 cast<ConstantSDNode>(Offset)->getSExtValue()); 7052 } 7053 7054 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7055 SelectionDAG &DAG, 7056 unsigned NewOpcode) const { 7057 SDLoc DL(Op); 7058 7059 SDValue VData = Op.getOperand(2); 7060 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7061 SDValue Ops[] = { 7062 Op.getOperand(0), // Chain 7063 VData, // vdata 7064 Op.getOperand(3), // rsrc 7065 DAG.getConstant(0, DL, MVT::i32), // vindex 7066 Offsets.first, // voffset 7067 Op.getOperand(5), // soffset 7068 Offsets.second, // offset 7069 Op.getOperand(6), // cachepolicy 7070 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7071 }; 7072 7073 auto *M = cast<MemSDNode>(Op); 7074 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7075 7076 EVT MemVT = VData.getValueType(); 7077 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7078 M->getMemOperand()); 7079 } 7080 7081 // Return a value to use for the idxen operand by examining the vindex operand. 7082 static unsigned getIdxEn(SDValue VIndex) { 7083 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7084 // No need to set idxen if vindex is known to be zero. 7085 return VIndexC->getZExtValue() != 0; 7086 return 1; 7087 } 7088 7089 SDValue 7090 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7091 unsigned NewOpcode) const { 7092 SDLoc DL(Op); 7093 7094 SDValue VData = Op.getOperand(2); 7095 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7096 SDValue Ops[] = { 7097 Op.getOperand(0), // Chain 7098 VData, // vdata 7099 Op.getOperand(3), // rsrc 7100 Op.getOperand(4), // vindex 7101 Offsets.first, // voffset 7102 Op.getOperand(6), // soffset 7103 Offsets.second, // offset 7104 Op.getOperand(7), // cachepolicy 7105 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7106 }; 7107 7108 auto *M = cast<MemSDNode>(Op); 7109 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7110 7111 EVT MemVT = VData.getValueType(); 7112 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7113 M->getMemOperand()); 7114 } 7115 7116 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7117 SelectionDAG &DAG) const { 7118 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7119 SDLoc DL(Op); 7120 7121 switch (IntrID) { 7122 case Intrinsic::amdgcn_ds_ordered_add: 7123 case Intrinsic::amdgcn_ds_ordered_swap: { 7124 MemSDNode *M = cast<MemSDNode>(Op); 7125 SDValue Chain = M->getOperand(0); 7126 SDValue M0 = M->getOperand(2); 7127 SDValue Value = M->getOperand(3); 7128 unsigned IndexOperand = M->getConstantOperandVal(7); 7129 unsigned WaveRelease = M->getConstantOperandVal(8); 7130 unsigned WaveDone = M->getConstantOperandVal(9); 7131 7132 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7133 IndexOperand &= ~0x3f; 7134 unsigned CountDw = 0; 7135 7136 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7137 CountDw = (IndexOperand >> 24) & 0xf; 7138 IndexOperand &= ~(0xf << 24); 7139 7140 if (CountDw < 1 || CountDw > 4) { 7141 report_fatal_error( 7142 "ds_ordered_count: dword count must be between 1 and 4"); 7143 } 7144 } 7145 7146 if (IndexOperand) 7147 report_fatal_error("ds_ordered_count: bad index operand"); 7148 7149 if (WaveDone && !WaveRelease) 7150 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7151 7152 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7153 unsigned ShaderType = 7154 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7155 unsigned Offset0 = OrderedCountIndex << 2; 7156 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7157 (Instruction << 4); 7158 7159 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7160 Offset1 |= (CountDw - 1) << 6; 7161 7162 unsigned Offset = Offset0 | (Offset1 << 8); 7163 7164 SDValue Ops[] = { 7165 Chain, 7166 Value, 7167 DAG.getTargetConstant(Offset, DL, MVT::i16), 7168 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7169 }; 7170 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7171 M->getVTList(), Ops, M->getMemoryVT(), 7172 M->getMemOperand()); 7173 } 7174 case Intrinsic::amdgcn_ds_fadd: { 7175 MemSDNode *M = cast<MemSDNode>(Op); 7176 unsigned Opc; 7177 switch (IntrID) { 7178 case Intrinsic::amdgcn_ds_fadd: 7179 Opc = ISD::ATOMIC_LOAD_FADD; 7180 break; 7181 } 7182 7183 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7184 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7185 M->getMemOperand()); 7186 } 7187 case Intrinsic::amdgcn_atomic_inc: 7188 case Intrinsic::amdgcn_atomic_dec: 7189 case Intrinsic::amdgcn_ds_fmin: 7190 case Intrinsic::amdgcn_ds_fmax: { 7191 MemSDNode *M = cast<MemSDNode>(Op); 7192 unsigned Opc; 7193 switch (IntrID) { 7194 case Intrinsic::amdgcn_atomic_inc: 7195 Opc = AMDGPUISD::ATOMIC_INC; 7196 break; 7197 case Intrinsic::amdgcn_atomic_dec: 7198 Opc = AMDGPUISD::ATOMIC_DEC; 7199 break; 7200 case Intrinsic::amdgcn_ds_fmin: 7201 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7202 break; 7203 case Intrinsic::amdgcn_ds_fmax: 7204 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7205 break; 7206 default: 7207 llvm_unreachable("Unknown intrinsic!"); 7208 } 7209 SDValue Ops[] = { 7210 M->getOperand(0), // Chain 7211 M->getOperand(2), // Ptr 7212 M->getOperand(3) // Value 7213 }; 7214 7215 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7216 M->getMemoryVT(), M->getMemOperand()); 7217 } 7218 case Intrinsic::amdgcn_buffer_load: 7219 case Intrinsic::amdgcn_buffer_load_format: { 7220 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7221 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7222 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7223 SDValue Ops[] = { 7224 Op.getOperand(0), // Chain 7225 Op.getOperand(2), // rsrc 7226 Op.getOperand(3), // vindex 7227 SDValue(), // voffset -- will be set by setBufferOffsets 7228 SDValue(), // soffset -- will be set by setBufferOffsets 7229 SDValue(), // offset -- will be set by setBufferOffsets 7230 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7231 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7232 }; 7233 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7234 7235 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7236 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7237 7238 EVT VT = Op.getValueType(); 7239 EVT IntVT = VT.changeTypeToInteger(); 7240 auto *M = cast<MemSDNode>(Op); 7241 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7242 EVT LoadVT = Op.getValueType(); 7243 7244 if (LoadVT.getScalarType() == MVT::f16) 7245 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7246 M, DAG, Ops); 7247 7248 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7249 if (LoadVT.getScalarType() == MVT::i8 || 7250 LoadVT.getScalarType() == MVT::i16) 7251 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7252 7253 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7254 M->getMemOperand(), DAG); 7255 } 7256 case Intrinsic::amdgcn_raw_buffer_load: 7257 case Intrinsic::amdgcn_raw_buffer_load_format: { 7258 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7259 7260 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7261 SDValue Ops[] = { 7262 Op.getOperand(0), // Chain 7263 Op.getOperand(2), // rsrc 7264 DAG.getConstant(0, DL, MVT::i32), // vindex 7265 Offsets.first, // voffset 7266 Op.getOperand(4), // soffset 7267 Offsets.second, // offset 7268 Op.getOperand(5), // cachepolicy, swizzled buffer 7269 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7270 }; 7271 7272 auto *M = cast<MemSDNode>(Op); 7273 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7274 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7275 } 7276 case Intrinsic::amdgcn_struct_buffer_load: 7277 case Intrinsic::amdgcn_struct_buffer_load_format: { 7278 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7279 7280 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7281 SDValue Ops[] = { 7282 Op.getOperand(0), // Chain 7283 Op.getOperand(2), // rsrc 7284 Op.getOperand(3), // vindex 7285 Offsets.first, // voffset 7286 Op.getOperand(5), // soffset 7287 Offsets.second, // offset 7288 Op.getOperand(6), // cachepolicy, swizzled buffer 7289 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7290 }; 7291 7292 auto *M = cast<MemSDNode>(Op); 7293 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7294 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7295 } 7296 case Intrinsic::amdgcn_tbuffer_load: { 7297 MemSDNode *M = cast<MemSDNode>(Op); 7298 EVT LoadVT = Op.getValueType(); 7299 7300 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7301 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7302 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7303 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7304 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7305 SDValue Ops[] = { 7306 Op.getOperand(0), // Chain 7307 Op.getOperand(2), // rsrc 7308 Op.getOperand(3), // vindex 7309 Op.getOperand(4), // voffset 7310 Op.getOperand(5), // soffset 7311 Op.getOperand(6), // offset 7312 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7313 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7314 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7315 }; 7316 7317 if (LoadVT.getScalarType() == MVT::f16) 7318 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7319 M, DAG, Ops); 7320 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7321 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7322 DAG); 7323 } 7324 case Intrinsic::amdgcn_raw_tbuffer_load: { 7325 MemSDNode *M = cast<MemSDNode>(Op); 7326 EVT LoadVT = Op.getValueType(); 7327 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7328 7329 SDValue Ops[] = { 7330 Op.getOperand(0), // Chain 7331 Op.getOperand(2), // rsrc 7332 DAG.getConstant(0, DL, MVT::i32), // vindex 7333 Offsets.first, // voffset 7334 Op.getOperand(4), // soffset 7335 Offsets.second, // offset 7336 Op.getOperand(5), // format 7337 Op.getOperand(6), // cachepolicy, swizzled buffer 7338 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7339 }; 7340 7341 if (LoadVT.getScalarType() == MVT::f16) 7342 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7343 M, DAG, Ops); 7344 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7345 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7346 DAG); 7347 } 7348 case Intrinsic::amdgcn_struct_tbuffer_load: { 7349 MemSDNode *M = cast<MemSDNode>(Op); 7350 EVT LoadVT = Op.getValueType(); 7351 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7352 7353 SDValue Ops[] = { 7354 Op.getOperand(0), // Chain 7355 Op.getOperand(2), // rsrc 7356 Op.getOperand(3), // vindex 7357 Offsets.first, // voffset 7358 Op.getOperand(5), // soffset 7359 Offsets.second, // offset 7360 Op.getOperand(6), // format 7361 Op.getOperand(7), // cachepolicy, swizzled buffer 7362 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7363 }; 7364 7365 if (LoadVT.getScalarType() == MVT::f16) 7366 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7367 M, DAG, Ops); 7368 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7369 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7370 DAG); 7371 } 7372 case Intrinsic::amdgcn_buffer_atomic_swap: 7373 case Intrinsic::amdgcn_buffer_atomic_add: 7374 case Intrinsic::amdgcn_buffer_atomic_sub: 7375 case Intrinsic::amdgcn_buffer_atomic_csub: 7376 case Intrinsic::amdgcn_buffer_atomic_smin: 7377 case Intrinsic::amdgcn_buffer_atomic_umin: 7378 case Intrinsic::amdgcn_buffer_atomic_smax: 7379 case Intrinsic::amdgcn_buffer_atomic_umax: 7380 case Intrinsic::amdgcn_buffer_atomic_and: 7381 case Intrinsic::amdgcn_buffer_atomic_or: 7382 case Intrinsic::amdgcn_buffer_atomic_xor: 7383 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7384 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7385 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7386 SDValue Ops[] = { 7387 Op.getOperand(0), // Chain 7388 Op.getOperand(2), // vdata 7389 Op.getOperand(3), // rsrc 7390 Op.getOperand(4), // vindex 7391 SDValue(), // voffset -- will be set by setBufferOffsets 7392 SDValue(), // soffset -- will be set by setBufferOffsets 7393 SDValue(), // offset -- will be set by setBufferOffsets 7394 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7395 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7396 }; 7397 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7398 7399 EVT VT = Op.getValueType(); 7400 7401 auto *M = cast<MemSDNode>(Op); 7402 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7403 unsigned Opcode = 0; 7404 7405 switch (IntrID) { 7406 case Intrinsic::amdgcn_buffer_atomic_swap: 7407 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7408 break; 7409 case Intrinsic::amdgcn_buffer_atomic_add: 7410 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7411 break; 7412 case Intrinsic::amdgcn_buffer_atomic_sub: 7413 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7414 break; 7415 case Intrinsic::amdgcn_buffer_atomic_csub: 7416 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7417 break; 7418 case Intrinsic::amdgcn_buffer_atomic_smin: 7419 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7420 break; 7421 case Intrinsic::amdgcn_buffer_atomic_umin: 7422 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7423 break; 7424 case Intrinsic::amdgcn_buffer_atomic_smax: 7425 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7426 break; 7427 case Intrinsic::amdgcn_buffer_atomic_umax: 7428 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7429 break; 7430 case Intrinsic::amdgcn_buffer_atomic_and: 7431 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7432 break; 7433 case Intrinsic::amdgcn_buffer_atomic_or: 7434 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7435 break; 7436 case Intrinsic::amdgcn_buffer_atomic_xor: 7437 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7438 break; 7439 case Intrinsic::amdgcn_buffer_atomic_fadd: 7440 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7441 DiagnosticInfoUnsupported 7442 NoFpRet(DAG.getMachineFunction().getFunction(), 7443 "return versions of fp atomics not supported", 7444 DL.getDebugLoc(), DS_Error); 7445 DAG.getContext()->diagnose(NoFpRet); 7446 return SDValue(); 7447 } 7448 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7449 break; 7450 default: 7451 llvm_unreachable("unhandled atomic opcode"); 7452 } 7453 7454 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7455 M->getMemOperand()); 7456 } 7457 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7458 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7459 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7460 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7461 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7462 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7463 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7464 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7465 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7466 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7467 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7468 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7469 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7470 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7471 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7472 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7473 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7474 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7475 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7476 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7477 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7478 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7479 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7480 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7481 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7482 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7483 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7484 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7485 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7486 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7487 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7488 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7489 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7490 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7491 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7492 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7493 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7494 return lowerStructBufferAtomicIntrin(Op, DAG, 7495 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7496 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7497 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7498 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7499 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7500 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7501 return lowerStructBufferAtomicIntrin(Op, DAG, 7502 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7503 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7504 return lowerStructBufferAtomicIntrin(Op, DAG, 7505 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7506 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7507 return lowerStructBufferAtomicIntrin(Op, DAG, 7508 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7509 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7510 return lowerStructBufferAtomicIntrin(Op, DAG, 7511 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7512 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7513 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7514 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7515 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7516 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7517 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7518 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7519 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7520 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7521 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7522 7523 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7524 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7525 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7526 SDValue Ops[] = { 7527 Op.getOperand(0), // Chain 7528 Op.getOperand(2), // src 7529 Op.getOperand(3), // cmp 7530 Op.getOperand(4), // rsrc 7531 Op.getOperand(5), // vindex 7532 SDValue(), // voffset -- will be set by setBufferOffsets 7533 SDValue(), // soffset -- will be set by setBufferOffsets 7534 SDValue(), // offset -- will be set by setBufferOffsets 7535 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7536 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7537 }; 7538 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7539 7540 EVT VT = Op.getValueType(); 7541 auto *M = cast<MemSDNode>(Op); 7542 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7543 7544 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7545 Op->getVTList(), Ops, VT, M->getMemOperand()); 7546 } 7547 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7548 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7549 SDValue Ops[] = { 7550 Op.getOperand(0), // Chain 7551 Op.getOperand(2), // src 7552 Op.getOperand(3), // cmp 7553 Op.getOperand(4), // rsrc 7554 DAG.getConstant(0, DL, MVT::i32), // vindex 7555 Offsets.first, // voffset 7556 Op.getOperand(6), // soffset 7557 Offsets.second, // offset 7558 Op.getOperand(7), // cachepolicy 7559 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7560 }; 7561 EVT VT = Op.getValueType(); 7562 auto *M = cast<MemSDNode>(Op); 7563 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7564 7565 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7566 Op->getVTList(), Ops, VT, M->getMemOperand()); 7567 } 7568 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7569 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7570 SDValue Ops[] = { 7571 Op.getOperand(0), // Chain 7572 Op.getOperand(2), // src 7573 Op.getOperand(3), // cmp 7574 Op.getOperand(4), // rsrc 7575 Op.getOperand(5), // vindex 7576 Offsets.first, // voffset 7577 Op.getOperand(7), // soffset 7578 Offsets.second, // offset 7579 Op.getOperand(8), // cachepolicy 7580 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7581 }; 7582 EVT VT = Op.getValueType(); 7583 auto *M = cast<MemSDNode>(Op); 7584 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7585 7586 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7587 Op->getVTList(), Ops, VT, M->getMemOperand()); 7588 } 7589 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7590 MemSDNode *M = cast<MemSDNode>(Op); 7591 SDValue NodePtr = M->getOperand(2); 7592 SDValue RayExtent = M->getOperand(3); 7593 SDValue RayOrigin = M->getOperand(4); 7594 SDValue RayDir = M->getOperand(5); 7595 SDValue RayInvDir = M->getOperand(6); 7596 SDValue TDescr = M->getOperand(7); 7597 7598 assert(NodePtr.getValueType() == MVT::i32 || 7599 NodePtr.getValueType() == MVT::i64); 7600 assert(RayDir.getValueType() == MVT::v3f16 || 7601 RayDir.getValueType() == MVT::v3f32); 7602 7603 if (!Subtarget->hasGFX10_AEncoding()) { 7604 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7605 return SDValue(); 7606 } 7607 7608 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7609 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7610 const unsigned NumVDataDwords = 4; 7611 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7612 const bool UseNSA = Subtarget->hasNSAEncoding() && 7613 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7614 const unsigned BaseOpcodes[2][2] = { 7615 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7616 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7617 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7618 int Opcode; 7619 if (UseNSA) { 7620 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7621 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7622 NumVAddrDwords); 7623 } else { 7624 Opcode = AMDGPU::getMIMGOpcode( 7625 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7626 PowerOf2Ceil(NumVAddrDwords)); 7627 } 7628 assert(Opcode != -1); 7629 7630 SmallVector<SDValue, 16> Ops; 7631 7632 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7633 SmallVector<SDValue, 3> Lanes; 7634 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7635 if (Lanes[0].getValueSizeInBits() == 32) { 7636 for (unsigned I = 0; I < 3; ++I) 7637 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7638 } else { 7639 if (IsAligned) { 7640 Ops.push_back( 7641 DAG.getBitcast(MVT::i32, 7642 DAG.getBuildVector(MVT::v2f16, DL, 7643 { Lanes[0], Lanes[1] }))); 7644 Ops.push_back(Lanes[2]); 7645 } else { 7646 SDValue Elt0 = Ops.pop_back_val(); 7647 Ops.push_back( 7648 DAG.getBitcast(MVT::i32, 7649 DAG.getBuildVector(MVT::v2f16, DL, 7650 { Elt0, Lanes[0] }))); 7651 Ops.push_back( 7652 DAG.getBitcast(MVT::i32, 7653 DAG.getBuildVector(MVT::v2f16, DL, 7654 { Lanes[1], Lanes[2] }))); 7655 } 7656 } 7657 }; 7658 7659 if (Is64) 7660 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7661 else 7662 Ops.push_back(NodePtr); 7663 7664 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7665 packLanes(RayOrigin, true); 7666 packLanes(RayDir, true); 7667 packLanes(RayInvDir, false); 7668 7669 if (!UseNSA) { 7670 // Build a single vector containing all the operands so far prepared. 7671 if (NumVAddrDwords > 8) { 7672 SDValue Undef = DAG.getUNDEF(MVT::i32); 7673 Ops.append(16 - Ops.size(), Undef); 7674 } 7675 assert(Ops.size() == 8 || Ops.size() == 16); 7676 SDValue MergedOps = DAG.getBuildVector( 7677 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7678 Ops.clear(); 7679 Ops.push_back(MergedOps); 7680 } 7681 7682 Ops.push_back(TDescr); 7683 if (IsA16) 7684 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7685 Ops.push_back(M->getChain()); 7686 7687 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7688 MachineMemOperand *MemRef = M->getMemOperand(); 7689 DAG.setNodeMemRefs(NewNode, {MemRef}); 7690 return SDValue(NewNode, 0); 7691 } 7692 case Intrinsic::amdgcn_global_atomic_fadd: 7693 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7694 DiagnosticInfoUnsupported 7695 NoFpRet(DAG.getMachineFunction().getFunction(), 7696 "return versions of fp atomics not supported", 7697 DL.getDebugLoc(), DS_Error); 7698 DAG.getContext()->diagnose(NoFpRet); 7699 return SDValue(); 7700 } 7701 LLVM_FALLTHROUGH; 7702 case Intrinsic::amdgcn_global_atomic_fmin: 7703 case Intrinsic::amdgcn_global_atomic_fmax: 7704 case Intrinsic::amdgcn_flat_atomic_fadd: 7705 case Intrinsic::amdgcn_flat_atomic_fmin: 7706 case Intrinsic::amdgcn_flat_atomic_fmax: { 7707 MemSDNode *M = cast<MemSDNode>(Op); 7708 SDValue Ops[] = { 7709 M->getOperand(0), // Chain 7710 M->getOperand(2), // Ptr 7711 M->getOperand(3) // Value 7712 }; 7713 unsigned Opcode = 0; 7714 switch (IntrID) { 7715 case Intrinsic::amdgcn_global_atomic_fadd: 7716 case Intrinsic::amdgcn_flat_atomic_fadd: { 7717 EVT VT = Op.getOperand(3).getValueType(); 7718 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7719 DAG.getVTList(VT, MVT::Other), Ops, 7720 M->getMemOperand()); 7721 } 7722 case Intrinsic::amdgcn_global_atomic_fmin: 7723 case Intrinsic::amdgcn_flat_atomic_fmin: { 7724 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7725 break; 7726 } 7727 case Intrinsic::amdgcn_global_atomic_fmax: 7728 case Intrinsic::amdgcn_flat_atomic_fmax: { 7729 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7730 break; 7731 } 7732 default: 7733 llvm_unreachable("unhandled atomic opcode"); 7734 } 7735 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7736 M->getVTList(), Ops, M->getMemoryVT(), 7737 M->getMemOperand()); 7738 } 7739 default: 7740 7741 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7742 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7743 return lowerImage(Op, ImageDimIntr, DAG, true); 7744 7745 return SDValue(); 7746 } 7747 } 7748 7749 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7750 // dwordx4 if on SI. 7751 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7752 SDVTList VTList, 7753 ArrayRef<SDValue> Ops, EVT MemVT, 7754 MachineMemOperand *MMO, 7755 SelectionDAG &DAG) const { 7756 EVT VT = VTList.VTs[0]; 7757 EVT WidenedVT = VT; 7758 EVT WidenedMemVT = MemVT; 7759 if (!Subtarget->hasDwordx3LoadStores() && 7760 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7761 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7762 WidenedVT.getVectorElementType(), 4); 7763 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7764 WidenedMemVT.getVectorElementType(), 4); 7765 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7766 } 7767 7768 assert(VTList.NumVTs == 2); 7769 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7770 7771 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7772 WidenedMemVT, MMO); 7773 if (WidenedVT != VT) { 7774 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7775 DAG.getVectorIdxConstant(0, DL)); 7776 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7777 } 7778 return NewOp; 7779 } 7780 7781 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7782 bool ImageStore) const { 7783 EVT StoreVT = VData.getValueType(); 7784 7785 // No change for f16 and legal vector D16 types. 7786 if (!StoreVT.isVector()) 7787 return VData; 7788 7789 SDLoc DL(VData); 7790 unsigned NumElements = StoreVT.getVectorNumElements(); 7791 7792 if (Subtarget->hasUnpackedD16VMem()) { 7793 // We need to unpack the packed data to store. 7794 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7795 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7796 7797 EVT EquivStoreVT = 7798 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7799 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7800 return DAG.UnrollVectorOp(ZExt.getNode()); 7801 } 7802 7803 // The sq block of gfx8.1 does not estimate register use correctly for d16 7804 // image store instructions. The data operand is computed as if it were not a 7805 // d16 image instruction. 7806 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7807 // Bitcast to i16 7808 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7809 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7810 7811 // Decompose into scalars 7812 SmallVector<SDValue, 4> Elts; 7813 DAG.ExtractVectorElements(IntVData, Elts); 7814 7815 // Group pairs of i16 into v2i16 and bitcast to i32 7816 SmallVector<SDValue, 4> PackedElts; 7817 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7818 SDValue Pair = 7819 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7820 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7821 PackedElts.push_back(IntPair); 7822 } 7823 if ((NumElements % 2) == 1) { 7824 // Handle v3i16 7825 unsigned I = Elts.size() / 2; 7826 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7827 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7828 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7829 PackedElts.push_back(IntPair); 7830 } 7831 7832 // Pad using UNDEF 7833 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7834 7835 // Build final vector 7836 EVT VecVT = 7837 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7838 return DAG.getBuildVector(VecVT, DL, PackedElts); 7839 } 7840 7841 if (NumElements == 3) { 7842 EVT IntStoreVT = 7843 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7844 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7845 7846 EVT WidenedStoreVT = EVT::getVectorVT( 7847 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7848 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7849 WidenedStoreVT.getStoreSizeInBits()); 7850 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7851 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7852 } 7853 7854 assert(isTypeLegal(StoreVT)); 7855 return VData; 7856 } 7857 7858 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7859 SelectionDAG &DAG) const { 7860 SDLoc DL(Op); 7861 SDValue Chain = Op.getOperand(0); 7862 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7863 MachineFunction &MF = DAG.getMachineFunction(); 7864 7865 switch (IntrinsicID) { 7866 case Intrinsic::amdgcn_exp_compr: { 7867 SDValue Src0 = Op.getOperand(4); 7868 SDValue Src1 = Op.getOperand(5); 7869 // Hack around illegal type on SI by directly selecting it. 7870 if (isTypeLegal(Src0.getValueType())) 7871 return SDValue(); 7872 7873 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7874 SDValue Undef = DAG.getUNDEF(MVT::f32); 7875 const SDValue Ops[] = { 7876 Op.getOperand(2), // tgt 7877 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7878 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7879 Undef, // src2 7880 Undef, // src3 7881 Op.getOperand(7), // vm 7882 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7883 Op.getOperand(3), // en 7884 Op.getOperand(0) // Chain 7885 }; 7886 7887 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7888 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7889 } 7890 case Intrinsic::amdgcn_s_barrier: { 7891 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7892 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7893 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7894 if (WGSize <= ST.getWavefrontSize()) 7895 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7896 Op.getOperand(0)), 0); 7897 } 7898 return SDValue(); 7899 }; 7900 case Intrinsic::amdgcn_tbuffer_store: { 7901 SDValue VData = Op.getOperand(2); 7902 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7903 if (IsD16) 7904 VData = handleD16VData(VData, DAG); 7905 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7906 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7907 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7908 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7909 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7910 SDValue Ops[] = { 7911 Chain, 7912 VData, // vdata 7913 Op.getOperand(3), // rsrc 7914 Op.getOperand(4), // vindex 7915 Op.getOperand(5), // voffset 7916 Op.getOperand(6), // soffset 7917 Op.getOperand(7), // offset 7918 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7919 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7920 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7921 }; 7922 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7923 AMDGPUISD::TBUFFER_STORE_FORMAT; 7924 MemSDNode *M = cast<MemSDNode>(Op); 7925 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7926 M->getMemoryVT(), M->getMemOperand()); 7927 } 7928 7929 case Intrinsic::amdgcn_struct_tbuffer_store: { 7930 SDValue VData = Op.getOperand(2); 7931 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7932 if (IsD16) 7933 VData = handleD16VData(VData, DAG); 7934 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7935 SDValue Ops[] = { 7936 Chain, 7937 VData, // vdata 7938 Op.getOperand(3), // rsrc 7939 Op.getOperand(4), // vindex 7940 Offsets.first, // voffset 7941 Op.getOperand(6), // soffset 7942 Offsets.second, // offset 7943 Op.getOperand(7), // format 7944 Op.getOperand(8), // cachepolicy, swizzled buffer 7945 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7946 }; 7947 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7948 AMDGPUISD::TBUFFER_STORE_FORMAT; 7949 MemSDNode *M = cast<MemSDNode>(Op); 7950 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7951 M->getMemoryVT(), M->getMemOperand()); 7952 } 7953 7954 case Intrinsic::amdgcn_raw_tbuffer_store: { 7955 SDValue VData = Op.getOperand(2); 7956 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7957 if (IsD16) 7958 VData = handleD16VData(VData, DAG); 7959 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7960 SDValue Ops[] = { 7961 Chain, 7962 VData, // vdata 7963 Op.getOperand(3), // rsrc 7964 DAG.getConstant(0, DL, MVT::i32), // vindex 7965 Offsets.first, // voffset 7966 Op.getOperand(5), // soffset 7967 Offsets.second, // offset 7968 Op.getOperand(6), // format 7969 Op.getOperand(7), // cachepolicy, swizzled buffer 7970 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7971 }; 7972 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7973 AMDGPUISD::TBUFFER_STORE_FORMAT; 7974 MemSDNode *M = cast<MemSDNode>(Op); 7975 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7976 M->getMemoryVT(), M->getMemOperand()); 7977 } 7978 7979 case Intrinsic::amdgcn_buffer_store: 7980 case Intrinsic::amdgcn_buffer_store_format: { 7981 SDValue VData = Op.getOperand(2); 7982 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7983 if (IsD16) 7984 VData = handleD16VData(VData, DAG); 7985 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7986 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7987 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7988 SDValue Ops[] = { 7989 Chain, 7990 VData, 7991 Op.getOperand(3), // rsrc 7992 Op.getOperand(4), // vindex 7993 SDValue(), // voffset -- will be set by setBufferOffsets 7994 SDValue(), // soffset -- will be set by setBufferOffsets 7995 SDValue(), // offset -- will be set by setBufferOffsets 7996 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7997 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7998 }; 7999 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8000 8001 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8002 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8003 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8004 MemSDNode *M = cast<MemSDNode>(Op); 8005 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8006 8007 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8008 EVT VDataType = VData.getValueType().getScalarType(); 8009 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8010 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8011 8012 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8013 M->getMemoryVT(), M->getMemOperand()); 8014 } 8015 8016 case Intrinsic::amdgcn_raw_buffer_store: 8017 case Intrinsic::amdgcn_raw_buffer_store_format: { 8018 const bool IsFormat = 8019 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8020 8021 SDValue VData = Op.getOperand(2); 8022 EVT VDataVT = VData.getValueType(); 8023 EVT EltType = VDataVT.getScalarType(); 8024 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8025 if (IsD16) { 8026 VData = handleD16VData(VData, DAG); 8027 VDataVT = VData.getValueType(); 8028 } 8029 8030 if (!isTypeLegal(VDataVT)) { 8031 VData = 8032 DAG.getNode(ISD::BITCAST, DL, 8033 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8034 } 8035 8036 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8037 SDValue Ops[] = { 8038 Chain, 8039 VData, 8040 Op.getOperand(3), // rsrc 8041 DAG.getConstant(0, DL, MVT::i32), // vindex 8042 Offsets.first, // voffset 8043 Op.getOperand(5), // soffset 8044 Offsets.second, // offset 8045 Op.getOperand(6), // cachepolicy, swizzled buffer 8046 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8047 }; 8048 unsigned Opc = 8049 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8050 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8051 MemSDNode *M = cast<MemSDNode>(Op); 8052 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8053 8054 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8055 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8056 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8057 8058 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8059 M->getMemoryVT(), M->getMemOperand()); 8060 } 8061 8062 case Intrinsic::amdgcn_struct_buffer_store: 8063 case Intrinsic::amdgcn_struct_buffer_store_format: { 8064 const bool IsFormat = 8065 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8066 8067 SDValue VData = Op.getOperand(2); 8068 EVT VDataVT = VData.getValueType(); 8069 EVT EltType = VDataVT.getScalarType(); 8070 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8071 8072 if (IsD16) { 8073 VData = handleD16VData(VData, DAG); 8074 VDataVT = VData.getValueType(); 8075 } 8076 8077 if (!isTypeLegal(VDataVT)) { 8078 VData = 8079 DAG.getNode(ISD::BITCAST, DL, 8080 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8081 } 8082 8083 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8084 SDValue Ops[] = { 8085 Chain, 8086 VData, 8087 Op.getOperand(3), // rsrc 8088 Op.getOperand(4), // vindex 8089 Offsets.first, // voffset 8090 Op.getOperand(6), // soffset 8091 Offsets.second, // offset 8092 Op.getOperand(7), // cachepolicy, swizzled buffer 8093 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8094 }; 8095 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8096 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8097 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8098 MemSDNode *M = cast<MemSDNode>(Op); 8099 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8100 8101 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8102 EVT VDataType = VData.getValueType().getScalarType(); 8103 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8104 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8105 8106 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8107 M->getMemoryVT(), M->getMemOperand()); 8108 } 8109 case Intrinsic::amdgcn_end_cf: 8110 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8111 Op->getOperand(2), Chain), 0); 8112 8113 default: { 8114 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8115 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8116 return lowerImage(Op, ImageDimIntr, DAG, true); 8117 8118 return Op; 8119 } 8120 } 8121 } 8122 8123 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8124 // offset (the offset that is included in bounds checking and swizzling, to be 8125 // split between the instruction's voffset and immoffset fields) and soffset 8126 // (the offset that is excluded from bounds checking and swizzling, to go in 8127 // the instruction's soffset field). This function takes the first kind of 8128 // offset and figures out how to split it between voffset and immoffset. 8129 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8130 SDValue Offset, SelectionDAG &DAG) const { 8131 SDLoc DL(Offset); 8132 const unsigned MaxImm = 4095; 8133 SDValue N0 = Offset; 8134 ConstantSDNode *C1 = nullptr; 8135 8136 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8137 N0 = SDValue(); 8138 else if (DAG.isBaseWithConstantOffset(N0)) { 8139 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8140 N0 = N0.getOperand(0); 8141 } 8142 8143 if (C1) { 8144 unsigned ImmOffset = C1->getZExtValue(); 8145 // If the immediate value is too big for the immoffset field, put the value 8146 // and -4096 into the immoffset field so that the value that is copied/added 8147 // for the voffset field is a multiple of 4096, and it stands more chance 8148 // of being CSEd with the copy/add for another similar load/store. 8149 // However, do not do that rounding down to a multiple of 4096 if that is a 8150 // negative number, as it appears to be illegal to have a negative offset 8151 // in the vgpr, even if adding the immediate offset makes it positive. 8152 unsigned Overflow = ImmOffset & ~MaxImm; 8153 ImmOffset -= Overflow; 8154 if ((int32_t)Overflow < 0) { 8155 Overflow += ImmOffset; 8156 ImmOffset = 0; 8157 } 8158 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8159 if (Overflow) { 8160 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8161 if (!N0) 8162 N0 = OverflowVal; 8163 else { 8164 SDValue Ops[] = { N0, OverflowVal }; 8165 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8166 } 8167 } 8168 } 8169 if (!N0) 8170 N0 = DAG.getConstant(0, DL, MVT::i32); 8171 if (!C1) 8172 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8173 return {N0, SDValue(C1, 0)}; 8174 } 8175 8176 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8177 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8178 // pointed to by Offsets. 8179 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8180 SelectionDAG &DAG, SDValue *Offsets, 8181 Align Alignment) const { 8182 SDLoc DL(CombinedOffset); 8183 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8184 uint32_t Imm = C->getZExtValue(); 8185 uint32_t SOffset, ImmOffset; 8186 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8187 Alignment)) { 8188 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8189 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8190 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8191 return; 8192 } 8193 } 8194 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8195 SDValue N0 = CombinedOffset.getOperand(0); 8196 SDValue N1 = CombinedOffset.getOperand(1); 8197 uint32_t SOffset, ImmOffset; 8198 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8199 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8200 Subtarget, Alignment)) { 8201 Offsets[0] = N0; 8202 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8203 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8204 return; 8205 } 8206 } 8207 Offsets[0] = CombinedOffset; 8208 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8209 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8210 } 8211 8212 // Handle 8 bit and 16 bit buffer loads 8213 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8214 EVT LoadVT, SDLoc DL, 8215 ArrayRef<SDValue> Ops, 8216 MemSDNode *M) const { 8217 EVT IntVT = LoadVT.changeTypeToInteger(); 8218 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8219 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8220 8221 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8222 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8223 Ops, IntVT, 8224 M->getMemOperand()); 8225 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8226 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8227 8228 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8229 } 8230 8231 // Handle 8 bit and 16 bit buffer stores 8232 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8233 EVT VDataType, SDLoc DL, 8234 SDValue Ops[], 8235 MemSDNode *M) const { 8236 if (VDataType == MVT::f16) 8237 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8238 8239 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8240 Ops[1] = BufferStoreExt; 8241 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8242 AMDGPUISD::BUFFER_STORE_SHORT; 8243 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8244 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8245 M->getMemOperand()); 8246 } 8247 8248 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8249 ISD::LoadExtType ExtType, SDValue Op, 8250 const SDLoc &SL, EVT VT) { 8251 if (VT.bitsLT(Op.getValueType())) 8252 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8253 8254 switch (ExtType) { 8255 case ISD::SEXTLOAD: 8256 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8257 case ISD::ZEXTLOAD: 8258 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8259 case ISD::EXTLOAD: 8260 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8261 case ISD::NON_EXTLOAD: 8262 return Op; 8263 } 8264 8265 llvm_unreachable("invalid ext type"); 8266 } 8267 8268 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8269 SelectionDAG &DAG = DCI.DAG; 8270 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8271 return SDValue(); 8272 8273 // FIXME: Constant loads should all be marked invariant. 8274 unsigned AS = Ld->getAddressSpace(); 8275 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8276 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8277 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8278 return SDValue(); 8279 8280 // Don't do this early, since it may interfere with adjacent load merging for 8281 // illegal types. We can avoid losing alignment information for exotic types 8282 // pre-legalize. 8283 EVT MemVT = Ld->getMemoryVT(); 8284 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8285 MemVT.getSizeInBits() >= 32) 8286 return SDValue(); 8287 8288 SDLoc SL(Ld); 8289 8290 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8291 "unexpected vector extload"); 8292 8293 // TODO: Drop only high part of range. 8294 SDValue Ptr = Ld->getBasePtr(); 8295 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8296 MVT::i32, SL, Ld->getChain(), Ptr, 8297 Ld->getOffset(), 8298 Ld->getPointerInfo(), MVT::i32, 8299 Ld->getAlignment(), 8300 Ld->getMemOperand()->getFlags(), 8301 Ld->getAAInfo(), 8302 nullptr); // Drop ranges 8303 8304 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8305 if (MemVT.isFloatingPoint()) { 8306 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8307 "unexpected fp extload"); 8308 TruncVT = MemVT.changeTypeToInteger(); 8309 } 8310 8311 SDValue Cvt = NewLoad; 8312 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8313 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8314 DAG.getValueType(TruncVT)); 8315 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8316 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8317 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8318 } else { 8319 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8320 } 8321 8322 EVT VT = Ld->getValueType(0); 8323 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8324 8325 DCI.AddToWorklist(Cvt.getNode()); 8326 8327 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8328 // the appropriate extension from the 32-bit load. 8329 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8330 DCI.AddToWorklist(Cvt.getNode()); 8331 8332 // Handle conversion back to floating point if necessary. 8333 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8334 8335 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8336 } 8337 8338 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8339 SDLoc DL(Op); 8340 LoadSDNode *Load = cast<LoadSDNode>(Op); 8341 ISD::LoadExtType ExtType = Load->getExtensionType(); 8342 EVT MemVT = Load->getMemoryVT(); 8343 8344 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8345 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8346 return SDValue(); 8347 8348 // FIXME: Copied from PPC 8349 // First, load into 32 bits, then truncate to 1 bit. 8350 8351 SDValue Chain = Load->getChain(); 8352 SDValue BasePtr = Load->getBasePtr(); 8353 MachineMemOperand *MMO = Load->getMemOperand(); 8354 8355 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8356 8357 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8358 BasePtr, RealMemVT, MMO); 8359 8360 if (!MemVT.isVector()) { 8361 SDValue Ops[] = { 8362 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8363 NewLD.getValue(1) 8364 }; 8365 8366 return DAG.getMergeValues(Ops, DL); 8367 } 8368 8369 SmallVector<SDValue, 3> Elts; 8370 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8371 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8372 DAG.getConstant(I, DL, MVT::i32)); 8373 8374 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8375 } 8376 8377 SDValue Ops[] = { 8378 DAG.getBuildVector(MemVT, DL, Elts), 8379 NewLD.getValue(1) 8380 }; 8381 8382 return DAG.getMergeValues(Ops, DL); 8383 } 8384 8385 if (!MemVT.isVector()) 8386 return SDValue(); 8387 8388 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8389 "Custom lowering for non-i32 vectors hasn't been implemented."); 8390 8391 unsigned Alignment = Load->getAlignment(); 8392 unsigned AS = Load->getAddressSpace(); 8393 if (Subtarget->hasLDSMisalignedBug() && 8394 AS == AMDGPUAS::FLAT_ADDRESS && 8395 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8396 return SplitVectorLoad(Op, DAG); 8397 } 8398 8399 MachineFunction &MF = DAG.getMachineFunction(); 8400 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8401 // If there is a possibility that flat instruction access scratch memory 8402 // then we need to use the same legalization rules we use for private. 8403 if (AS == AMDGPUAS::FLAT_ADDRESS && 8404 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8405 AS = MFI->hasFlatScratchInit() ? 8406 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8407 8408 unsigned NumElements = MemVT.getVectorNumElements(); 8409 8410 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8411 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8412 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8413 if (MemVT.isPow2VectorType()) 8414 return SDValue(); 8415 return WidenOrSplitVectorLoad(Op, DAG); 8416 } 8417 // Non-uniform loads will be selected to MUBUF instructions, so they 8418 // have the same legalization requirements as global and private 8419 // loads. 8420 // 8421 } 8422 8423 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8424 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8425 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8426 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8427 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8428 Alignment >= 4 && NumElements < 32) { 8429 if (MemVT.isPow2VectorType()) 8430 return SDValue(); 8431 return WidenOrSplitVectorLoad(Op, DAG); 8432 } 8433 // Non-uniform loads will be selected to MUBUF instructions, so they 8434 // have the same legalization requirements as global and private 8435 // loads. 8436 // 8437 } 8438 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8439 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8440 AS == AMDGPUAS::GLOBAL_ADDRESS || 8441 AS == AMDGPUAS::FLAT_ADDRESS) { 8442 if (NumElements > 4) 8443 return SplitVectorLoad(Op, DAG); 8444 // v3 loads not supported on SI. 8445 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8446 return WidenOrSplitVectorLoad(Op, DAG); 8447 8448 // v3 and v4 loads are supported for private and global memory. 8449 return SDValue(); 8450 } 8451 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8452 // Depending on the setting of the private_element_size field in the 8453 // resource descriptor, we can only make private accesses up to a certain 8454 // size. 8455 switch (Subtarget->getMaxPrivateElementSize()) { 8456 case 4: { 8457 SDValue Ops[2]; 8458 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8459 return DAG.getMergeValues(Ops, DL); 8460 } 8461 case 8: 8462 if (NumElements > 2) 8463 return SplitVectorLoad(Op, DAG); 8464 return SDValue(); 8465 case 16: 8466 // Same as global/flat 8467 if (NumElements > 4) 8468 return SplitVectorLoad(Op, DAG); 8469 // v3 loads not supported on SI. 8470 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8471 return WidenOrSplitVectorLoad(Op, DAG); 8472 8473 return SDValue(); 8474 default: 8475 llvm_unreachable("unsupported private_element_size"); 8476 } 8477 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8478 // Use ds_read_b128 or ds_read_b96 when possible. 8479 if (Subtarget->hasDS96AndDS128() && 8480 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8481 MemVT.getStoreSize() == 12) && 8482 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8483 Load->getAlign())) 8484 return SDValue(); 8485 8486 if (NumElements > 2) 8487 return SplitVectorLoad(Op, DAG); 8488 8489 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 8490 // address is negative, then the instruction is incorrectly treated as 8491 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8492 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8493 // load later in the SILoadStoreOptimizer. 8494 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8495 NumElements == 2 && MemVT.getStoreSize() == 8 && 8496 Load->getAlignment() < 8) { 8497 return SplitVectorLoad(Op, DAG); 8498 } 8499 } 8500 8501 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8502 MemVT, *Load->getMemOperand())) { 8503 SDValue Ops[2]; 8504 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8505 return DAG.getMergeValues(Ops, DL); 8506 } 8507 8508 return SDValue(); 8509 } 8510 8511 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8512 EVT VT = Op.getValueType(); 8513 if (VT.getSizeInBits() == 128) 8514 return splitTernaryVectorOp(Op, DAG); 8515 8516 assert(VT.getSizeInBits() == 64); 8517 8518 SDLoc DL(Op); 8519 SDValue Cond = Op.getOperand(0); 8520 8521 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8522 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8523 8524 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8525 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8526 8527 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8528 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8529 8530 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8531 8532 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8533 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8534 8535 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8536 8537 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8538 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8539 } 8540 8541 // Catch division cases where we can use shortcuts with rcp and rsq 8542 // instructions. 8543 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8544 SelectionDAG &DAG) const { 8545 SDLoc SL(Op); 8546 SDValue LHS = Op.getOperand(0); 8547 SDValue RHS = Op.getOperand(1); 8548 EVT VT = Op.getValueType(); 8549 const SDNodeFlags Flags = Op->getFlags(); 8550 8551 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8552 8553 // Without !fpmath accuracy information, we can't do more because we don't 8554 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8555 if (!AllowInaccurateRcp) 8556 return SDValue(); 8557 8558 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8559 if (CLHS->isExactlyValue(1.0)) { 8560 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8561 // the CI documentation has a worst case error of 1 ulp. 8562 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8563 // use it as long as we aren't trying to use denormals. 8564 // 8565 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8566 8567 // 1.0 / sqrt(x) -> rsq(x) 8568 8569 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8570 // error seems really high at 2^29 ULP. 8571 if (RHS.getOpcode() == ISD::FSQRT) 8572 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8573 8574 // 1.0 / x -> rcp(x) 8575 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8576 } 8577 8578 // Same as for 1.0, but expand the sign out of the constant. 8579 if (CLHS->isExactlyValue(-1.0)) { 8580 // -1.0 / x -> rcp (fneg x) 8581 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8582 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8583 } 8584 } 8585 8586 // Turn into multiply by the reciprocal. 8587 // x / y -> x * (1.0 / y) 8588 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8589 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8590 } 8591 8592 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8593 SelectionDAG &DAG) const { 8594 SDLoc SL(Op); 8595 SDValue X = Op.getOperand(0); 8596 SDValue Y = Op.getOperand(1); 8597 EVT VT = Op.getValueType(); 8598 const SDNodeFlags Flags = Op->getFlags(); 8599 8600 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8601 DAG.getTarget().Options.UnsafeFPMath; 8602 if (!AllowInaccurateDiv) 8603 return SDValue(); 8604 8605 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8606 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8607 8608 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8609 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8610 8611 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8612 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8613 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8614 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8615 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8616 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8617 } 8618 8619 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8620 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8621 SDNodeFlags Flags) { 8622 if (GlueChain->getNumValues() <= 1) { 8623 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8624 } 8625 8626 assert(GlueChain->getNumValues() == 3); 8627 8628 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8629 switch (Opcode) { 8630 default: llvm_unreachable("no chain equivalent for opcode"); 8631 case ISD::FMUL: 8632 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8633 break; 8634 } 8635 8636 return DAG.getNode(Opcode, SL, VTList, 8637 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8638 Flags); 8639 } 8640 8641 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8642 EVT VT, SDValue A, SDValue B, SDValue C, 8643 SDValue GlueChain, SDNodeFlags Flags) { 8644 if (GlueChain->getNumValues() <= 1) { 8645 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8646 } 8647 8648 assert(GlueChain->getNumValues() == 3); 8649 8650 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8651 switch (Opcode) { 8652 default: llvm_unreachable("no chain equivalent for opcode"); 8653 case ISD::FMA: 8654 Opcode = AMDGPUISD::FMA_W_CHAIN; 8655 break; 8656 } 8657 8658 return DAG.getNode(Opcode, SL, VTList, 8659 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8660 Flags); 8661 } 8662 8663 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8664 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8665 return FastLowered; 8666 8667 SDLoc SL(Op); 8668 SDValue Src0 = Op.getOperand(0); 8669 SDValue Src1 = Op.getOperand(1); 8670 8671 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8672 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8673 8674 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8675 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8676 8677 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8678 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8679 8680 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8681 } 8682 8683 // Faster 2.5 ULP division that does not support denormals. 8684 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8685 SDLoc SL(Op); 8686 SDValue LHS = Op.getOperand(1); 8687 SDValue RHS = Op.getOperand(2); 8688 8689 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8690 8691 const APFloat K0Val(BitsToFloat(0x6f800000)); 8692 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8693 8694 const APFloat K1Val(BitsToFloat(0x2f800000)); 8695 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8696 8697 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8698 8699 EVT SetCCVT = 8700 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8701 8702 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8703 8704 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8705 8706 // TODO: Should this propagate fast-math-flags? 8707 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8708 8709 // rcp does not support denormals. 8710 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8711 8712 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8713 8714 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8715 } 8716 8717 // Returns immediate value for setting the F32 denorm mode when using the 8718 // S_DENORM_MODE instruction. 8719 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8720 const SDLoc &SL, const GCNSubtarget *ST) { 8721 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8722 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8723 ? FP_DENORM_FLUSH_NONE 8724 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8725 8726 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8727 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8728 } 8729 8730 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8731 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8732 return FastLowered; 8733 8734 // The selection matcher assumes anything with a chain selecting to a 8735 // mayRaiseFPException machine instruction. Since we're introducing a chain 8736 // here, we need to explicitly report nofpexcept for the regular fdiv 8737 // lowering. 8738 SDNodeFlags Flags = Op->getFlags(); 8739 Flags.setNoFPExcept(true); 8740 8741 SDLoc SL(Op); 8742 SDValue LHS = Op.getOperand(0); 8743 SDValue RHS = Op.getOperand(1); 8744 8745 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8746 8747 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8748 8749 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8750 {RHS, RHS, LHS}, Flags); 8751 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8752 {LHS, RHS, LHS}, Flags); 8753 8754 // Denominator is scaled to not be denormal, so using rcp is ok. 8755 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8756 DenominatorScaled, Flags); 8757 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8758 DenominatorScaled, Flags); 8759 8760 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8761 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8762 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8763 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8764 8765 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8766 8767 if (!HasFP32Denormals) { 8768 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8769 // lowering. The chain dependence is insufficient, and we need glue. We do 8770 // not need the glue variants in a strictfp function. 8771 8772 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8773 8774 SDNode *EnableDenorm; 8775 if (Subtarget->hasDenormModeInst()) { 8776 const SDValue EnableDenormValue = 8777 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8778 8779 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8780 DAG.getEntryNode(), EnableDenormValue).getNode(); 8781 } else { 8782 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8783 SL, MVT::i32); 8784 EnableDenorm = 8785 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8786 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8787 } 8788 8789 SDValue Ops[3] = { 8790 NegDivScale0, 8791 SDValue(EnableDenorm, 0), 8792 SDValue(EnableDenorm, 1) 8793 }; 8794 8795 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8796 } 8797 8798 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8799 ApproxRcp, One, NegDivScale0, Flags); 8800 8801 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8802 ApproxRcp, Fma0, Flags); 8803 8804 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8805 Fma1, Fma1, Flags); 8806 8807 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8808 NumeratorScaled, Mul, Flags); 8809 8810 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8811 Fma2, Fma1, Mul, Fma2, Flags); 8812 8813 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8814 NumeratorScaled, Fma3, Flags); 8815 8816 if (!HasFP32Denormals) { 8817 SDNode *DisableDenorm; 8818 if (Subtarget->hasDenormModeInst()) { 8819 const SDValue DisableDenormValue = 8820 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8821 8822 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8823 Fma4.getValue(1), DisableDenormValue, 8824 Fma4.getValue(2)).getNode(); 8825 } else { 8826 const SDValue DisableDenormValue = 8827 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8828 8829 DisableDenorm = DAG.getMachineNode( 8830 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8831 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8832 } 8833 8834 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8835 SDValue(DisableDenorm, 0), DAG.getRoot()); 8836 DAG.setRoot(OutputChain); 8837 } 8838 8839 SDValue Scale = NumeratorScaled.getValue(1); 8840 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8841 {Fma4, Fma1, Fma3, Scale}, Flags); 8842 8843 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8844 } 8845 8846 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8847 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8848 return FastLowered; 8849 8850 SDLoc SL(Op); 8851 SDValue X = Op.getOperand(0); 8852 SDValue Y = Op.getOperand(1); 8853 8854 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8855 8856 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8857 8858 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8859 8860 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8861 8862 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8863 8864 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8865 8866 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8867 8868 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8869 8870 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8871 8872 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8873 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8874 8875 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8876 NegDivScale0, Mul, DivScale1); 8877 8878 SDValue Scale; 8879 8880 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8881 // Workaround a hardware bug on SI where the condition output from div_scale 8882 // is not usable. 8883 8884 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8885 8886 // Figure out if the scale to use for div_fmas. 8887 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8888 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8889 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8890 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8891 8892 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8893 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8894 8895 SDValue Scale0Hi 8896 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8897 SDValue Scale1Hi 8898 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8899 8900 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8901 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8902 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8903 } else { 8904 Scale = DivScale1.getValue(1); 8905 } 8906 8907 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8908 Fma4, Fma3, Mul, Scale); 8909 8910 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8911 } 8912 8913 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8914 EVT VT = Op.getValueType(); 8915 8916 if (VT == MVT::f32) 8917 return LowerFDIV32(Op, DAG); 8918 8919 if (VT == MVT::f64) 8920 return LowerFDIV64(Op, DAG); 8921 8922 if (VT == MVT::f16) 8923 return LowerFDIV16(Op, DAG); 8924 8925 llvm_unreachable("Unexpected type for fdiv"); 8926 } 8927 8928 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8929 SDLoc DL(Op); 8930 StoreSDNode *Store = cast<StoreSDNode>(Op); 8931 EVT VT = Store->getMemoryVT(); 8932 8933 if (VT == MVT::i1) { 8934 return DAG.getTruncStore(Store->getChain(), DL, 8935 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8936 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8937 } 8938 8939 assert(VT.isVector() && 8940 Store->getValue().getValueType().getScalarType() == MVT::i32); 8941 8942 unsigned AS = Store->getAddressSpace(); 8943 if (Subtarget->hasLDSMisalignedBug() && 8944 AS == AMDGPUAS::FLAT_ADDRESS && 8945 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8946 return SplitVectorStore(Op, DAG); 8947 } 8948 8949 MachineFunction &MF = DAG.getMachineFunction(); 8950 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8951 // If there is a possibility that flat instruction access scratch memory 8952 // then we need to use the same legalization rules we use for private. 8953 if (AS == AMDGPUAS::FLAT_ADDRESS && 8954 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8955 AS = MFI->hasFlatScratchInit() ? 8956 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8957 8958 unsigned NumElements = VT.getVectorNumElements(); 8959 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8960 AS == AMDGPUAS::FLAT_ADDRESS) { 8961 if (NumElements > 4) 8962 return SplitVectorStore(Op, DAG); 8963 // v3 stores not supported on SI. 8964 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8965 return SplitVectorStore(Op, DAG); 8966 8967 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8968 VT, *Store->getMemOperand())) 8969 return expandUnalignedStore(Store, DAG); 8970 8971 return SDValue(); 8972 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8973 switch (Subtarget->getMaxPrivateElementSize()) { 8974 case 4: 8975 return scalarizeVectorStore(Store, DAG); 8976 case 8: 8977 if (NumElements > 2) 8978 return SplitVectorStore(Op, DAG); 8979 return SDValue(); 8980 case 16: 8981 if (NumElements > 4 || 8982 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8983 return SplitVectorStore(Op, DAG); 8984 return SDValue(); 8985 default: 8986 llvm_unreachable("unsupported private_element_size"); 8987 } 8988 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8989 // Use ds_write_b128 or ds_write_b96 when possible. 8990 if (Subtarget->hasDS96AndDS128() && 8991 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8992 (VT.getStoreSize() == 12)) && 8993 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8994 Store->getAlign())) 8995 return SDValue(); 8996 8997 if (NumElements > 2) 8998 return SplitVectorStore(Op, DAG); 8999 9000 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 9001 // address is negative, then the instruction is incorrectly treated as 9002 // out-of-bounds even if base + offsets is in bounds. Split vectorized 9003 // stores here to avoid emitting ds_write2_b32. We may re-combine the 9004 // store later in the SILoadStoreOptimizer. 9005 if (!Subtarget->hasUsableDSOffset() && 9006 NumElements == 2 && VT.getStoreSize() == 8 && 9007 Store->getAlignment() < 8) { 9008 return SplitVectorStore(Op, DAG); 9009 } 9010 9011 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9012 VT, *Store->getMemOperand())) { 9013 if (VT.isVector()) 9014 return SplitVectorStore(Op, DAG); 9015 return expandUnalignedStore(Store, DAG); 9016 } 9017 9018 return SDValue(); 9019 } else { 9020 llvm_unreachable("unhandled address space"); 9021 } 9022 } 9023 9024 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9025 SDLoc DL(Op); 9026 EVT VT = Op.getValueType(); 9027 SDValue Arg = Op.getOperand(0); 9028 SDValue TrigVal; 9029 9030 // Propagate fast-math flags so that the multiply we introduce can be folded 9031 // if Arg is already the result of a multiply by constant. 9032 auto Flags = Op->getFlags(); 9033 9034 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9035 9036 if (Subtarget->hasTrigReducedRange()) { 9037 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9038 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9039 } else { 9040 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9041 } 9042 9043 switch (Op.getOpcode()) { 9044 case ISD::FCOS: 9045 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9046 case ISD::FSIN: 9047 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9048 default: 9049 llvm_unreachable("Wrong trig opcode"); 9050 } 9051 } 9052 9053 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9054 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9055 assert(AtomicNode->isCompareAndSwap()); 9056 unsigned AS = AtomicNode->getAddressSpace(); 9057 9058 // No custom lowering required for local address space 9059 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9060 return Op; 9061 9062 // Non-local address space requires custom lowering for atomic compare 9063 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9064 SDLoc DL(Op); 9065 SDValue ChainIn = Op.getOperand(0); 9066 SDValue Addr = Op.getOperand(1); 9067 SDValue Old = Op.getOperand(2); 9068 SDValue New = Op.getOperand(3); 9069 EVT VT = Op.getValueType(); 9070 MVT SimpleVT = VT.getSimpleVT(); 9071 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9072 9073 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9074 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9075 9076 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9077 Ops, VT, AtomicNode->getMemOperand()); 9078 } 9079 9080 //===----------------------------------------------------------------------===// 9081 // Custom DAG optimizations 9082 //===----------------------------------------------------------------------===// 9083 9084 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9085 DAGCombinerInfo &DCI) const { 9086 EVT VT = N->getValueType(0); 9087 EVT ScalarVT = VT.getScalarType(); 9088 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9089 return SDValue(); 9090 9091 SelectionDAG &DAG = DCI.DAG; 9092 SDLoc DL(N); 9093 9094 SDValue Src = N->getOperand(0); 9095 EVT SrcVT = Src.getValueType(); 9096 9097 // TODO: We could try to match extracting the higher bytes, which would be 9098 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9099 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9100 // about in practice. 9101 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9102 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9103 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9104 DCI.AddToWorklist(Cvt.getNode()); 9105 9106 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9107 if (ScalarVT != MVT::f32) { 9108 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9109 DAG.getTargetConstant(0, DL, MVT::i32)); 9110 } 9111 return Cvt; 9112 } 9113 } 9114 9115 return SDValue(); 9116 } 9117 9118 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9119 9120 // This is a variant of 9121 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9122 // 9123 // The normal DAG combiner will do this, but only if the add has one use since 9124 // that would increase the number of instructions. 9125 // 9126 // This prevents us from seeing a constant offset that can be folded into a 9127 // memory instruction's addressing mode. If we know the resulting add offset of 9128 // a pointer can be folded into an addressing offset, we can replace the pointer 9129 // operand with the add of new constant offset. This eliminates one of the uses, 9130 // and may allow the remaining use to also be simplified. 9131 // 9132 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9133 unsigned AddrSpace, 9134 EVT MemVT, 9135 DAGCombinerInfo &DCI) const { 9136 SDValue N0 = N->getOperand(0); 9137 SDValue N1 = N->getOperand(1); 9138 9139 // We only do this to handle cases where it's profitable when there are 9140 // multiple uses of the add, so defer to the standard combine. 9141 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9142 N0->hasOneUse()) 9143 return SDValue(); 9144 9145 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9146 if (!CN1) 9147 return SDValue(); 9148 9149 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9150 if (!CAdd) 9151 return SDValue(); 9152 9153 // If the resulting offset is too large, we can't fold it into the addressing 9154 // mode offset. 9155 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9156 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9157 9158 AddrMode AM; 9159 AM.HasBaseReg = true; 9160 AM.BaseOffs = Offset.getSExtValue(); 9161 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9162 return SDValue(); 9163 9164 SelectionDAG &DAG = DCI.DAG; 9165 SDLoc SL(N); 9166 EVT VT = N->getValueType(0); 9167 9168 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9169 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9170 9171 SDNodeFlags Flags; 9172 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9173 (N0.getOpcode() == ISD::OR || 9174 N0->getFlags().hasNoUnsignedWrap())); 9175 9176 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9177 } 9178 9179 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9180 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9181 /// specific intrinsic, but they all place the pointer operand first. 9182 static unsigned getBasePtrIndex(const MemSDNode *N) { 9183 switch (N->getOpcode()) { 9184 case ISD::STORE: 9185 case ISD::INTRINSIC_W_CHAIN: 9186 case ISD::INTRINSIC_VOID: 9187 return 2; 9188 default: 9189 return 1; 9190 } 9191 } 9192 9193 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9194 DAGCombinerInfo &DCI) const { 9195 SelectionDAG &DAG = DCI.DAG; 9196 SDLoc SL(N); 9197 9198 unsigned PtrIdx = getBasePtrIndex(N); 9199 SDValue Ptr = N->getOperand(PtrIdx); 9200 9201 // TODO: We could also do this for multiplies. 9202 if (Ptr.getOpcode() == ISD::SHL) { 9203 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9204 N->getMemoryVT(), DCI); 9205 if (NewPtr) { 9206 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9207 9208 NewOps[PtrIdx] = NewPtr; 9209 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9210 } 9211 } 9212 9213 return SDValue(); 9214 } 9215 9216 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9217 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9218 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9219 (Opc == ISD::XOR && Val == 0); 9220 } 9221 9222 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9223 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9224 // integer combine opportunities since most 64-bit operations are decomposed 9225 // this way. TODO: We won't want this for SALU especially if it is an inline 9226 // immediate. 9227 SDValue SITargetLowering::splitBinaryBitConstantOp( 9228 DAGCombinerInfo &DCI, 9229 const SDLoc &SL, 9230 unsigned Opc, SDValue LHS, 9231 const ConstantSDNode *CRHS) const { 9232 uint64_t Val = CRHS->getZExtValue(); 9233 uint32_t ValLo = Lo_32(Val); 9234 uint32_t ValHi = Hi_32(Val); 9235 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9236 9237 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9238 bitOpWithConstantIsReducible(Opc, ValHi)) || 9239 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9240 // If we need to materialize a 64-bit immediate, it will be split up later 9241 // anyway. Avoid creating the harder to understand 64-bit immediate 9242 // materialization. 9243 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9244 } 9245 9246 return SDValue(); 9247 } 9248 9249 // Returns true if argument is a boolean value which is not serialized into 9250 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9251 static bool isBoolSGPR(SDValue V) { 9252 if (V.getValueType() != MVT::i1) 9253 return false; 9254 switch (V.getOpcode()) { 9255 default: 9256 break; 9257 case ISD::SETCC: 9258 case AMDGPUISD::FP_CLASS: 9259 return true; 9260 case ISD::AND: 9261 case ISD::OR: 9262 case ISD::XOR: 9263 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9264 } 9265 return false; 9266 } 9267 9268 // If a constant has all zeroes or all ones within each byte return it. 9269 // Otherwise return 0. 9270 static uint32_t getConstantPermuteMask(uint32_t C) { 9271 // 0xff for any zero byte in the mask 9272 uint32_t ZeroByteMask = 0; 9273 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9274 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9275 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9276 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9277 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9278 if ((NonZeroByteMask & C) != NonZeroByteMask) 9279 return 0; // Partial bytes selected. 9280 return C; 9281 } 9282 9283 // Check if a node selects whole bytes from its operand 0 starting at a byte 9284 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9285 // or -1 if not succeeded. 9286 // Note byte select encoding: 9287 // value 0-3 selects corresponding source byte; 9288 // value 0xc selects zero; 9289 // value 0xff selects 0xff. 9290 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9291 assert(V.getValueSizeInBits() == 32); 9292 9293 if (V.getNumOperands() != 2) 9294 return ~0; 9295 9296 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9297 if (!N1) 9298 return ~0; 9299 9300 uint32_t C = N1->getZExtValue(); 9301 9302 switch (V.getOpcode()) { 9303 default: 9304 break; 9305 case ISD::AND: 9306 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9307 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9308 } 9309 break; 9310 9311 case ISD::OR: 9312 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9313 return (0x03020100 & ~ConstMask) | ConstMask; 9314 } 9315 break; 9316 9317 case ISD::SHL: 9318 if (C % 8) 9319 return ~0; 9320 9321 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9322 9323 case ISD::SRL: 9324 if (C % 8) 9325 return ~0; 9326 9327 return uint32_t(0x0c0c0c0c03020100ull >> C); 9328 } 9329 9330 return ~0; 9331 } 9332 9333 SDValue SITargetLowering::performAndCombine(SDNode *N, 9334 DAGCombinerInfo &DCI) const { 9335 if (DCI.isBeforeLegalize()) 9336 return SDValue(); 9337 9338 SelectionDAG &DAG = DCI.DAG; 9339 EVT VT = N->getValueType(0); 9340 SDValue LHS = N->getOperand(0); 9341 SDValue RHS = N->getOperand(1); 9342 9343 9344 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9345 if (VT == MVT::i64 && CRHS) { 9346 if (SDValue Split 9347 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9348 return Split; 9349 } 9350 9351 if (CRHS && VT == MVT::i32) { 9352 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9353 // nb = number of trailing zeroes in mask 9354 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9355 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9356 uint64_t Mask = CRHS->getZExtValue(); 9357 unsigned Bits = countPopulation(Mask); 9358 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9359 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9360 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9361 unsigned Shift = CShift->getZExtValue(); 9362 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9363 unsigned Offset = NB + Shift; 9364 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9365 SDLoc SL(N); 9366 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9367 LHS->getOperand(0), 9368 DAG.getConstant(Offset, SL, MVT::i32), 9369 DAG.getConstant(Bits, SL, MVT::i32)); 9370 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9371 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9372 DAG.getValueType(NarrowVT)); 9373 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9374 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9375 return Shl; 9376 } 9377 } 9378 } 9379 9380 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9381 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9382 isa<ConstantSDNode>(LHS.getOperand(2))) { 9383 uint32_t Sel = getConstantPermuteMask(Mask); 9384 if (!Sel) 9385 return SDValue(); 9386 9387 // Select 0xc for all zero bytes 9388 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9389 SDLoc DL(N); 9390 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9391 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9392 } 9393 } 9394 9395 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9396 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9397 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9398 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9399 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9400 9401 SDValue X = LHS.getOperand(0); 9402 SDValue Y = RHS.getOperand(0); 9403 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9404 return SDValue(); 9405 9406 if (LCC == ISD::SETO) { 9407 if (X != LHS.getOperand(1)) 9408 return SDValue(); 9409 9410 if (RCC == ISD::SETUNE) { 9411 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9412 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9413 return SDValue(); 9414 9415 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9416 SIInstrFlags::N_SUBNORMAL | 9417 SIInstrFlags::N_ZERO | 9418 SIInstrFlags::P_ZERO | 9419 SIInstrFlags::P_SUBNORMAL | 9420 SIInstrFlags::P_NORMAL; 9421 9422 static_assert(((~(SIInstrFlags::S_NAN | 9423 SIInstrFlags::Q_NAN | 9424 SIInstrFlags::N_INFINITY | 9425 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9426 "mask not equal"); 9427 9428 SDLoc DL(N); 9429 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9430 X, DAG.getConstant(Mask, DL, MVT::i32)); 9431 } 9432 } 9433 } 9434 9435 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9436 std::swap(LHS, RHS); 9437 9438 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9439 RHS.hasOneUse()) { 9440 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9441 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9442 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9443 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9444 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9445 (RHS.getOperand(0) == LHS.getOperand(0) && 9446 LHS.getOperand(0) == LHS.getOperand(1))) { 9447 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9448 unsigned NewMask = LCC == ISD::SETO ? 9449 Mask->getZExtValue() & ~OrdMask : 9450 Mask->getZExtValue() & OrdMask; 9451 9452 SDLoc DL(N); 9453 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9454 DAG.getConstant(NewMask, DL, MVT::i32)); 9455 } 9456 } 9457 9458 if (VT == MVT::i32 && 9459 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9460 // and x, (sext cc from i1) => select cc, x, 0 9461 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9462 std::swap(LHS, RHS); 9463 if (isBoolSGPR(RHS.getOperand(0))) 9464 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9465 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9466 } 9467 9468 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9469 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9470 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9471 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9472 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9473 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9474 if (LHSMask != ~0u && RHSMask != ~0u) { 9475 // Canonicalize the expression in an attempt to have fewer unique masks 9476 // and therefore fewer registers used to hold the masks. 9477 if (LHSMask > RHSMask) { 9478 std::swap(LHSMask, RHSMask); 9479 std::swap(LHS, RHS); 9480 } 9481 9482 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9483 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9484 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9485 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9486 9487 // Check of we need to combine values from two sources within a byte. 9488 if (!(LHSUsedLanes & RHSUsedLanes) && 9489 // If we select high and lower word keep it for SDWA. 9490 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9491 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9492 // Each byte in each mask is either selector mask 0-3, or has higher 9493 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9494 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9495 // mask which is not 0xff wins. By anding both masks we have a correct 9496 // result except that 0x0c shall be corrected to give 0x0c only. 9497 uint32_t Mask = LHSMask & RHSMask; 9498 for (unsigned I = 0; I < 32; I += 8) { 9499 uint32_t ByteSel = 0xff << I; 9500 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9501 Mask &= (0x0c << I) & 0xffffffff; 9502 } 9503 9504 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9505 // or 0x0c. 9506 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9507 SDLoc DL(N); 9508 9509 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9510 LHS.getOperand(0), RHS.getOperand(0), 9511 DAG.getConstant(Sel, DL, MVT::i32)); 9512 } 9513 } 9514 } 9515 9516 return SDValue(); 9517 } 9518 9519 SDValue SITargetLowering::performOrCombine(SDNode *N, 9520 DAGCombinerInfo &DCI) const { 9521 SelectionDAG &DAG = DCI.DAG; 9522 SDValue LHS = N->getOperand(0); 9523 SDValue RHS = N->getOperand(1); 9524 9525 EVT VT = N->getValueType(0); 9526 if (VT == MVT::i1) { 9527 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9528 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9529 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9530 SDValue Src = LHS.getOperand(0); 9531 if (Src != RHS.getOperand(0)) 9532 return SDValue(); 9533 9534 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9535 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9536 if (!CLHS || !CRHS) 9537 return SDValue(); 9538 9539 // Only 10 bits are used. 9540 static const uint32_t MaxMask = 0x3ff; 9541 9542 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9543 SDLoc DL(N); 9544 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9545 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9546 } 9547 9548 return SDValue(); 9549 } 9550 9551 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9552 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9553 LHS.getOpcode() == AMDGPUISD::PERM && 9554 isa<ConstantSDNode>(LHS.getOperand(2))) { 9555 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9556 if (!Sel) 9557 return SDValue(); 9558 9559 Sel |= LHS.getConstantOperandVal(2); 9560 SDLoc DL(N); 9561 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9562 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9563 } 9564 9565 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9566 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9567 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9568 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9569 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9570 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9571 if (LHSMask != ~0u && RHSMask != ~0u) { 9572 // Canonicalize the expression in an attempt to have fewer unique masks 9573 // and therefore fewer registers used to hold the masks. 9574 if (LHSMask > RHSMask) { 9575 std::swap(LHSMask, RHSMask); 9576 std::swap(LHS, RHS); 9577 } 9578 9579 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9580 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9581 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9582 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9583 9584 // Check of we need to combine values from two sources within a byte. 9585 if (!(LHSUsedLanes & RHSUsedLanes) && 9586 // If we select high and lower word keep it for SDWA. 9587 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9588 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9589 // Kill zero bytes selected by other mask. Zero value is 0xc. 9590 LHSMask &= ~RHSUsedLanes; 9591 RHSMask &= ~LHSUsedLanes; 9592 // Add 4 to each active LHS lane 9593 LHSMask |= LHSUsedLanes & 0x04040404; 9594 // Combine masks 9595 uint32_t Sel = LHSMask | RHSMask; 9596 SDLoc DL(N); 9597 9598 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9599 LHS.getOperand(0), RHS.getOperand(0), 9600 DAG.getConstant(Sel, DL, MVT::i32)); 9601 } 9602 } 9603 } 9604 9605 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9606 return SDValue(); 9607 9608 // TODO: This could be a generic combine with a predicate for extracting the 9609 // high half of an integer being free. 9610 9611 // (or i64:x, (zero_extend i32:y)) -> 9612 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9613 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9614 RHS.getOpcode() != ISD::ZERO_EXTEND) 9615 std::swap(LHS, RHS); 9616 9617 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9618 SDValue ExtSrc = RHS.getOperand(0); 9619 EVT SrcVT = ExtSrc.getValueType(); 9620 if (SrcVT == MVT::i32) { 9621 SDLoc SL(N); 9622 SDValue LowLHS, HiBits; 9623 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9624 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9625 9626 DCI.AddToWorklist(LowOr.getNode()); 9627 DCI.AddToWorklist(HiBits.getNode()); 9628 9629 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9630 LowOr, HiBits); 9631 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9632 } 9633 } 9634 9635 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9636 if (CRHS) { 9637 if (SDValue Split 9638 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9639 N->getOperand(0), CRHS)) 9640 return Split; 9641 } 9642 9643 return SDValue(); 9644 } 9645 9646 SDValue SITargetLowering::performXorCombine(SDNode *N, 9647 DAGCombinerInfo &DCI) const { 9648 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9649 return RV; 9650 9651 EVT VT = N->getValueType(0); 9652 if (VT != MVT::i64) 9653 return SDValue(); 9654 9655 SDValue LHS = N->getOperand(0); 9656 SDValue RHS = N->getOperand(1); 9657 9658 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9659 if (CRHS) { 9660 if (SDValue Split 9661 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9662 return Split; 9663 } 9664 9665 return SDValue(); 9666 } 9667 9668 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9669 DAGCombinerInfo &DCI) const { 9670 if (!Subtarget->has16BitInsts() || 9671 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9672 return SDValue(); 9673 9674 EVT VT = N->getValueType(0); 9675 if (VT != MVT::i32) 9676 return SDValue(); 9677 9678 SDValue Src = N->getOperand(0); 9679 if (Src.getValueType() != MVT::i16) 9680 return SDValue(); 9681 9682 return SDValue(); 9683 } 9684 9685 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9686 DAGCombinerInfo &DCI) 9687 const { 9688 SDValue Src = N->getOperand(0); 9689 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9690 9691 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9692 VTSign->getVT() == MVT::i8) || 9693 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9694 VTSign->getVT() == MVT::i16)) && 9695 Src.hasOneUse()) { 9696 auto *M = cast<MemSDNode>(Src); 9697 SDValue Ops[] = { 9698 Src.getOperand(0), // Chain 9699 Src.getOperand(1), // rsrc 9700 Src.getOperand(2), // vindex 9701 Src.getOperand(3), // voffset 9702 Src.getOperand(4), // soffset 9703 Src.getOperand(5), // offset 9704 Src.getOperand(6), 9705 Src.getOperand(7) 9706 }; 9707 // replace with BUFFER_LOAD_BYTE/SHORT 9708 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9709 Src.getOperand(0).getValueType()); 9710 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9711 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9712 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9713 ResList, 9714 Ops, M->getMemoryVT(), 9715 M->getMemOperand()); 9716 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9717 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9718 } 9719 return SDValue(); 9720 } 9721 9722 SDValue SITargetLowering::performClassCombine(SDNode *N, 9723 DAGCombinerInfo &DCI) const { 9724 SelectionDAG &DAG = DCI.DAG; 9725 SDValue Mask = N->getOperand(1); 9726 9727 // fp_class x, 0 -> false 9728 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9729 if (CMask->isZero()) 9730 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9731 } 9732 9733 if (N->getOperand(0).isUndef()) 9734 return DAG.getUNDEF(MVT::i1); 9735 9736 return SDValue(); 9737 } 9738 9739 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9740 DAGCombinerInfo &DCI) const { 9741 EVT VT = N->getValueType(0); 9742 SDValue N0 = N->getOperand(0); 9743 9744 if (N0.isUndef()) 9745 return N0; 9746 9747 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9748 N0.getOpcode() == ISD::SINT_TO_FP)) { 9749 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9750 N->getFlags()); 9751 } 9752 9753 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9754 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9755 N0.getOperand(0), N->getFlags()); 9756 } 9757 9758 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9759 } 9760 9761 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9762 unsigned MaxDepth) const { 9763 unsigned Opcode = Op.getOpcode(); 9764 if (Opcode == ISD::FCANONICALIZE) 9765 return true; 9766 9767 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9768 auto F = CFP->getValueAPF(); 9769 if (F.isNaN() && F.isSignaling()) 9770 return false; 9771 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9772 } 9773 9774 // If source is a result of another standard FP operation it is already in 9775 // canonical form. 9776 if (MaxDepth == 0) 9777 return false; 9778 9779 switch (Opcode) { 9780 // These will flush denorms if required. 9781 case ISD::FADD: 9782 case ISD::FSUB: 9783 case ISD::FMUL: 9784 case ISD::FCEIL: 9785 case ISD::FFLOOR: 9786 case ISD::FMA: 9787 case ISD::FMAD: 9788 case ISD::FSQRT: 9789 case ISD::FDIV: 9790 case ISD::FREM: 9791 case ISD::FP_ROUND: 9792 case ISD::FP_EXTEND: 9793 case AMDGPUISD::FMUL_LEGACY: 9794 case AMDGPUISD::FMAD_FTZ: 9795 case AMDGPUISD::RCP: 9796 case AMDGPUISD::RSQ: 9797 case AMDGPUISD::RSQ_CLAMP: 9798 case AMDGPUISD::RCP_LEGACY: 9799 case AMDGPUISD::RCP_IFLAG: 9800 case AMDGPUISD::DIV_SCALE: 9801 case AMDGPUISD::DIV_FMAS: 9802 case AMDGPUISD::DIV_FIXUP: 9803 case AMDGPUISD::FRACT: 9804 case AMDGPUISD::LDEXP: 9805 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9806 case AMDGPUISD::CVT_F32_UBYTE0: 9807 case AMDGPUISD::CVT_F32_UBYTE1: 9808 case AMDGPUISD::CVT_F32_UBYTE2: 9809 case AMDGPUISD::CVT_F32_UBYTE3: 9810 return true; 9811 9812 // It can/will be lowered or combined as a bit operation. 9813 // Need to check their input recursively to handle. 9814 case ISD::FNEG: 9815 case ISD::FABS: 9816 case ISD::FCOPYSIGN: 9817 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9818 9819 case ISD::FSIN: 9820 case ISD::FCOS: 9821 case ISD::FSINCOS: 9822 return Op.getValueType().getScalarType() != MVT::f16; 9823 9824 case ISD::FMINNUM: 9825 case ISD::FMAXNUM: 9826 case ISD::FMINNUM_IEEE: 9827 case ISD::FMAXNUM_IEEE: 9828 case AMDGPUISD::CLAMP: 9829 case AMDGPUISD::FMED3: 9830 case AMDGPUISD::FMAX3: 9831 case AMDGPUISD::FMIN3: { 9832 // FIXME: Shouldn't treat the generic operations different based these. 9833 // However, we aren't really required to flush the result from 9834 // minnum/maxnum.. 9835 9836 // snans will be quieted, so we only need to worry about denormals. 9837 if (Subtarget->supportsMinMaxDenormModes() || 9838 denormalsEnabledForType(DAG, Op.getValueType())) 9839 return true; 9840 9841 // Flushing may be required. 9842 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9843 // targets need to check their input recursively. 9844 9845 // FIXME: Does this apply with clamp? It's implemented with max. 9846 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9847 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9848 return false; 9849 } 9850 9851 return true; 9852 } 9853 case ISD::SELECT: { 9854 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9855 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9856 } 9857 case ISD::BUILD_VECTOR: { 9858 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9859 SDValue SrcOp = Op.getOperand(i); 9860 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9861 return false; 9862 } 9863 9864 return true; 9865 } 9866 case ISD::EXTRACT_VECTOR_ELT: 9867 case ISD::EXTRACT_SUBVECTOR: { 9868 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9869 } 9870 case ISD::INSERT_VECTOR_ELT: { 9871 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9872 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9873 } 9874 case ISD::UNDEF: 9875 // Could be anything. 9876 return false; 9877 9878 case ISD::BITCAST: 9879 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9880 case ISD::TRUNCATE: { 9881 // Hack round the mess we make when legalizing extract_vector_elt 9882 if (Op.getValueType() == MVT::i16) { 9883 SDValue TruncSrc = Op.getOperand(0); 9884 if (TruncSrc.getValueType() == MVT::i32 && 9885 TruncSrc.getOpcode() == ISD::BITCAST && 9886 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9887 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9888 } 9889 } 9890 return false; 9891 } 9892 case ISD::INTRINSIC_WO_CHAIN: { 9893 unsigned IntrinsicID 9894 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9895 // TODO: Handle more intrinsics 9896 switch (IntrinsicID) { 9897 case Intrinsic::amdgcn_cvt_pkrtz: 9898 case Intrinsic::amdgcn_cubeid: 9899 case Intrinsic::amdgcn_frexp_mant: 9900 case Intrinsic::amdgcn_fdot2: 9901 case Intrinsic::amdgcn_rcp: 9902 case Intrinsic::amdgcn_rsq: 9903 case Intrinsic::amdgcn_rsq_clamp: 9904 case Intrinsic::amdgcn_rcp_legacy: 9905 case Intrinsic::amdgcn_rsq_legacy: 9906 case Intrinsic::amdgcn_trig_preop: 9907 return true; 9908 default: 9909 break; 9910 } 9911 9912 LLVM_FALLTHROUGH; 9913 } 9914 default: 9915 return denormalsEnabledForType(DAG, Op.getValueType()) && 9916 DAG.isKnownNeverSNaN(Op); 9917 } 9918 9919 llvm_unreachable("invalid operation"); 9920 } 9921 9922 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9923 unsigned MaxDepth) const { 9924 MachineRegisterInfo &MRI = MF.getRegInfo(); 9925 MachineInstr *MI = MRI.getVRegDef(Reg); 9926 unsigned Opcode = MI->getOpcode(); 9927 9928 if (Opcode == AMDGPU::G_FCANONICALIZE) 9929 return true; 9930 9931 Optional<FPValueAndVReg> FCR; 9932 // Constant splat (can be padded with undef) or scalar constant. 9933 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9934 if (FCR->Value.isSignaling()) 9935 return false; 9936 return !FCR->Value.isDenormal() || 9937 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9938 } 9939 9940 if (MaxDepth == 0) 9941 return false; 9942 9943 switch (Opcode) { 9944 case AMDGPU::G_FMINNUM_IEEE: 9945 case AMDGPU::G_FMAXNUM_IEEE: { 9946 if (Subtarget->supportsMinMaxDenormModes() || 9947 denormalsEnabledForType(MRI.getType(Reg), MF)) 9948 return true; 9949 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9950 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9951 return false; 9952 return true; 9953 } 9954 default: 9955 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9956 isKnownNeverSNaN(Reg, MRI); 9957 } 9958 9959 llvm_unreachable("invalid operation"); 9960 } 9961 9962 // Constant fold canonicalize. 9963 SDValue SITargetLowering::getCanonicalConstantFP( 9964 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9965 // Flush denormals to 0 if not enabled. 9966 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9967 return DAG.getConstantFP(0.0, SL, VT); 9968 9969 if (C.isNaN()) { 9970 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9971 if (C.isSignaling()) { 9972 // Quiet a signaling NaN. 9973 // FIXME: Is this supposed to preserve payload bits? 9974 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9975 } 9976 9977 // Make sure it is the canonical NaN bitpattern. 9978 // 9979 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9980 // immediate? 9981 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9982 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9983 } 9984 9985 // Already canonical. 9986 return DAG.getConstantFP(C, SL, VT); 9987 } 9988 9989 static bool vectorEltWillFoldAway(SDValue Op) { 9990 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9991 } 9992 9993 SDValue SITargetLowering::performFCanonicalizeCombine( 9994 SDNode *N, 9995 DAGCombinerInfo &DCI) const { 9996 SelectionDAG &DAG = DCI.DAG; 9997 SDValue N0 = N->getOperand(0); 9998 EVT VT = N->getValueType(0); 9999 10000 // fcanonicalize undef -> qnan 10001 if (N0.isUndef()) { 10002 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10003 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10004 } 10005 10006 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10007 EVT VT = N->getValueType(0); 10008 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10009 } 10010 10011 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10012 // (fcanonicalize k) 10013 // 10014 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10015 10016 // TODO: This could be better with wider vectors that will be split to v2f16, 10017 // and to consider uses since there aren't that many packed operations. 10018 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10019 isTypeLegal(MVT::v2f16)) { 10020 SDLoc SL(N); 10021 SDValue NewElts[2]; 10022 SDValue Lo = N0.getOperand(0); 10023 SDValue Hi = N0.getOperand(1); 10024 EVT EltVT = Lo.getValueType(); 10025 10026 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10027 for (unsigned I = 0; I != 2; ++I) { 10028 SDValue Op = N0.getOperand(I); 10029 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10030 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10031 CFP->getValueAPF()); 10032 } else if (Op.isUndef()) { 10033 // Handled below based on what the other operand is. 10034 NewElts[I] = Op; 10035 } else { 10036 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10037 } 10038 } 10039 10040 // If one half is undef, and one is constant, prefer a splat vector rather 10041 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10042 // cheaper to use and may be free with a packed operation. 10043 if (NewElts[0].isUndef()) { 10044 if (isa<ConstantFPSDNode>(NewElts[1])) 10045 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10046 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10047 } 10048 10049 if (NewElts[1].isUndef()) { 10050 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10051 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10052 } 10053 10054 return DAG.getBuildVector(VT, SL, NewElts); 10055 } 10056 } 10057 10058 unsigned SrcOpc = N0.getOpcode(); 10059 10060 // If it's free to do so, push canonicalizes further up the source, which may 10061 // find a canonical source. 10062 // 10063 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10064 // sNaNs. 10065 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10066 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10067 if (CRHS && N0.hasOneUse()) { 10068 SDLoc SL(N); 10069 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10070 N0.getOperand(0)); 10071 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10072 DCI.AddToWorklist(Canon0.getNode()); 10073 10074 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10075 } 10076 } 10077 10078 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10079 } 10080 10081 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10082 switch (Opc) { 10083 case ISD::FMAXNUM: 10084 case ISD::FMAXNUM_IEEE: 10085 return AMDGPUISD::FMAX3; 10086 case ISD::SMAX: 10087 return AMDGPUISD::SMAX3; 10088 case ISD::UMAX: 10089 return AMDGPUISD::UMAX3; 10090 case ISD::FMINNUM: 10091 case ISD::FMINNUM_IEEE: 10092 return AMDGPUISD::FMIN3; 10093 case ISD::SMIN: 10094 return AMDGPUISD::SMIN3; 10095 case ISD::UMIN: 10096 return AMDGPUISD::UMIN3; 10097 default: 10098 llvm_unreachable("Not a min/max opcode"); 10099 } 10100 } 10101 10102 SDValue SITargetLowering::performIntMed3ImmCombine( 10103 SelectionDAG &DAG, const SDLoc &SL, 10104 SDValue Op0, SDValue Op1, bool Signed) const { 10105 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10106 if (!K1) 10107 return SDValue(); 10108 10109 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10110 if (!K0) 10111 return SDValue(); 10112 10113 if (Signed) { 10114 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10115 return SDValue(); 10116 } else { 10117 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10118 return SDValue(); 10119 } 10120 10121 EVT VT = K0->getValueType(0); 10122 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10123 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10124 return DAG.getNode(Med3Opc, SL, VT, 10125 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10126 } 10127 10128 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10129 if (VT == MVT::i16) { 10130 MVT NVT = MVT::i32; 10131 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10132 10133 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10134 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10135 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10136 10137 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10138 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10139 } 10140 10141 return SDValue(); 10142 } 10143 10144 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10145 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10146 return C; 10147 10148 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10149 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10150 return C; 10151 } 10152 10153 return nullptr; 10154 } 10155 10156 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10157 const SDLoc &SL, 10158 SDValue Op0, 10159 SDValue Op1) const { 10160 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10161 if (!K1) 10162 return SDValue(); 10163 10164 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10165 if (!K0) 10166 return SDValue(); 10167 10168 // Ordered >= (although NaN inputs should have folded away by now). 10169 if (K0->getValueAPF() > K1->getValueAPF()) 10170 return SDValue(); 10171 10172 const MachineFunction &MF = DAG.getMachineFunction(); 10173 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10174 10175 // TODO: Check IEEE bit enabled? 10176 EVT VT = Op0.getValueType(); 10177 if (Info->getMode().DX10Clamp) { 10178 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10179 // hardware fmed3 behavior converting to a min. 10180 // FIXME: Should this be allowing -0.0? 10181 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10182 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10183 } 10184 10185 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10186 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10187 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10188 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10189 // then give the other result, which is different from med3 with a NaN 10190 // input. 10191 SDValue Var = Op0.getOperand(0); 10192 if (!DAG.isKnownNeverSNaN(Var)) 10193 return SDValue(); 10194 10195 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10196 10197 if ((!K0->hasOneUse() || 10198 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10199 (!K1->hasOneUse() || 10200 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10201 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10202 Var, SDValue(K0, 0), SDValue(K1, 0)); 10203 } 10204 } 10205 10206 return SDValue(); 10207 } 10208 10209 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10210 DAGCombinerInfo &DCI) const { 10211 SelectionDAG &DAG = DCI.DAG; 10212 10213 EVT VT = N->getValueType(0); 10214 unsigned Opc = N->getOpcode(); 10215 SDValue Op0 = N->getOperand(0); 10216 SDValue Op1 = N->getOperand(1); 10217 10218 // Only do this if the inner op has one use since this will just increases 10219 // register pressure for no benefit. 10220 10221 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10222 !VT.isVector() && 10223 (VT == MVT::i32 || VT == MVT::f32 || 10224 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10225 // max(max(a, b), c) -> max3(a, b, c) 10226 // min(min(a, b), c) -> min3(a, b, c) 10227 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10228 SDLoc DL(N); 10229 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10230 DL, 10231 N->getValueType(0), 10232 Op0.getOperand(0), 10233 Op0.getOperand(1), 10234 Op1); 10235 } 10236 10237 // Try commuted. 10238 // max(a, max(b, c)) -> max3(a, b, c) 10239 // min(a, min(b, c)) -> min3(a, b, c) 10240 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10241 SDLoc DL(N); 10242 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10243 DL, 10244 N->getValueType(0), 10245 Op0, 10246 Op1.getOperand(0), 10247 Op1.getOperand(1)); 10248 } 10249 } 10250 10251 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10252 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10253 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10254 return Med3; 10255 } 10256 10257 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10258 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10259 return Med3; 10260 } 10261 10262 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10263 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10264 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10265 (Opc == AMDGPUISD::FMIN_LEGACY && 10266 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10267 (VT == MVT::f32 || VT == MVT::f64 || 10268 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10269 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10270 Op0.hasOneUse()) { 10271 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10272 return Res; 10273 } 10274 10275 return SDValue(); 10276 } 10277 10278 static bool isClampZeroToOne(SDValue A, SDValue B) { 10279 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10280 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10281 // FIXME: Should this be allowing -0.0? 10282 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10283 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10284 } 10285 } 10286 10287 return false; 10288 } 10289 10290 // FIXME: Should only worry about snans for version with chain. 10291 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10292 DAGCombinerInfo &DCI) const { 10293 EVT VT = N->getValueType(0); 10294 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10295 // NaNs. With a NaN input, the order of the operands may change the result. 10296 10297 SelectionDAG &DAG = DCI.DAG; 10298 SDLoc SL(N); 10299 10300 SDValue Src0 = N->getOperand(0); 10301 SDValue Src1 = N->getOperand(1); 10302 SDValue Src2 = N->getOperand(2); 10303 10304 if (isClampZeroToOne(Src0, Src1)) { 10305 // const_a, const_b, x -> clamp is safe in all cases including signaling 10306 // nans. 10307 // FIXME: Should this be allowing -0.0? 10308 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10309 } 10310 10311 const MachineFunction &MF = DAG.getMachineFunction(); 10312 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10313 10314 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10315 // handling no dx10-clamp? 10316 if (Info->getMode().DX10Clamp) { 10317 // If NaNs is clamped to 0, we are free to reorder the inputs. 10318 10319 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10320 std::swap(Src0, Src1); 10321 10322 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10323 std::swap(Src1, Src2); 10324 10325 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10326 std::swap(Src0, Src1); 10327 10328 if (isClampZeroToOne(Src1, Src2)) 10329 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10330 } 10331 10332 return SDValue(); 10333 } 10334 10335 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10336 DAGCombinerInfo &DCI) const { 10337 SDValue Src0 = N->getOperand(0); 10338 SDValue Src1 = N->getOperand(1); 10339 if (Src0.isUndef() && Src1.isUndef()) 10340 return DCI.DAG.getUNDEF(N->getValueType(0)); 10341 return SDValue(); 10342 } 10343 10344 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10345 // expanded into a set of cmp/select instructions. 10346 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10347 unsigned NumElem, 10348 bool IsDivergentIdx) { 10349 if (UseDivergentRegisterIndexing) 10350 return false; 10351 10352 unsigned VecSize = EltSize * NumElem; 10353 10354 // Sub-dword vectors of size 2 dword or less have better implementation. 10355 if (VecSize <= 64 && EltSize < 32) 10356 return false; 10357 10358 // Always expand the rest of sub-dword instructions, otherwise it will be 10359 // lowered via memory. 10360 if (EltSize < 32) 10361 return true; 10362 10363 // Always do this if var-idx is divergent, otherwise it will become a loop. 10364 if (IsDivergentIdx) 10365 return true; 10366 10367 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10368 unsigned NumInsts = NumElem /* Number of compares */ + 10369 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10370 return NumInsts <= 16; 10371 } 10372 10373 static bool shouldExpandVectorDynExt(SDNode *N) { 10374 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10375 if (isa<ConstantSDNode>(Idx)) 10376 return false; 10377 10378 SDValue Vec = N->getOperand(0); 10379 EVT VecVT = Vec.getValueType(); 10380 EVT EltVT = VecVT.getVectorElementType(); 10381 unsigned EltSize = EltVT.getSizeInBits(); 10382 unsigned NumElem = VecVT.getVectorNumElements(); 10383 10384 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10385 Idx->isDivergent()); 10386 } 10387 10388 SDValue SITargetLowering::performExtractVectorEltCombine( 10389 SDNode *N, DAGCombinerInfo &DCI) const { 10390 SDValue Vec = N->getOperand(0); 10391 SelectionDAG &DAG = DCI.DAG; 10392 10393 EVT VecVT = Vec.getValueType(); 10394 EVT EltVT = VecVT.getVectorElementType(); 10395 10396 if ((Vec.getOpcode() == ISD::FNEG || 10397 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10398 SDLoc SL(N); 10399 EVT EltVT = N->getValueType(0); 10400 SDValue Idx = N->getOperand(1); 10401 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10402 Vec.getOperand(0), Idx); 10403 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10404 } 10405 10406 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10407 // => 10408 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10409 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10410 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10411 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10412 SDLoc SL(N); 10413 EVT EltVT = N->getValueType(0); 10414 SDValue Idx = N->getOperand(1); 10415 unsigned Opc = Vec.getOpcode(); 10416 10417 switch(Opc) { 10418 default: 10419 break; 10420 // TODO: Support other binary operations. 10421 case ISD::FADD: 10422 case ISD::FSUB: 10423 case ISD::FMUL: 10424 case ISD::ADD: 10425 case ISD::UMIN: 10426 case ISD::UMAX: 10427 case ISD::SMIN: 10428 case ISD::SMAX: 10429 case ISD::FMAXNUM: 10430 case ISD::FMINNUM: 10431 case ISD::FMAXNUM_IEEE: 10432 case ISD::FMINNUM_IEEE: { 10433 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10434 Vec.getOperand(0), Idx); 10435 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10436 Vec.getOperand(1), Idx); 10437 10438 DCI.AddToWorklist(Elt0.getNode()); 10439 DCI.AddToWorklist(Elt1.getNode()); 10440 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10441 } 10442 } 10443 } 10444 10445 unsigned VecSize = VecVT.getSizeInBits(); 10446 unsigned EltSize = EltVT.getSizeInBits(); 10447 10448 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10449 if (::shouldExpandVectorDynExt(N)) { 10450 SDLoc SL(N); 10451 SDValue Idx = N->getOperand(1); 10452 SDValue V; 10453 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10454 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10455 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10456 if (I == 0) 10457 V = Elt; 10458 else 10459 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10460 } 10461 return V; 10462 } 10463 10464 if (!DCI.isBeforeLegalize()) 10465 return SDValue(); 10466 10467 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10468 // elements. This exposes more load reduction opportunities by replacing 10469 // multiple small extract_vector_elements with a single 32-bit extract. 10470 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10471 if (isa<MemSDNode>(Vec) && 10472 EltSize <= 16 && 10473 EltVT.isByteSized() && 10474 VecSize > 32 && 10475 VecSize % 32 == 0 && 10476 Idx) { 10477 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10478 10479 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10480 unsigned EltIdx = BitIndex / 32; 10481 unsigned LeftoverBitIdx = BitIndex % 32; 10482 SDLoc SL(N); 10483 10484 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10485 DCI.AddToWorklist(Cast.getNode()); 10486 10487 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10488 DAG.getConstant(EltIdx, SL, MVT::i32)); 10489 DCI.AddToWorklist(Elt.getNode()); 10490 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10491 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10492 DCI.AddToWorklist(Srl.getNode()); 10493 10494 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10495 DCI.AddToWorklist(Trunc.getNode()); 10496 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10497 } 10498 10499 return SDValue(); 10500 } 10501 10502 SDValue 10503 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10504 DAGCombinerInfo &DCI) const { 10505 SDValue Vec = N->getOperand(0); 10506 SDValue Idx = N->getOperand(2); 10507 EVT VecVT = Vec.getValueType(); 10508 EVT EltVT = VecVT.getVectorElementType(); 10509 10510 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10511 // => BUILD_VECTOR n x select (e, const-idx) 10512 if (!::shouldExpandVectorDynExt(N)) 10513 return SDValue(); 10514 10515 SelectionDAG &DAG = DCI.DAG; 10516 SDLoc SL(N); 10517 SDValue Ins = N->getOperand(1); 10518 EVT IdxVT = Idx.getValueType(); 10519 10520 SmallVector<SDValue, 16> Ops; 10521 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10522 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10523 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10524 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10525 Ops.push_back(V); 10526 } 10527 10528 return DAG.getBuildVector(VecVT, SL, Ops); 10529 } 10530 10531 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10532 const SDNode *N0, 10533 const SDNode *N1) const { 10534 EVT VT = N0->getValueType(0); 10535 10536 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10537 // support denormals ever. 10538 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10539 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10540 getSubtarget()->hasMadF16())) && 10541 isOperationLegal(ISD::FMAD, VT)) 10542 return ISD::FMAD; 10543 10544 const TargetOptions &Options = DAG.getTarget().Options; 10545 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10546 (N0->getFlags().hasAllowContract() && 10547 N1->getFlags().hasAllowContract())) && 10548 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10549 return ISD::FMA; 10550 } 10551 10552 return 0; 10553 } 10554 10555 // For a reassociatable opcode perform: 10556 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10557 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10558 SelectionDAG &DAG) const { 10559 EVT VT = N->getValueType(0); 10560 if (VT != MVT::i32 && VT != MVT::i64) 10561 return SDValue(); 10562 10563 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10564 return SDValue(); 10565 10566 unsigned Opc = N->getOpcode(); 10567 SDValue Op0 = N->getOperand(0); 10568 SDValue Op1 = N->getOperand(1); 10569 10570 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10571 return SDValue(); 10572 10573 if (Op0->isDivergent()) 10574 std::swap(Op0, Op1); 10575 10576 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10577 return SDValue(); 10578 10579 SDValue Op2 = Op1.getOperand(1); 10580 Op1 = Op1.getOperand(0); 10581 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10582 return SDValue(); 10583 10584 if (Op1->isDivergent()) 10585 std::swap(Op1, Op2); 10586 10587 SDLoc SL(N); 10588 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10589 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10590 } 10591 10592 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10593 EVT VT, 10594 SDValue N0, SDValue N1, SDValue N2, 10595 bool Signed) { 10596 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10597 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10598 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10599 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10600 } 10601 10602 SDValue SITargetLowering::performAddCombine(SDNode *N, 10603 DAGCombinerInfo &DCI) const { 10604 SelectionDAG &DAG = DCI.DAG; 10605 EVT VT = N->getValueType(0); 10606 SDLoc SL(N); 10607 SDValue LHS = N->getOperand(0); 10608 SDValue RHS = N->getOperand(1); 10609 10610 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10611 && Subtarget->hasMad64_32() && 10612 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10613 VT.getScalarSizeInBits() <= 64) { 10614 if (LHS.getOpcode() != ISD::MUL) 10615 std::swap(LHS, RHS); 10616 10617 SDValue MulLHS = LHS.getOperand(0); 10618 SDValue MulRHS = LHS.getOperand(1); 10619 SDValue AddRHS = RHS; 10620 10621 // TODO: Maybe restrict if SGPR inputs. 10622 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10623 numBitsUnsigned(MulRHS, DAG) <= 32) { 10624 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10625 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10626 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10627 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10628 } 10629 10630 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10631 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10632 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10633 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10634 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10635 } 10636 10637 return SDValue(); 10638 } 10639 10640 if (SDValue V = reassociateScalarOps(N, DAG)) { 10641 return V; 10642 } 10643 10644 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10645 return SDValue(); 10646 10647 // add x, zext (setcc) => addcarry x, 0, setcc 10648 // add x, sext (setcc) => subcarry x, 0, setcc 10649 unsigned Opc = LHS.getOpcode(); 10650 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10651 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10652 std::swap(RHS, LHS); 10653 10654 Opc = RHS.getOpcode(); 10655 switch (Opc) { 10656 default: break; 10657 case ISD::ZERO_EXTEND: 10658 case ISD::SIGN_EXTEND: 10659 case ISD::ANY_EXTEND: { 10660 auto Cond = RHS.getOperand(0); 10661 // If this won't be a real VOPC output, we would still need to insert an 10662 // extra instruction anyway. 10663 if (!isBoolSGPR(Cond)) 10664 break; 10665 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10666 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10667 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10668 return DAG.getNode(Opc, SL, VTList, Args); 10669 } 10670 case ISD::ADDCARRY: { 10671 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10672 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10673 if (!C || C->getZExtValue() != 0) break; 10674 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10675 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10676 } 10677 } 10678 return SDValue(); 10679 } 10680 10681 SDValue SITargetLowering::performSubCombine(SDNode *N, 10682 DAGCombinerInfo &DCI) const { 10683 SelectionDAG &DAG = DCI.DAG; 10684 EVT VT = N->getValueType(0); 10685 10686 if (VT != MVT::i32) 10687 return SDValue(); 10688 10689 SDLoc SL(N); 10690 SDValue LHS = N->getOperand(0); 10691 SDValue RHS = N->getOperand(1); 10692 10693 // sub x, zext (setcc) => subcarry x, 0, setcc 10694 // sub x, sext (setcc) => addcarry x, 0, setcc 10695 unsigned Opc = RHS.getOpcode(); 10696 switch (Opc) { 10697 default: break; 10698 case ISD::ZERO_EXTEND: 10699 case ISD::SIGN_EXTEND: 10700 case ISD::ANY_EXTEND: { 10701 auto Cond = RHS.getOperand(0); 10702 // If this won't be a real VOPC output, we would still need to insert an 10703 // extra instruction anyway. 10704 if (!isBoolSGPR(Cond)) 10705 break; 10706 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10707 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10708 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10709 return DAG.getNode(Opc, SL, VTList, Args); 10710 } 10711 } 10712 10713 if (LHS.getOpcode() == ISD::SUBCARRY) { 10714 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10715 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10716 if (!C || !C->isZero()) 10717 return SDValue(); 10718 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10719 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10720 } 10721 return SDValue(); 10722 } 10723 10724 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10725 DAGCombinerInfo &DCI) const { 10726 10727 if (N->getValueType(0) != MVT::i32) 10728 return SDValue(); 10729 10730 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10731 if (!C || C->getZExtValue() != 0) 10732 return SDValue(); 10733 10734 SelectionDAG &DAG = DCI.DAG; 10735 SDValue LHS = N->getOperand(0); 10736 10737 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10738 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10739 unsigned LHSOpc = LHS.getOpcode(); 10740 unsigned Opc = N->getOpcode(); 10741 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10742 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10743 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10744 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10745 } 10746 return SDValue(); 10747 } 10748 10749 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10750 DAGCombinerInfo &DCI) const { 10751 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10752 return SDValue(); 10753 10754 SelectionDAG &DAG = DCI.DAG; 10755 EVT VT = N->getValueType(0); 10756 10757 SDLoc SL(N); 10758 SDValue LHS = N->getOperand(0); 10759 SDValue RHS = N->getOperand(1); 10760 10761 // These should really be instruction patterns, but writing patterns with 10762 // source modifiers is a pain. 10763 10764 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10765 if (LHS.getOpcode() == ISD::FADD) { 10766 SDValue A = LHS.getOperand(0); 10767 if (A == LHS.getOperand(1)) { 10768 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10769 if (FusedOp != 0) { 10770 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10771 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10772 } 10773 } 10774 } 10775 10776 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10777 if (RHS.getOpcode() == ISD::FADD) { 10778 SDValue A = RHS.getOperand(0); 10779 if (A == RHS.getOperand(1)) { 10780 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10781 if (FusedOp != 0) { 10782 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10783 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10784 } 10785 } 10786 } 10787 10788 return SDValue(); 10789 } 10790 10791 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10792 DAGCombinerInfo &DCI) const { 10793 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10794 return SDValue(); 10795 10796 SelectionDAG &DAG = DCI.DAG; 10797 SDLoc SL(N); 10798 EVT VT = N->getValueType(0); 10799 assert(!VT.isVector()); 10800 10801 // Try to get the fneg to fold into the source modifier. This undoes generic 10802 // DAG combines and folds them into the mad. 10803 // 10804 // Only do this if we are not trying to support denormals. v_mad_f32 does 10805 // not support denormals ever. 10806 SDValue LHS = N->getOperand(0); 10807 SDValue RHS = N->getOperand(1); 10808 if (LHS.getOpcode() == ISD::FADD) { 10809 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10810 SDValue A = LHS.getOperand(0); 10811 if (A == LHS.getOperand(1)) { 10812 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10813 if (FusedOp != 0){ 10814 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10815 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10816 10817 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10818 } 10819 } 10820 } 10821 10822 if (RHS.getOpcode() == ISD::FADD) { 10823 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10824 10825 SDValue A = RHS.getOperand(0); 10826 if (A == RHS.getOperand(1)) { 10827 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10828 if (FusedOp != 0){ 10829 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10830 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10831 } 10832 } 10833 } 10834 10835 return SDValue(); 10836 } 10837 10838 SDValue SITargetLowering::performFMACombine(SDNode *N, 10839 DAGCombinerInfo &DCI) const { 10840 SelectionDAG &DAG = DCI.DAG; 10841 EVT VT = N->getValueType(0); 10842 SDLoc SL(N); 10843 10844 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10845 return SDValue(); 10846 10847 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10848 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10849 SDValue Op1 = N->getOperand(0); 10850 SDValue Op2 = N->getOperand(1); 10851 SDValue FMA = N->getOperand(2); 10852 10853 if (FMA.getOpcode() != ISD::FMA || 10854 Op1.getOpcode() != ISD::FP_EXTEND || 10855 Op2.getOpcode() != ISD::FP_EXTEND) 10856 return SDValue(); 10857 10858 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10859 // regardless of the denorm mode setting. Therefore, 10860 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 10861 const TargetOptions &Options = DAG.getTarget().Options; 10862 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10863 (N->getFlags().hasAllowContract() && 10864 FMA->getFlags().hasAllowContract())) { 10865 Op1 = Op1.getOperand(0); 10866 Op2 = Op2.getOperand(0); 10867 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10868 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10869 return SDValue(); 10870 10871 SDValue Vec1 = Op1.getOperand(0); 10872 SDValue Idx1 = Op1.getOperand(1); 10873 SDValue Vec2 = Op2.getOperand(0); 10874 10875 SDValue FMAOp1 = FMA.getOperand(0); 10876 SDValue FMAOp2 = FMA.getOperand(1); 10877 SDValue FMAAcc = FMA.getOperand(2); 10878 10879 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10880 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10881 return SDValue(); 10882 10883 FMAOp1 = FMAOp1.getOperand(0); 10884 FMAOp2 = FMAOp2.getOperand(0); 10885 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10886 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10887 return SDValue(); 10888 10889 SDValue Vec3 = FMAOp1.getOperand(0); 10890 SDValue Vec4 = FMAOp2.getOperand(0); 10891 SDValue Idx2 = FMAOp1.getOperand(1); 10892 10893 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10894 // Idx1 and Idx2 cannot be the same. 10895 Idx1 == Idx2) 10896 return SDValue(); 10897 10898 if (Vec1 == Vec2 || Vec3 == Vec4) 10899 return SDValue(); 10900 10901 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10902 return SDValue(); 10903 10904 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10905 (Vec1 == Vec4 && Vec2 == Vec3)) { 10906 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10907 DAG.getTargetConstant(0, SL, MVT::i1)); 10908 } 10909 } 10910 return SDValue(); 10911 } 10912 10913 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10914 DAGCombinerInfo &DCI) const { 10915 SelectionDAG &DAG = DCI.DAG; 10916 SDLoc SL(N); 10917 10918 SDValue LHS = N->getOperand(0); 10919 SDValue RHS = N->getOperand(1); 10920 EVT VT = LHS.getValueType(); 10921 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10922 10923 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10924 if (!CRHS) { 10925 CRHS = dyn_cast<ConstantSDNode>(LHS); 10926 if (CRHS) { 10927 std::swap(LHS, RHS); 10928 CC = getSetCCSwappedOperands(CC); 10929 } 10930 } 10931 10932 if (CRHS) { 10933 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10934 isBoolSGPR(LHS.getOperand(0))) { 10935 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10936 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10937 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10938 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10939 if ((CRHS->isAllOnes() && 10940 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10941 (CRHS->isZero() && 10942 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10943 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10944 DAG.getConstant(-1, SL, MVT::i1)); 10945 if ((CRHS->isAllOnes() && 10946 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10947 (CRHS->isZero() && 10948 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10949 return LHS.getOperand(0); 10950 } 10951 10952 const APInt &CRHSVal = CRHS->getAPIntValue(); 10953 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10954 LHS.getOpcode() == ISD::SELECT && 10955 isa<ConstantSDNode>(LHS.getOperand(1)) && 10956 isa<ConstantSDNode>(LHS.getOperand(2)) && 10957 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10958 isBoolSGPR(LHS.getOperand(0))) { 10959 // Given CT != FT: 10960 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10961 // setcc (select cc, CT, CF), CF, ne => cc 10962 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10963 // setcc (select cc, CT, CF), CT, eq => cc 10964 const APInt &CT = LHS.getConstantOperandAPInt(1); 10965 const APInt &CF = LHS.getConstantOperandAPInt(2); 10966 10967 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10968 (CT == CRHSVal && CC == ISD::SETNE)) 10969 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10970 DAG.getConstant(-1, SL, MVT::i1)); 10971 if ((CF == CRHSVal && CC == ISD::SETNE) || 10972 (CT == CRHSVal && CC == ISD::SETEQ)) 10973 return LHS.getOperand(0); 10974 } 10975 } 10976 10977 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10978 VT != MVT::f16)) 10979 return SDValue(); 10980 10981 // Match isinf/isfinite pattern 10982 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10983 // (fcmp one (fabs x), inf) -> (fp_class x, 10984 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10985 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10986 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10987 if (!CRHS) 10988 return SDValue(); 10989 10990 const APFloat &APF = CRHS->getValueAPF(); 10991 if (APF.isInfinity() && !APF.isNegative()) { 10992 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10993 SIInstrFlags::N_INFINITY; 10994 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10995 SIInstrFlags::P_ZERO | 10996 SIInstrFlags::N_NORMAL | 10997 SIInstrFlags::P_NORMAL | 10998 SIInstrFlags::N_SUBNORMAL | 10999 SIInstrFlags::P_SUBNORMAL; 11000 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11001 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11002 DAG.getConstant(Mask, SL, MVT::i32)); 11003 } 11004 } 11005 11006 return SDValue(); 11007 } 11008 11009 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11010 DAGCombinerInfo &DCI) const { 11011 SelectionDAG &DAG = DCI.DAG; 11012 SDLoc SL(N); 11013 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11014 11015 SDValue Src = N->getOperand(0); 11016 SDValue Shift = N->getOperand(0); 11017 11018 // TODO: Extend type shouldn't matter (assuming legal types). 11019 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11020 Shift = Shift.getOperand(0); 11021 11022 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11023 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11024 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11025 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11026 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11027 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11028 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11029 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11030 SDLoc(Shift.getOperand(0)), MVT::i32); 11031 11032 unsigned ShiftOffset = 8 * Offset; 11033 if (Shift.getOpcode() == ISD::SHL) 11034 ShiftOffset -= C->getZExtValue(); 11035 else 11036 ShiftOffset += C->getZExtValue(); 11037 11038 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11039 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11040 MVT::f32, Shifted); 11041 } 11042 } 11043 } 11044 11045 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11046 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11047 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11048 // We simplified Src. If this node is not dead, visit it again so it is 11049 // folded properly. 11050 if (N->getOpcode() != ISD::DELETED_NODE) 11051 DCI.AddToWorklist(N); 11052 return SDValue(N, 0); 11053 } 11054 11055 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11056 if (SDValue DemandedSrc = 11057 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11058 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11059 11060 return SDValue(); 11061 } 11062 11063 SDValue SITargetLowering::performClampCombine(SDNode *N, 11064 DAGCombinerInfo &DCI) const { 11065 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11066 if (!CSrc) 11067 return SDValue(); 11068 11069 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11070 const APFloat &F = CSrc->getValueAPF(); 11071 APFloat Zero = APFloat::getZero(F.getSemantics()); 11072 if (F < Zero || 11073 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11074 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11075 } 11076 11077 APFloat One(F.getSemantics(), "1.0"); 11078 if (F > One) 11079 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11080 11081 return SDValue(CSrc, 0); 11082 } 11083 11084 11085 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11086 DAGCombinerInfo &DCI) const { 11087 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11088 return SDValue(); 11089 switch (N->getOpcode()) { 11090 case ISD::ADD: 11091 return performAddCombine(N, DCI); 11092 case ISD::SUB: 11093 return performSubCombine(N, DCI); 11094 case ISD::ADDCARRY: 11095 case ISD::SUBCARRY: 11096 return performAddCarrySubCarryCombine(N, DCI); 11097 case ISD::FADD: 11098 return performFAddCombine(N, DCI); 11099 case ISD::FSUB: 11100 return performFSubCombine(N, DCI); 11101 case ISD::SETCC: 11102 return performSetCCCombine(N, DCI); 11103 case ISD::FMAXNUM: 11104 case ISD::FMINNUM: 11105 case ISD::FMAXNUM_IEEE: 11106 case ISD::FMINNUM_IEEE: 11107 case ISD::SMAX: 11108 case ISD::SMIN: 11109 case ISD::UMAX: 11110 case ISD::UMIN: 11111 case AMDGPUISD::FMIN_LEGACY: 11112 case AMDGPUISD::FMAX_LEGACY: 11113 return performMinMaxCombine(N, DCI); 11114 case ISD::FMA: 11115 return performFMACombine(N, DCI); 11116 case ISD::AND: 11117 return performAndCombine(N, DCI); 11118 case ISD::OR: 11119 return performOrCombine(N, DCI); 11120 case ISD::XOR: 11121 return performXorCombine(N, DCI); 11122 case ISD::ZERO_EXTEND: 11123 return performZeroExtendCombine(N, DCI); 11124 case ISD::SIGN_EXTEND_INREG: 11125 return performSignExtendInRegCombine(N , DCI); 11126 case AMDGPUISD::FP_CLASS: 11127 return performClassCombine(N, DCI); 11128 case ISD::FCANONICALIZE: 11129 return performFCanonicalizeCombine(N, DCI); 11130 case AMDGPUISD::RCP: 11131 return performRcpCombine(N, DCI); 11132 case AMDGPUISD::FRACT: 11133 case AMDGPUISD::RSQ: 11134 case AMDGPUISD::RCP_LEGACY: 11135 case AMDGPUISD::RCP_IFLAG: 11136 case AMDGPUISD::RSQ_CLAMP: 11137 case AMDGPUISD::LDEXP: { 11138 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11139 SDValue Src = N->getOperand(0); 11140 if (Src.isUndef()) 11141 return Src; 11142 break; 11143 } 11144 case ISD::SINT_TO_FP: 11145 case ISD::UINT_TO_FP: 11146 return performUCharToFloatCombine(N, DCI); 11147 case AMDGPUISD::CVT_F32_UBYTE0: 11148 case AMDGPUISD::CVT_F32_UBYTE1: 11149 case AMDGPUISD::CVT_F32_UBYTE2: 11150 case AMDGPUISD::CVT_F32_UBYTE3: 11151 return performCvtF32UByteNCombine(N, DCI); 11152 case AMDGPUISD::FMED3: 11153 return performFMed3Combine(N, DCI); 11154 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11155 return performCvtPkRTZCombine(N, DCI); 11156 case AMDGPUISD::CLAMP: 11157 return performClampCombine(N, DCI); 11158 case ISD::SCALAR_TO_VECTOR: { 11159 SelectionDAG &DAG = DCI.DAG; 11160 EVT VT = N->getValueType(0); 11161 11162 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11163 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11164 SDLoc SL(N); 11165 SDValue Src = N->getOperand(0); 11166 EVT EltVT = Src.getValueType(); 11167 if (EltVT == MVT::f16) 11168 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11169 11170 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11171 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11172 } 11173 11174 break; 11175 } 11176 case ISD::EXTRACT_VECTOR_ELT: 11177 return performExtractVectorEltCombine(N, DCI); 11178 case ISD::INSERT_VECTOR_ELT: 11179 return performInsertVectorEltCombine(N, DCI); 11180 case ISD::LOAD: { 11181 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11182 return Widended; 11183 LLVM_FALLTHROUGH; 11184 } 11185 default: { 11186 if (!DCI.isBeforeLegalize()) { 11187 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11188 return performMemSDNodeCombine(MemNode, DCI); 11189 } 11190 11191 break; 11192 } 11193 } 11194 11195 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11196 } 11197 11198 /// Helper function for adjustWritemask 11199 static unsigned SubIdx2Lane(unsigned Idx) { 11200 switch (Idx) { 11201 default: return ~0u; 11202 case AMDGPU::sub0: return 0; 11203 case AMDGPU::sub1: return 1; 11204 case AMDGPU::sub2: return 2; 11205 case AMDGPU::sub3: return 3; 11206 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11207 } 11208 } 11209 11210 /// Adjust the writemask of MIMG instructions 11211 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11212 SelectionDAG &DAG) const { 11213 unsigned Opcode = Node->getMachineOpcode(); 11214 11215 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11216 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11217 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11218 return Node; // not implemented for D16 11219 11220 SDNode *Users[5] = { nullptr }; 11221 unsigned Lane = 0; 11222 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11223 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11224 unsigned NewDmask = 0; 11225 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11226 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11227 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11228 Node->getConstantOperandVal(LWEIdx)) 11229 ? true 11230 : false; 11231 unsigned TFCLane = 0; 11232 bool HasChain = Node->getNumValues() > 1; 11233 11234 if (OldDmask == 0) { 11235 // These are folded out, but on the chance it happens don't assert. 11236 return Node; 11237 } 11238 11239 unsigned OldBitsSet = countPopulation(OldDmask); 11240 // Work out which is the TFE/LWE lane if that is enabled. 11241 if (UsesTFC) { 11242 TFCLane = OldBitsSet; 11243 } 11244 11245 // Try to figure out the used register components 11246 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11247 I != E; ++I) { 11248 11249 // Don't look at users of the chain. 11250 if (I.getUse().getResNo() != 0) 11251 continue; 11252 11253 // Abort if we can't understand the usage 11254 if (!I->isMachineOpcode() || 11255 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11256 return Node; 11257 11258 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11259 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11260 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11261 // set, etc. 11262 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11263 if (Lane == ~0u) 11264 return Node; 11265 11266 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11267 if (UsesTFC && Lane == TFCLane) { 11268 Users[Lane] = *I; 11269 } else { 11270 // Set which texture component corresponds to the lane. 11271 unsigned Comp; 11272 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11273 Comp = countTrailingZeros(Dmask); 11274 Dmask &= ~(1 << Comp); 11275 } 11276 11277 // Abort if we have more than one user per component. 11278 if (Users[Lane]) 11279 return Node; 11280 11281 Users[Lane] = *I; 11282 NewDmask |= 1 << Comp; 11283 } 11284 } 11285 11286 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11287 bool NoChannels = !NewDmask; 11288 if (NoChannels) { 11289 if (!UsesTFC) { 11290 // No uses of the result and not using TFC. Then do nothing. 11291 return Node; 11292 } 11293 // If the original dmask has one channel - then nothing to do 11294 if (OldBitsSet == 1) 11295 return Node; 11296 // Use an arbitrary dmask - required for the instruction to work 11297 NewDmask = 1; 11298 } 11299 // Abort if there's no change 11300 if (NewDmask == OldDmask) 11301 return Node; 11302 11303 unsigned BitsSet = countPopulation(NewDmask); 11304 11305 // Check for TFE or LWE - increase the number of channels by one to account 11306 // for the extra return value 11307 // This will need adjustment for D16 if this is also included in 11308 // adjustWriteMask (this function) but at present D16 are excluded. 11309 unsigned NewChannels = BitsSet + UsesTFC; 11310 11311 int NewOpcode = 11312 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11313 assert(NewOpcode != -1 && 11314 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11315 "failed to find equivalent MIMG op"); 11316 11317 // Adjust the writemask in the node 11318 SmallVector<SDValue, 12> Ops; 11319 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11320 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11321 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11322 11323 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11324 11325 MVT ResultVT = NewChannels == 1 ? 11326 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11327 NewChannels == 5 ? 8 : NewChannels); 11328 SDVTList NewVTList = HasChain ? 11329 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11330 11331 11332 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11333 NewVTList, Ops); 11334 11335 if (HasChain) { 11336 // Update chain. 11337 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11338 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11339 } 11340 11341 if (NewChannels == 1) { 11342 assert(Node->hasNUsesOfValue(1, 0)); 11343 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11344 SDLoc(Node), Users[Lane]->getValueType(0), 11345 SDValue(NewNode, 0)); 11346 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11347 return nullptr; 11348 } 11349 11350 // Update the users of the node with the new indices 11351 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11352 SDNode *User = Users[i]; 11353 if (!User) { 11354 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11355 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11356 if (i || !NoChannels) 11357 continue; 11358 } else { 11359 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11360 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11361 } 11362 11363 switch (Idx) { 11364 default: break; 11365 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11366 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11367 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11368 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11369 } 11370 } 11371 11372 DAG.RemoveDeadNode(Node); 11373 return nullptr; 11374 } 11375 11376 static bool isFrameIndexOp(SDValue Op) { 11377 if (Op.getOpcode() == ISD::AssertZext) 11378 Op = Op.getOperand(0); 11379 11380 return isa<FrameIndexSDNode>(Op); 11381 } 11382 11383 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11384 /// with frame index operands. 11385 /// LLVM assumes that inputs are to these instructions are registers. 11386 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11387 SelectionDAG &DAG) const { 11388 if (Node->getOpcode() == ISD::CopyToReg) { 11389 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11390 SDValue SrcVal = Node->getOperand(2); 11391 11392 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11393 // to try understanding copies to physical registers. 11394 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11395 SDLoc SL(Node); 11396 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11397 SDValue VReg = DAG.getRegister( 11398 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11399 11400 SDNode *Glued = Node->getGluedNode(); 11401 SDValue ToVReg 11402 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11403 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11404 SDValue ToResultReg 11405 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11406 VReg, ToVReg.getValue(1)); 11407 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11408 DAG.RemoveDeadNode(Node); 11409 return ToResultReg.getNode(); 11410 } 11411 } 11412 11413 SmallVector<SDValue, 8> Ops; 11414 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11415 if (!isFrameIndexOp(Node->getOperand(i))) { 11416 Ops.push_back(Node->getOperand(i)); 11417 continue; 11418 } 11419 11420 SDLoc DL(Node); 11421 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11422 Node->getOperand(i).getValueType(), 11423 Node->getOperand(i)), 0)); 11424 } 11425 11426 return DAG.UpdateNodeOperands(Node, Ops); 11427 } 11428 11429 /// Fold the instructions after selecting them. 11430 /// Returns null if users were already updated. 11431 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11432 SelectionDAG &DAG) const { 11433 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11434 unsigned Opcode = Node->getMachineOpcode(); 11435 11436 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11437 !TII->isGather4(Opcode) && 11438 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11439 return adjustWritemask(Node, DAG); 11440 } 11441 11442 if (Opcode == AMDGPU::INSERT_SUBREG || 11443 Opcode == AMDGPU::REG_SEQUENCE) { 11444 legalizeTargetIndependentNode(Node, DAG); 11445 return Node; 11446 } 11447 11448 switch (Opcode) { 11449 case AMDGPU::V_DIV_SCALE_F32_e64: 11450 case AMDGPU::V_DIV_SCALE_F64_e64: { 11451 // Satisfy the operand register constraint when one of the inputs is 11452 // undefined. Ordinarily each undef value will have its own implicit_def of 11453 // a vreg, so force these to use a single register. 11454 SDValue Src0 = Node->getOperand(1); 11455 SDValue Src1 = Node->getOperand(3); 11456 SDValue Src2 = Node->getOperand(5); 11457 11458 if ((Src0.isMachineOpcode() && 11459 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11460 (Src0 == Src1 || Src0 == Src2)) 11461 break; 11462 11463 MVT VT = Src0.getValueType().getSimpleVT(); 11464 const TargetRegisterClass *RC = 11465 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11466 11467 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11468 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11469 11470 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11471 UndefReg, Src0, SDValue()); 11472 11473 // src0 must be the same register as src1 or src2, even if the value is 11474 // undefined, so make sure we don't violate this constraint. 11475 if (Src0.isMachineOpcode() && 11476 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11477 if (Src1.isMachineOpcode() && 11478 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11479 Src0 = Src1; 11480 else if (Src2.isMachineOpcode() && 11481 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11482 Src0 = Src2; 11483 else { 11484 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11485 Src0 = UndefReg; 11486 Src1 = UndefReg; 11487 } 11488 } else 11489 break; 11490 11491 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11492 Ops[1] = Src0; 11493 Ops[3] = Src1; 11494 Ops[5] = Src2; 11495 Ops.push_back(ImpDef.getValue(1)); 11496 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11497 } 11498 default: 11499 break; 11500 } 11501 11502 return Node; 11503 } 11504 11505 // Any MIMG instructions that use tfe or lwe require an initialization of the 11506 // result register that will be written in the case of a memory access failure. 11507 // The required code is also added to tie this init code to the result of the 11508 // img instruction. 11509 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11510 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11511 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11512 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11513 MachineBasicBlock &MBB = *MI.getParent(); 11514 11515 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11516 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11517 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11518 11519 if (!TFE && !LWE) // intersect_ray 11520 return; 11521 11522 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11523 unsigned LWEVal = LWE->getImm(); 11524 unsigned D16Val = D16 ? D16->getImm() : 0; 11525 11526 if (!TFEVal && !LWEVal) 11527 return; 11528 11529 // At least one of TFE or LWE are non-zero 11530 // We have to insert a suitable initialization of the result value and 11531 // tie this to the dest of the image instruction. 11532 11533 const DebugLoc &DL = MI.getDebugLoc(); 11534 11535 int DstIdx = 11536 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11537 11538 // Calculate which dword we have to initialize to 0. 11539 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11540 11541 // check that dmask operand is found. 11542 assert(MO_Dmask && "Expected dmask operand in instruction"); 11543 11544 unsigned dmask = MO_Dmask->getImm(); 11545 // Determine the number of active lanes taking into account the 11546 // Gather4 special case 11547 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11548 11549 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11550 11551 unsigned InitIdx = 11552 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11553 11554 // Abandon attempt if the dst size isn't large enough 11555 // - this is in fact an error but this is picked up elsewhere and 11556 // reported correctly. 11557 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11558 if (DstSize < InitIdx) 11559 return; 11560 11561 // Create a register for the initialization value. 11562 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11563 unsigned NewDst = 0; // Final initialized value will be in here 11564 11565 // If PRTStrictNull feature is enabled (the default) then initialize 11566 // all the result registers to 0, otherwise just the error indication 11567 // register (VGPRn+1) 11568 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11569 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11570 11571 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11572 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11573 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11574 // Initialize dword 11575 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11576 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11577 .addImm(0); 11578 // Insert into the super-reg 11579 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11580 .addReg(PrevDst) 11581 .addReg(SubReg) 11582 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11583 11584 PrevDst = NewDst; 11585 } 11586 11587 // Add as an implicit operand 11588 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11589 11590 // Tie the just added implicit operand to the dst 11591 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11592 } 11593 11594 /// Assign the register class depending on the number of 11595 /// bits set in the writemask 11596 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11597 SDNode *Node) const { 11598 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11599 11600 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11601 11602 if (TII->isVOP3(MI.getOpcode())) { 11603 // Make sure constant bus requirements are respected. 11604 TII->legalizeOperandsVOP3(MRI, MI); 11605 11606 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11607 // This saves a chain-copy of registers and better balance register 11608 // use between vgpr and agpr as agpr tuples tend to be big. 11609 if (MI.getDesc().OpInfo) { 11610 unsigned Opc = MI.getOpcode(); 11611 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11612 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11613 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11614 if (I == -1) 11615 break; 11616 MachineOperand &Op = MI.getOperand(I); 11617 if (!Op.isReg() || !Op.getReg().isVirtual()) 11618 continue; 11619 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11620 if (!TRI->hasAGPRs(RC)) 11621 continue; 11622 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11623 if (!Src || !Src->isCopy() || 11624 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11625 continue; 11626 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11627 // All uses of agpr64 and agpr32 can also accept vgpr except for 11628 // v_accvgpr_read, but we do not produce agpr reads during selection, 11629 // so no use checks are needed. 11630 MRI.setRegClass(Op.getReg(), NewRC); 11631 } 11632 } 11633 11634 return; 11635 } 11636 11637 // Replace unused atomics with the no return version. 11638 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11639 if (NoRetAtomicOp != -1) { 11640 if (!Node->hasAnyUseOfValue(0)) { 11641 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11642 AMDGPU::OpName::cpol); 11643 if (CPolIdx != -1) { 11644 MachineOperand &CPol = MI.getOperand(CPolIdx); 11645 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11646 } 11647 MI.RemoveOperand(0); 11648 MI.setDesc(TII->get(NoRetAtomicOp)); 11649 return; 11650 } 11651 11652 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11653 // instruction, because the return type of these instructions is a vec2 of 11654 // the memory type, so it can be tied to the input operand. 11655 // This means these instructions always have a use, so we need to add a 11656 // special case to check if the atomic has only one extract_subreg use, 11657 // which itself has no uses. 11658 if ((Node->hasNUsesOfValue(1, 0) && 11659 Node->use_begin()->isMachineOpcode() && 11660 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11661 !Node->use_begin()->hasAnyUseOfValue(0))) { 11662 Register Def = MI.getOperand(0).getReg(); 11663 11664 // Change this into a noret atomic. 11665 MI.setDesc(TII->get(NoRetAtomicOp)); 11666 MI.RemoveOperand(0); 11667 11668 // If we only remove the def operand from the atomic instruction, the 11669 // extract_subreg will be left with a use of a vreg without a def. 11670 // So we need to insert an implicit_def to avoid machine verifier 11671 // errors. 11672 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11673 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11674 } 11675 return; 11676 } 11677 11678 if (TII->isMIMG(MI) && !MI.mayStore()) 11679 AddIMGInit(MI); 11680 } 11681 11682 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11683 uint64_t Val) { 11684 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11685 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11686 } 11687 11688 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11689 const SDLoc &DL, 11690 SDValue Ptr) const { 11691 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11692 11693 // Build the half of the subregister with the constants before building the 11694 // full 128-bit register. If we are building multiple resource descriptors, 11695 // this will allow CSEing of the 2-component register. 11696 const SDValue Ops0[] = { 11697 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11698 buildSMovImm32(DAG, DL, 0), 11699 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11700 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11701 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11702 }; 11703 11704 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11705 MVT::v2i32, Ops0), 0); 11706 11707 // Combine the constants and the pointer. 11708 const SDValue Ops1[] = { 11709 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11710 Ptr, 11711 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11712 SubRegHi, 11713 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11714 }; 11715 11716 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11717 } 11718 11719 /// Return a resource descriptor with the 'Add TID' bit enabled 11720 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11721 /// of the resource descriptor) to create an offset, which is added to 11722 /// the resource pointer. 11723 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11724 SDValue Ptr, uint32_t RsrcDword1, 11725 uint64_t RsrcDword2And3) const { 11726 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11727 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11728 if (RsrcDword1) { 11729 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11730 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11731 0); 11732 } 11733 11734 SDValue DataLo = buildSMovImm32(DAG, DL, 11735 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11736 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11737 11738 const SDValue Ops[] = { 11739 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11740 PtrLo, 11741 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11742 PtrHi, 11743 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11744 DataLo, 11745 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11746 DataHi, 11747 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11748 }; 11749 11750 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11751 } 11752 11753 //===----------------------------------------------------------------------===// 11754 // SI Inline Assembly Support 11755 //===----------------------------------------------------------------------===// 11756 11757 std::pair<unsigned, const TargetRegisterClass *> 11758 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11759 StringRef Constraint, 11760 MVT VT) const { 11761 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11762 11763 const TargetRegisterClass *RC = nullptr; 11764 if (Constraint.size() == 1) { 11765 const unsigned BitWidth = VT.getSizeInBits(); 11766 switch (Constraint[0]) { 11767 default: 11768 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11769 case 's': 11770 case 'r': 11771 switch (BitWidth) { 11772 case 16: 11773 RC = &AMDGPU::SReg_32RegClass; 11774 break; 11775 case 64: 11776 RC = &AMDGPU::SGPR_64RegClass; 11777 break; 11778 default: 11779 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11780 if (!RC) 11781 return std::make_pair(0U, nullptr); 11782 break; 11783 } 11784 break; 11785 case 'v': 11786 switch (BitWidth) { 11787 case 16: 11788 RC = &AMDGPU::VGPR_32RegClass; 11789 break; 11790 default: 11791 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11792 if (!RC) 11793 return std::make_pair(0U, nullptr); 11794 break; 11795 } 11796 break; 11797 case 'a': 11798 if (!Subtarget->hasMAIInsts()) 11799 break; 11800 switch (BitWidth) { 11801 case 16: 11802 RC = &AMDGPU::AGPR_32RegClass; 11803 break; 11804 default: 11805 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11806 if (!RC) 11807 return std::make_pair(0U, nullptr); 11808 break; 11809 } 11810 break; 11811 } 11812 // We actually support i128, i16 and f16 as inline parameters 11813 // even if they are not reported as legal 11814 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11815 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11816 return std::make_pair(0U, RC); 11817 } 11818 11819 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11820 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11821 if (RegName.consume_front("v")) { 11822 RC = &AMDGPU::VGPR_32RegClass; 11823 } else if (RegName.consume_front("s")) { 11824 RC = &AMDGPU::SGPR_32RegClass; 11825 } else if (RegName.consume_front("a")) { 11826 RC = &AMDGPU::AGPR_32RegClass; 11827 } 11828 11829 if (RC) { 11830 uint32_t Idx; 11831 if (RegName.consume_front("[")) { 11832 uint32_t End; 11833 bool Failed = RegName.consumeInteger(10, Idx); 11834 Failed |= !RegName.consume_front(":"); 11835 Failed |= RegName.consumeInteger(10, End); 11836 Failed |= !RegName.consume_back("]"); 11837 if (!Failed) { 11838 uint32_t Width = (End - Idx + 1) * 32; 11839 MCRegister Reg = RC->getRegister(Idx); 11840 if (SIRegisterInfo::isVGPRClass(RC)) 11841 RC = TRI->getVGPRClassForBitWidth(Width); 11842 else if (SIRegisterInfo::isSGPRClass(RC)) 11843 RC = TRI->getSGPRClassForBitWidth(Width); 11844 else if (SIRegisterInfo::isAGPRClass(RC)) 11845 RC = TRI->getAGPRClassForBitWidth(Width); 11846 if (RC) { 11847 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11848 return std::make_pair(Reg, RC); 11849 } 11850 } 11851 } else { 11852 bool Failed = RegName.getAsInteger(10, Idx); 11853 if (!Failed && Idx < RC->getNumRegs()) 11854 return std::make_pair(RC->getRegister(Idx), RC); 11855 } 11856 } 11857 } 11858 11859 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11860 if (Ret.first) 11861 Ret.second = TRI->getPhysRegClass(Ret.first); 11862 11863 return Ret; 11864 } 11865 11866 static bool isImmConstraint(StringRef Constraint) { 11867 if (Constraint.size() == 1) { 11868 switch (Constraint[0]) { 11869 default: break; 11870 case 'I': 11871 case 'J': 11872 case 'A': 11873 case 'B': 11874 case 'C': 11875 return true; 11876 } 11877 } else if (Constraint == "DA" || 11878 Constraint == "DB") { 11879 return true; 11880 } 11881 return false; 11882 } 11883 11884 SITargetLowering::ConstraintType 11885 SITargetLowering::getConstraintType(StringRef Constraint) const { 11886 if (Constraint.size() == 1) { 11887 switch (Constraint[0]) { 11888 default: break; 11889 case 's': 11890 case 'v': 11891 case 'a': 11892 return C_RegisterClass; 11893 } 11894 } 11895 if (isImmConstraint(Constraint)) { 11896 return C_Other; 11897 } 11898 return TargetLowering::getConstraintType(Constraint); 11899 } 11900 11901 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11902 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11903 Val = Val & maskTrailingOnes<uint64_t>(Size); 11904 } 11905 return Val; 11906 } 11907 11908 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11909 std::string &Constraint, 11910 std::vector<SDValue> &Ops, 11911 SelectionDAG &DAG) const { 11912 if (isImmConstraint(Constraint)) { 11913 uint64_t Val; 11914 if (getAsmOperandConstVal(Op, Val) && 11915 checkAsmConstraintVal(Op, Constraint, Val)) { 11916 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11917 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11918 } 11919 } else { 11920 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11921 } 11922 } 11923 11924 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11925 unsigned Size = Op.getScalarValueSizeInBits(); 11926 if (Size > 64) 11927 return false; 11928 11929 if (Size == 16 && !Subtarget->has16BitInsts()) 11930 return false; 11931 11932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11933 Val = C->getSExtValue(); 11934 return true; 11935 } 11936 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11937 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11938 return true; 11939 } 11940 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11941 if (Size != 16 || Op.getNumOperands() != 2) 11942 return false; 11943 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11944 return false; 11945 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11946 Val = C->getSExtValue(); 11947 return true; 11948 } 11949 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11950 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11951 return true; 11952 } 11953 } 11954 11955 return false; 11956 } 11957 11958 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11959 const std::string &Constraint, 11960 uint64_t Val) const { 11961 if (Constraint.size() == 1) { 11962 switch (Constraint[0]) { 11963 case 'I': 11964 return AMDGPU::isInlinableIntLiteral(Val); 11965 case 'J': 11966 return isInt<16>(Val); 11967 case 'A': 11968 return checkAsmConstraintValA(Op, Val); 11969 case 'B': 11970 return isInt<32>(Val); 11971 case 'C': 11972 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11973 AMDGPU::isInlinableIntLiteral(Val); 11974 default: 11975 break; 11976 } 11977 } else if (Constraint.size() == 2) { 11978 if (Constraint == "DA") { 11979 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11980 int64_t LoBits = static_cast<int32_t>(Val); 11981 return checkAsmConstraintValA(Op, HiBits, 32) && 11982 checkAsmConstraintValA(Op, LoBits, 32); 11983 } 11984 if (Constraint == "DB") { 11985 return true; 11986 } 11987 } 11988 llvm_unreachable("Invalid asm constraint"); 11989 } 11990 11991 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11992 uint64_t Val, 11993 unsigned MaxSize) const { 11994 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11995 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11996 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11997 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11998 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11999 return true; 12000 } 12001 return false; 12002 } 12003 12004 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12005 switch (UnalignedClassID) { 12006 case AMDGPU::VReg_64RegClassID: 12007 return AMDGPU::VReg_64_Align2RegClassID; 12008 case AMDGPU::VReg_96RegClassID: 12009 return AMDGPU::VReg_96_Align2RegClassID; 12010 case AMDGPU::VReg_128RegClassID: 12011 return AMDGPU::VReg_128_Align2RegClassID; 12012 case AMDGPU::VReg_160RegClassID: 12013 return AMDGPU::VReg_160_Align2RegClassID; 12014 case AMDGPU::VReg_192RegClassID: 12015 return AMDGPU::VReg_192_Align2RegClassID; 12016 case AMDGPU::VReg_224RegClassID: 12017 return AMDGPU::VReg_224_Align2RegClassID; 12018 case AMDGPU::VReg_256RegClassID: 12019 return AMDGPU::VReg_256_Align2RegClassID; 12020 case AMDGPU::VReg_512RegClassID: 12021 return AMDGPU::VReg_512_Align2RegClassID; 12022 case AMDGPU::VReg_1024RegClassID: 12023 return AMDGPU::VReg_1024_Align2RegClassID; 12024 case AMDGPU::AReg_64RegClassID: 12025 return AMDGPU::AReg_64_Align2RegClassID; 12026 case AMDGPU::AReg_96RegClassID: 12027 return AMDGPU::AReg_96_Align2RegClassID; 12028 case AMDGPU::AReg_128RegClassID: 12029 return AMDGPU::AReg_128_Align2RegClassID; 12030 case AMDGPU::AReg_160RegClassID: 12031 return AMDGPU::AReg_160_Align2RegClassID; 12032 case AMDGPU::AReg_192RegClassID: 12033 return AMDGPU::AReg_192_Align2RegClassID; 12034 case AMDGPU::AReg_256RegClassID: 12035 return AMDGPU::AReg_256_Align2RegClassID; 12036 case AMDGPU::AReg_512RegClassID: 12037 return AMDGPU::AReg_512_Align2RegClassID; 12038 case AMDGPU::AReg_1024RegClassID: 12039 return AMDGPU::AReg_1024_Align2RegClassID; 12040 default: 12041 return -1; 12042 } 12043 } 12044 12045 // Figure out which registers should be reserved for stack access. Only after 12046 // the function is legalized do we know all of the non-spill stack objects or if 12047 // calls are present. 12048 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12049 MachineRegisterInfo &MRI = MF.getRegInfo(); 12050 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12051 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12052 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12053 const SIInstrInfo *TII = ST.getInstrInfo(); 12054 12055 if (Info->isEntryFunction()) { 12056 // Callable functions have fixed registers used for stack access. 12057 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12058 } 12059 12060 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12061 Info->getStackPtrOffsetReg())); 12062 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12063 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12064 12065 // We need to worry about replacing the default register with itself in case 12066 // of MIR testcases missing the MFI. 12067 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12068 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12069 12070 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12071 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12072 12073 Info->limitOccupancy(MF); 12074 12075 if (ST.isWave32() && !MF.empty()) { 12076 for (auto &MBB : MF) { 12077 for (auto &MI : MBB) { 12078 TII->fixImplicitOperands(MI); 12079 } 12080 } 12081 } 12082 12083 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12084 // classes if required. Ideally the register class constraints would differ 12085 // per-subtarget, but there's no easy way to achieve that right now. This is 12086 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12087 // from using them as the register class for legal types. 12088 if (ST.needsAlignedVGPRs()) { 12089 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12090 const Register Reg = Register::index2VirtReg(I); 12091 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12092 if (!RC) 12093 continue; 12094 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12095 if (NewClassID != -1) 12096 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12097 } 12098 } 12099 12100 TargetLoweringBase::finalizeLowering(MF); 12101 } 12102 12103 void SITargetLowering::computeKnownBitsForFrameIndex( 12104 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12105 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12106 12107 // Set the high bits to zero based on the maximum allowed scratch size per 12108 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12109 // calculation won't overflow, so assume the sign bit is never set. 12110 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12111 } 12112 12113 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12114 KnownBits &Known, unsigned Dim) { 12115 unsigned MaxValue = 12116 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12117 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12118 } 12119 12120 void SITargetLowering::computeKnownBitsForTargetInstr( 12121 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12122 const MachineRegisterInfo &MRI, unsigned Depth) const { 12123 const MachineInstr *MI = MRI.getVRegDef(R); 12124 switch (MI->getOpcode()) { 12125 case AMDGPU::G_INTRINSIC: { 12126 switch (MI->getIntrinsicID()) { 12127 case Intrinsic::amdgcn_workitem_id_x: 12128 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12129 break; 12130 case Intrinsic::amdgcn_workitem_id_y: 12131 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12132 break; 12133 case Intrinsic::amdgcn_workitem_id_z: 12134 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12135 break; 12136 case Intrinsic::amdgcn_mbcnt_lo: 12137 case Intrinsic::amdgcn_mbcnt_hi: { 12138 // These return at most the wavefront size - 1. 12139 unsigned Size = MRI.getType(R).getSizeInBits(); 12140 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12141 break; 12142 } 12143 case Intrinsic::amdgcn_groupstaticsize: { 12144 // We can report everything over the maximum size as 0. We can't report 12145 // based on the actual size because we don't know if it's accurate or not 12146 // at any given point. 12147 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12148 break; 12149 } 12150 } 12151 break; 12152 } 12153 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12154 Known.Zero.setHighBits(24); 12155 break; 12156 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12157 Known.Zero.setHighBits(16); 12158 break; 12159 } 12160 } 12161 12162 Align SITargetLowering::computeKnownAlignForTargetInstr( 12163 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12164 unsigned Depth) const { 12165 const MachineInstr *MI = MRI.getVRegDef(R); 12166 switch (MI->getOpcode()) { 12167 case AMDGPU::G_INTRINSIC: 12168 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12169 // FIXME: Can this move to generic code? What about the case where the call 12170 // site specifies a lower alignment? 12171 Intrinsic::ID IID = MI->getIntrinsicID(); 12172 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12173 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12174 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12175 return *RetAlign; 12176 return Align(1); 12177 } 12178 default: 12179 return Align(1); 12180 } 12181 } 12182 12183 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12184 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12185 const Align CacheLineAlign = Align(64); 12186 12187 // Pre-GFX10 target did not benefit from loop alignment 12188 if (!ML || DisableLoopAlignment || 12189 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12190 getSubtarget()->hasInstFwdPrefetchBug()) 12191 return PrefAlign; 12192 12193 // On GFX10 I$ is 4 x 64 bytes cache lines. 12194 // By default prefetcher keeps one cache line behind and reads two ahead. 12195 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12196 // behind and one ahead. 12197 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12198 // If loop fits 64 bytes it always spans no more than two cache lines and 12199 // does not need an alignment. 12200 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12201 // Else if loop is less or equal 192 bytes we need two lines behind. 12202 12203 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12204 const MachineBasicBlock *Header = ML->getHeader(); 12205 if (Header->getAlignment() != PrefAlign) 12206 return Header->getAlignment(); // Already processed. 12207 12208 unsigned LoopSize = 0; 12209 for (const MachineBasicBlock *MBB : ML->blocks()) { 12210 // If inner loop block is aligned assume in average half of the alignment 12211 // size to be added as nops. 12212 if (MBB != Header) 12213 LoopSize += MBB->getAlignment().value() / 2; 12214 12215 for (const MachineInstr &MI : *MBB) { 12216 LoopSize += TII->getInstSizeInBytes(MI); 12217 if (LoopSize > 192) 12218 return PrefAlign; 12219 } 12220 } 12221 12222 if (LoopSize <= 64) 12223 return PrefAlign; 12224 12225 if (LoopSize <= 128) 12226 return CacheLineAlign; 12227 12228 // If any of parent loops is surrounded by prefetch instructions do not 12229 // insert new for inner loop, which would reset parent's settings. 12230 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12231 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12232 auto I = Exit->getFirstNonDebugInstr(); 12233 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12234 return CacheLineAlign; 12235 } 12236 } 12237 12238 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12239 MachineBasicBlock *Exit = ML->getExitBlock(); 12240 12241 if (Pre && Exit) { 12242 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12243 TII->get(AMDGPU::S_INST_PREFETCH)) 12244 .addImm(1); // prefetch 2 lines behind PC 12245 12246 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12247 TII->get(AMDGPU::S_INST_PREFETCH)) 12248 .addImm(2); // prefetch 1 line behind PC 12249 } 12250 12251 return CacheLineAlign; 12252 } 12253 12254 LLVM_ATTRIBUTE_UNUSED 12255 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12256 assert(N->getOpcode() == ISD::CopyFromReg); 12257 do { 12258 // Follow the chain until we find an INLINEASM node. 12259 N = N->getOperand(0).getNode(); 12260 if (N->getOpcode() == ISD::INLINEASM || 12261 N->getOpcode() == ISD::INLINEASM_BR) 12262 return true; 12263 } while (N->getOpcode() == ISD::CopyFromReg); 12264 return false; 12265 } 12266 12267 bool SITargetLowering::isSDNodeSourceOfDivergence( 12268 const SDNode *N, FunctionLoweringInfo *FLI, 12269 LegacyDivergenceAnalysis *KDA) const { 12270 switch (N->getOpcode()) { 12271 case ISD::CopyFromReg: { 12272 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12273 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12274 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12275 Register Reg = R->getReg(); 12276 12277 // FIXME: Why does this need to consider isLiveIn? 12278 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12279 return !TRI->isSGPRReg(MRI, Reg); 12280 12281 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12282 return KDA->isDivergent(V); 12283 12284 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12285 return !TRI->isSGPRReg(MRI, Reg); 12286 } 12287 case ISD::LOAD: { 12288 const LoadSDNode *L = cast<LoadSDNode>(N); 12289 unsigned AS = L->getAddressSpace(); 12290 // A flat load may access private memory. 12291 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12292 } 12293 case ISD::CALLSEQ_END: 12294 return true; 12295 case ISD::INTRINSIC_WO_CHAIN: 12296 return AMDGPU::isIntrinsicSourceOfDivergence( 12297 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12298 case ISD::INTRINSIC_W_CHAIN: 12299 return AMDGPU::isIntrinsicSourceOfDivergence( 12300 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12301 case AMDGPUISD::ATOMIC_CMP_SWAP: 12302 case AMDGPUISD::ATOMIC_INC: 12303 case AMDGPUISD::ATOMIC_DEC: 12304 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12305 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12306 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12307 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12308 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12309 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12310 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12311 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12312 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12313 case AMDGPUISD::BUFFER_ATOMIC_AND: 12314 case AMDGPUISD::BUFFER_ATOMIC_OR: 12315 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12316 case AMDGPUISD::BUFFER_ATOMIC_INC: 12317 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12318 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12319 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12320 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12321 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12322 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12323 // Target-specific read-modify-write atomics are sources of divergence. 12324 return true; 12325 default: 12326 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12327 // Generic read-modify-write atomics are sources of divergence. 12328 return A->readMem() && A->writeMem(); 12329 } 12330 return false; 12331 } 12332 } 12333 12334 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12335 EVT VT) const { 12336 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12337 case MVT::f32: 12338 return hasFP32Denormals(DAG.getMachineFunction()); 12339 case MVT::f64: 12340 case MVT::f16: 12341 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12342 default: 12343 return false; 12344 } 12345 } 12346 12347 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12348 MachineFunction &MF) const { 12349 switch (Ty.getScalarSizeInBits()) { 12350 case 32: 12351 return hasFP32Denormals(MF); 12352 case 64: 12353 case 16: 12354 return hasFP64FP16Denormals(MF); 12355 default: 12356 return false; 12357 } 12358 } 12359 12360 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12361 const SelectionDAG &DAG, 12362 bool SNaN, 12363 unsigned Depth) const { 12364 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12365 const MachineFunction &MF = DAG.getMachineFunction(); 12366 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12367 12368 if (Info->getMode().DX10Clamp) 12369 return true; // Clamped to 0. 12370 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12371 } 12372 12373 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12374 SNaN, Depth); 12375 } 12376 12377 // Global FP atomic instructions have a hardcoded FP mode and do not support 12378 // FP32 denormals, and only support v2f16 denormals. 12379 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12380 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12381 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12382 if (&Flt == &APFloat::IEEEsingle()) 12383 return DenormMode == DenormalMode::getPreserveSign(); 12384 return DenormMode == DenormalMode::getIEEE(); 12385 } 12386 12387 TargetLowering::AtomicExpansionKind 12388 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12389 12390 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12391 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12392 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12393 SmallVector<StringRef> SSNs; 12394 Ctx.getSyncScopeNames(SSNs); 12395 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12396 ? "system" 12397 : SSNs[RMW->getSyncScopeID()]; 12398 ORE.emit([&]() { 12399 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12400 << "Hardware instruction generated for atomic " 12401 << RMW->getOperationName(RMW->getOperation()) 12402 << " operation at memory scope " << MemScope 12403 << " due to an unsafe request."; 12404 }); 12405 return Kind; 12406 }; 12407 12408 switch (RMW->getOperation()) { 12409 case AtomicRMWInst::FAdd: { 12410 Type *Ty = RMW->getType(); 12411 12412 // We don't have a way to support 16-bit atomics now, so just leave them 12413 // as-is. 12414 if (Ty->isHalfTy()) 12415 return AtomicExpansionKind::None; 12416 12417 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12418 return AtomicExpansionKind::CmpXChg; 12419 12420 unsigned AS = RMW->getPointerAddressSpace(); 12421 12422 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12423 Subtarget->hasAtomicFaddInsts()) { 12424 if (Subtarget->hasGFX940Insts()) 12425 return AtomicExpansionKind::None; 12426 12427 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12428 // floating point atomic instructions. May generate more efficient code, 12429 // but may not respect rounding and denormal modes, and may give incorrect 12430 // results for certain memory destinations. 12431 if (RMW->getFunction() 12432 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12433 .getValueAsString() != "true") 12434 return AtomicExpansionKind::CmpXChg; 12435 12436 if (Subtarget->hasGFX90AInsts()) { 12437 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12438 return AtomicExpansionKind::CmpXChg; 12439 12440 auto SSID = RMW->getSyncScopeID(); 12441 if (SSID == SyncScope::System || 12442 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12443 return AtomicExpansionKind::CmpXChg; 12444 12445 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12446 } 12447 12448 if (AS == AMDGPUAS::FLAT_ADDRESS) 12449 return AtomicExpansionKind::CmpXChg; 12450 12451 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12452 : AtomicExpansionKind::CmpXChg; 12453 } 12454 12455 // DS FP atomics do respect the denormal mode, but the rounding mode is 12456 // fixed to round-to-nearest-even. 12457 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12458 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12459 if (!Ty->isDoubleTy()) 12460 return AtomicExpansionKind::None; 12461 12462 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12463 return AtomicExpansionKind::None; 12464 12465 return RMW->getFunction() 12466 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12467 .getValueAsString() == "true" 12468 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12469 : AtomicExpansionKind::CmpXChg; 12470 } 12471 12472 return AtomicExpansionKind::CmpXChg; 12473 } 12474 default: 12475 break; 12476 } 12477 12478 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12479 } 12480 12481 const TargetRegisterClass * 12482 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12483 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12484 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12485 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12486 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12487 : &AMDGPU::SReg_32RegClass; 12488 if (!TRI->isSGPRClass(RC) && !isDivergent) 12489 return TRI->getEquivalentSGPRClass(RC); 12490 else if (TRI->isSGPRClass(RC) && isDivergent) 12491 return TRI->getEquivalentVGPRClass(RC); 12492 12493 return RC; 12494 } 12495 12496 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12497 // uniform values (as produced by the mask results of control flow intrinsics) 12498 // used outside of divergent blocks. The phi users need to also be treated as 12499 // always uniform. 12500 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12501 unsigned WaveSize) { 12502 // FIXME: We assume we never cast the mask results of a control flow 12503 // intrinsic. 12504 // Early exit if the type won't be consistent as a compile time hack. 12505 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12506 if (!IT || IT->getBitWidth() != WaveSize) 12507 return false; 12508 12509 if (!isa<Instruction>(V)) 12510 return false; 12511 if (!Visited.insert(V).second) 12512 return false; 12513 bool Result = false; 12514 for (auto U : V->users()) { 12515 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12516 if (V == U->getOperand(1)) { 12517 switch (Intrinsic->getIntrinsicID()) { 12518 default: 12519 Result = false; 12520 break; 12521 case Intrinsic::amdgcn_if_break: 12522 case Intrinsic::amdgcn_if: 12523 case Intrinsic::amdgcn_else: 12524 Result = true; 12525 break; 12526 } 12527 } 12528 if (V == U->getOperand(0)) { 12529 switch (Intrinsic->getIntrinsicID()) { 12530 default: 12531 Result = false; 12532 break; 12533 case Intrinsic::amdgcn_end_cf: 12534 case Intrinsic::amdgcn_loop: 12535 Result = true; 12536 break; 12537 } 12538 } 12539 } else { 12540 Result = hasCFUser(U, Visited, WaveSize); 12541 } 12542 if (Result) 12543 break; 12544 } 12545 return Result; 12546 } 12547 12548 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12549 const Value *V) const { 12550 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12551 if (CI->isInlineAsm()) { 12552 // FIXME: This cannot give a correct answer. This should only trigger in 12553 // the case where inline asm returns mixed SGPR and VGPR results, used 12554 // outside the defining block. We don't have a specific result to 12555 // consider, so this assumes if any value is SGPR, the overall register 12556 // also needs to be SGPR. 12557 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12558 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12559 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12560 for (auto &TC : TargetConstraints) { 12561 if (TC.Type == InlineAsm::isOutput) { 12562 ComputeConstraintToUse(TC, SDValue()); 12563 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12564 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12565 if (RC && SIRI->isSGPRClass(RC)) 12566 return true; 12567 } 12568 } 12569 } 12570 } 12571 SmallPtrSet<const Value *, 16> Visited; 12572 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12573 } 12574 12575 std::pair<InstructionCost, MVT> 12576 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12577 Type *Ty) const { 12578 std::pair<InstructionCost, MVT> Cost = 12579 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12580 auto Size = DL.getTypeSizeInBits(Ty); 12581 // Maximum load or store can handle 8 dwords for scalar and 4 for 12582 // vector ALU. Let's assume anything above 8 dwords is expensive 12583 // even if legal. 12584 if (Size <= 256) 12585 return Cost; 12586 12587 Cost.first += (Size + 255) / 256; 12588 return Cost; 12589 } 12590 12591 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12592 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12593 for (; I != E; ++I) { 12594 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12595 if (getBasePtrIndex(M) == I.getOperandNo()) 12596 return true; 12597 } 12598 } 12599 return false; 12600 } 12601 12602 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12603 SDValue N1) const { 12604 if (!N0.hasOneUse()) 12605 return false; 12606 // Take care of the opportunity to keep N0 uniform 12607 if (N0->isDivergent() || !N1->isDivergent()) 12608 return true; 12609 // Check if we have a good chance to form the memory access pattern with the 12610 // base and offset 12611 return (DAG.isBaseWithConstantOffset(N0) && 12612 hasMemSDNodeUser(*N0->use_begin())); 12613 } 12614 12615 MachineMemOperand::Flags 12616 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12617 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12618 if (I.getMetadata("amdgpu.noclobber")) 12619 return MONoClobber; 12620 return MachineMemOperand::MONone; 12621 } 12622