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/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineFunction.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/IR/DiagnosticInfo.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/IntrinsicsAMDGPU.h" 35 #include "llvm/IR/IntrinsicsR600.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/KnownBits.h" 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "si-lower" 42 43 STATISTIC(NumTailCalls, "Number of tail calls"); 44 45 static cl::opt<bool> DisableLoopAlignment( 46 "amdgpu-disable-loop-alignment", 47 cl::desc("Do not align and prefetch loops"), 48 cl::init(false)); 49 50 static cl::opt<bool> UseDivergentRegisterIndexing( 51 "amdgpu-use-divergent-register-indexing", 52 cl::Hidden, 53 cl::desc("Use indirect register addressing for divergent indexes"), 54 cl::init(false)); 55 56 static bool hasFP32Denormals(const MachineFunction &MF) { 57 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 58 return Info->getMode().allFP32Denormals(); 59 } 60 61 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 62 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 63 return Info->getMode().allFP64FP16Denormals(); 64 } 65 66 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 67 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 68 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 69 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 70 return AMDGPU::SGPR0 + Reg; 71 } 72 } 73 llvm_unreachable("Cannot allocate sgpr"); 74 } 75 76 SITargetLowering::SITargetLowering(const TargetMachine &TM, 77 const GCNSubtarget &STI) 78 : AMDGPUTargetLowering(TM, STI), 79 Subtarget(&STI) { 80 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 81 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 82 83 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 84 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 85 86 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 87 88 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 89 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 90 91 addRegisterClass(MVT::f64, V64RegClass); 92 addRegisterClass(MVT::v2f32, V64RegClass); 93 94 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 95 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 96 97 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 99 100 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 101 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 102 103 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 104 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 105 106 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 107 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 108 109 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 110 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 111 112 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 113 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 114 115 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 116 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 117 118 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 119 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 120 121 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 122 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 123 124 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 125 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 126 127 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 128 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 129 130 if (Subtarget->has16BitInsts()) { 131 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 132 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 133 134 // Unless there are also VOP3P operations, not operations are really legal. 135 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 136 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 137 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 138 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 139 addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass); 141 } 142 143 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 144 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 145 146 computeRegisterProperties(Subtarget->getRegisterInfo()); 147 148 // The boolean content concept here is too inflexible. Compares only ever 149 // really produce a 1-bit result. Any copy/extend from these will turn into a 150 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 151 // it's what most targets use. 152 setBooleanContents(ZeroOrOneBooleanContent); 153 setBooleanVectorContents(ZeroOrOneBooleanContent); 154 155 // We need to custom lower vector stores from local memory 156 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::i1, Custom); 165 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 166 167 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 175 setOperationAction(ISD::STORE, MVT::i1, Custom); 176 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 177 178 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 179 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 180 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 181 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 182 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 183 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 184 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 185 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 186 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 187 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 188 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 189 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 190 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 191 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 192 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 193 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 194 195 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 197 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 198 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 199 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 200 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 201 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 202 203 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 204 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 205 206 setOperationAction(ISD::SELECT, MVT::i1, Promote); 207 setOperationAction(ISD::SELECT, MVT::i64, Custom); 208 setOperationAction(ISD::SELECT, MVT::f64, Promote); 209 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 210 211 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 212 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 213 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 214 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 216 217 setOperationAction(ISD::SETCC, MVT::i1, Promote); 218 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 219 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 220 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 221 222 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 234 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 235 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 236 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 237 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 238 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 243 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 244 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 245 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 246 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 247 248 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 249 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 250 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 251 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 252 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 253 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 254 255 setOperationAction(ISD::UADDO, MVT::i32, Legal); 256 setOperationAction(ISD::USUBO, MVT::i32, Legal); 257 258 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 259 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 260 261 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 262 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 263 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 264 265 #if 0 266 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 268 #endif 269 270 // We only support LOAD/STORE and vector manipulation ops for vectors 271 // with > 4 elements. 272 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 273 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 274 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 275 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 276 MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64, 277 MVT::v32i32, MVT::v32f32 }) { 278 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 279 switch (Op) { 280 case ISD::LOAD: 281 case ISD::STORE: 282 case ISD::BUILD_VECTOR: 283 case ISD::BITCAST: 284 case ISD::EXTRACT_VECTOR_ELT: 285 case ISD::INSERT_VECTOR_ELT: 286 case ISD::EXTRACT_SUBVECTOR: 287 case ISD::SCALAR_TO_VECTOR: 288 break; 289 case ISD::INSERT_SUBVECTOR: 290 case ISD::CONCAT_VECTORS: 291 setOperationAction(Op, VT, Custom); 292 break; 293 default: 294 setOperationAction(Op, VT, Expand); 295 break; 296 } 297 } 298 } 299 300 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 301 302 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 303 // is expanded to avoid having two separate loops in case the index is a VGPR. 304 305 // Most operations are naturally 32-bit vector operations. We only support 306 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 307 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 308 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 309 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 310 311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 312 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 313 314 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 315 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 316 317 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 319 } 320 321 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 322 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 323 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 324 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 326 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 329 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 330 331 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 333 } 334 335 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 336 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 337 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 338 339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 340 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 341 342 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 343 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 344 345 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 347 } 348 349 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 350 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 351 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 352 353 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 354 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 355 356 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 357 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 358 359 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 361 } 362 363 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 364 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 365 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 366 367 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 368 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 369 370 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 371 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 372 373 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 374 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 375 } 376 377 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 378 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 379 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 380 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 381 382 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 383 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 384 385 // Avoid stack access for these. 386 // TODO: Generalize to more vector types. 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 389 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 391 392 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 393 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 395 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 398 399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 403 404 // Deal with vec3 vector operations when widened to vec4. 405 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 409 410 // Deal with vec5/6/7 vector operations when widened to vec8. 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 414 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 415 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 416 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 417 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 418 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 419 420 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 421 // and output demarshalling 422 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 424 425 // We can't return success/failure, only the old value, 426 // let LLVM add the comparison 427 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 428 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 429 430 if (Subtarget->hasFlatAddressSpace()) { 431 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 432 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 433 } 434 435 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 436 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 437 438 // FIXME: This should be narrowed to i32, but that only happens if i64 is 439 // illegal. 440 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 441 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 442 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 443 444 // On SI this is s_memtime and s_memrealtime on VI. 445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 446 setOperationAction(ISD::TRAP, MVT::Other, Custom); 447 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 448 449 if (Subtarget->has16BitInsts()) { 450 setOperationAction(ISD::FPOW, MVT::f16, Promote); 451 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 452 setOperationAction(ISD::FLOG, MVT::f16, Custom); 453 setOperationAction(ISD::FEXP, MVT::f16, Custom); 454 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 455 } 456 457 if (Subtarget->hasMadMacF32Insts()) 458 setOperationAction(ISD::FMAD, MVT::f32, Legal); 459 460 if (!Subtarget->hasBFI()) { 461 // fcopysign can be done in a single instruction with BFI. 462 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 463 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 464 } 465 466 if (!Subtarget->hasBCNT(32)) 467 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 468 469 if (!Subtarget->hasBCNT(64)) 470 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 471 472 if (Subtarget->hasFFBH()) { 473 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 475 } 476 477 if (Subtarget->hasFFBL()) { 478 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 479 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 480 } 481 482 // We only really have 32-bit BFE instructions (and 16-bit on VI). 483 // 484 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 485 // effort to match them now. We want this to be false for i64 cases when the 486 // extraction isn't restricted to the upper or lower half. Ideally we would 487 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 488 // span the midpoint are probably relatively rare, so don't worry about them 489 // for now. 490 if (Subtarget->hasBFE()) 491 setHasExtractBitsInsn(true); 492 493 // Clamp modifier on add/sub 494 if (Subtarget->hasIntClamp()) { 495 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 496 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 497 } 498 499 if (Subtarget->hasAddNoCarry()) { 500 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 501 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 502 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 503 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 504 } 505 506 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 507 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 508 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 509 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 510 511 512 // These are really only legal for ieee_mode functions. We should be avoiding 513 // them for functions that don't have ieee_mode enabled, so just say they are 514 // legal. 515 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 516 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 517 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 518 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 519 520 521 if (Subtarget->haveRoundOpsF64()) { 522 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 523 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 524 setOperationAction(ISD::FRINT, MVT::f64, Legal); 525 } else { 526 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 527 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 528 setOperationAction(ISD::FRINT, MVT::f64, Custom); 529 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 530 } 531 532 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 533 534 setOperationAction(ISD::FSIN, MVT::f32, Custom); 535 setOperationAction(ISD::FCOS, MVT::f32, Custom); 536 setOperationAction(ISD::FDIV, MVT::f32, Custom); 537 setOperationAction(ISD::FDIV, MVT::f64, Custom); 538 539 if (Subtarget->has16BitInsts()) { 540 setOperationAction(ISD::Constant, MVT::i16, Legal); 541 542 setOperationAction(ISD::SMIN, MVT::i16, Legal); 543 setOperationAction(ISD::SMAX, MVT::i16, Legal); 544 545 setOperationAction(ISD::UMIN, MVT::i16, Legal); 546 setOperationAction(ISD::UMAX, MVT::i16, Legal); 547 548 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 549 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 550 551 setOperationAction(ISD::ROTR, MVT::i16, Expand); 552 setOperationAction(ISD::ROTL, MVT::i16, Expand); 553 554 setOperationAction(ISD::SDIV, MVT::i16, Promote); 555 setOperationAction(ISD::UDIV, MVT::i16, Promote); 556 setOperationAction(ISD::SREM, MVT::i16, Promote); 557 setOperationAction(ISD::UREM, MVT::i16, Promote); 558 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 559 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 560 561 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 562 563 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 565 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 567 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 568 569 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 570 571 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 572 573 setOperationAction(ISD::LOAD, MVT::i16, Custom); 574 575 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 576 577 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 578 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 579 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 580 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 581 582 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 583 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 584 585 // F16 - Constant Actions. 586 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 587 588 // F16 - Load/Store Actions. 589 setOperationAction(ISD::LOAD, MVT::f16, Promote); 590 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 591 setOperationAction(ISD::STORE, MVT::f16, Promote); 592 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 593 594 // F16 - VOP1 Actions. 595 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 596 setOperationAction(ISD::FCOS, MVT::f16, Custom); 597 setOperationAction(ISD::FSIN, MVT::f16, Custom); 598 599 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 600 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 601 602 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 603 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 604 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 605 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 606 setOperationAction(ISD::FROUND, MVT::f16, Custom); 607 setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom); 608 609 // F16 - VOP2 Actions. 610 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 611 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 612 613 setOperationAction(ISD::FDIV, MVT::f16, Custom); 614 615 // F16 - VOP3 Actions. 616 setOperationAction(ISD::FMA, MVT::f16, Legal); 617 if (STI.hasMadF16()) 618 setOperationAction(ISD::FMAD, MVT::f16, Legal); 619 620 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16, 621 MVT::v8f16}) { 622 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 623 switch (Op) { 624 case ISD::LOAD: 625 case ISD::STORE: 626 case ISD::BUILD_VECTOR: 627 case ISD::BITCAST: 628 case ISD::EXTRACT_VECTOR_ELT: 629 case ISD::INSERT_VECTOR_ELT: 630 case ISD::INSERT_SUBVECTOR: 631 case ISD::EXTRACT_SUBVECTOR: 632 case ISD::SCALAR_TO_VECTOR: 633 break; 634 case ISD::CONCAT_VECTORS: 635 setOperationAction(Op, VT, Custom); 636 break; 637 default: 638 setOperationAction(Op, VT, Expand); 639 break; 640 } 641 } 642 } 643 644 // v_perm_b32 can handle either of these. 645 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 646 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 647 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 648 649 // XXX - Do these do anything? Vector constants turn into build_vector. 650 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 651 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 652 653 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 654 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 655 656 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 657 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 658 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 659 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 660 661 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 664 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 665 666 setOperationAction(ISD::AND, MVT::v2i16, Promote); 667 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 668 setOperationAction(ISD::OR, MVT::v2i16, Promote); 669 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 670 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 671 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 672 673 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 674 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 675 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 676 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 677 678 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 679 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 680 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 681 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 682 683 setOperationAction(ISD::LOAD, MVT::v8i16, Promote); 684 AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32); 685 setOperationAction(ISD::LOAD, MVT::v8f16, Promote); 686 AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32); 687 688 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 689 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 690 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 691 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 692 693 setOperationAction(ISD::STORE, MVT::v8i16, Promote); 694 AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32); 695 setOperationAction(ISD::STORE, MVT::v8f16, Promote); 696 AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32); 697 698 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 699 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 700 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 701 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 702 703 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 704 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 705 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 706 707 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand); 708 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand); 709 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand); 710 711 if (!Subtarget->hasVOP3PInsts()) { 712 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 713 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 714 } 715 716 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 717 // This isn't really legal, but this avoids the legalizer unrolling it (and 718 // allows matching fneg (fabs x) patterns) 719 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 720 721 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 722 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 723 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 724 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 725 726 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 727 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 728 setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom); 729 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom); 730 731 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 732 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 733 setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand); 734 setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand); 735 736 for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) { 737 setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom); 738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom); 739 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand); 740 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand); 741 } 742 } 743 744 if (Subtarget->hasVOP3PInsts()) { 745 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 746 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 747 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 750 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 751 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 753 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 754 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 755 756 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 759 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 760 761 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 763 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 764 765 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 766 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 767 768 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 769 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 772 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 777 778 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 779 // Split vector operations. 780 setOperationAction(ISD::SHL, VT, Custom); 781 setOperationAction(ISD::SRA, VT, Custom); 782 setOperationAction(ISD::SRL, VT, Custom); 783 setOperationAction(ISD::ADD, VT, Custom); 784 setOperationAction(ISD::SUB, VT, Custom); 785 setOperationAction(ISD::MUL, VT, Custom); 786 787 setOperationAction(ISD::SMIN, VT, Custom); 788 setOperationAction(ISD::SMAX, VT, Custom); 789 setOperationAction(ISD::UMIN, VT, Custom); 790 setOperationAction(ISD::UMAX, VT, Custom); 791 792 setOperationAction(ISD::UADDSAT, VT, Custom); 793 setOperationAction(ISD::SADDSAT, VT, Custom); 794 setOperationAction(ISD::USUBSAT, VT, Custom); 795 setOperationAction(ISD::SSUBSAT, VT, Custom); 796 } 797 798 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 799 // Split vector operations. 800 setOperationAction(ISD::FADD, VT, Custom); 801 setOperationAction(ISD::FMUL, VT, Custom); 802 setOperationAction(ISD::FMA, VT, Custom); 803 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 804 } 805 806 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 807 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 808 809 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 810 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 811 812 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 814 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 815 816 if (Subtarget->hasPackedFP32Ops()) { 817 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 819 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 820 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 821 822 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 823 setOperationAction(ISD::FADD, VT, Custom); 824 setOperationAction(ISD::FMUL, VT, Custom); 825 setOperationAction(ISD::FMA, VT, Custom); 826 } 827 } 828 } 829 830 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 831 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 832 833 if (Subtarget->has16BitInsts()) { 834 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 835 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 836 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 837 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 838 } else { 839 // Legalization hack. 840 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 841 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 842 843 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 844 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 845 } 846 847 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 848 MVT::v8i16, MVT::v8f16 }) { 849 setOperationAction(ISD::SELECT, VT, Custom); 850 } 851 852 setOperationAction(ISD::SMULO, MVT::i64, Custom); 853 setOperationAction(ISD::UMULO, MVT::i64, Custom); 854 855 if (Subtarget->hasMad64_32()) { 856 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 857 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 858 } 859 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 866 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 867 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 878 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 879 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 889 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 890 891 setTargetDAGCombine({ISD::ADD, 892 ISD::ADDCARRY, 893 ISD::SUB, 894 ISD::SUBCARRY, 895 ISD::FADD, 896 ISD::FSUB, 897 ISD::FMINNUM, 898 ISD::FMAXNUM, 899 ISD::FMINNUM_IEEE, 900 ISD::FMAXNUM_IEEE, 901 ISD::FMA, 902 ISD::SMIN, 903 ISD::SMAX, 904 ISD::UMIN, 905 ISD::UMAX, 906 ISD::SETCC, 907 ISD::AND, 908 ISD::OR, 909 ISD::XOR, 910 ISD::SINT_TO_FP, 911 ISD::UINT_TO_FP, 912 ISD::FCANONICALIZE, 913 ISD::SCALAR_TO_VECTOR, 914 ISD::ZERO_EXTEND, 915 ISD::SIGN_EXTEND_INREG, 916 ISD::EXTRACT_VECTOR_ELT, 917 ISD::INSERT_VECTOR_ELT}); 918 919 // All memory operations. Some folding on the pointer operand is done to help 920 // matching the constant offsets in the addressing modes. 921 setTargetDAGCombine({ISD::LOAD, 922 ISD::STORE, 923 ISD::ATOMIC_LOAD, 924 ISD::ATOMIC_STORE, 925 ISD::ATOMIC_CMP_SWAP, 926 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 927 ISD::ATOMIC_SWAP, 928 ISD::ATOMIC_LOAD_ADD, 929 ISD::ATOMIC_LOAD_SUB, 930 ISD::ATOMIC_LOAD_AND, 931 ISD::ATOMIC_LOAD_OR, 932 ISD::ATOMIC_LOAD_XOR, 933 ISD::ATOMIC_LOAD_NAND, 934 ISD::ATOMIC_LOAD_MIN, 935 ISD::ATOMIC_LOAD_MAX, 936 ISD::ATOMIC_LOAD_UMIN, 937 ISD::ATOMIC_LOAD_UMAX, 938 ISD::ATOMIC_LOAD_FADD, 939 ISD::INTRINSIC_VOID, 940 ISD::INTRINSIC_W_CHAIN}); 941 942 // FIXME: In other contexts we pretend this is a per-function property. 943 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 944 945 setSchedulingPreference(Sched::RegPressure); 946 } 947 948 const GCNSubtarget *SITargetLowering::getSubtarget() const { 949 return Subtarget; 950 } 951 952 //===----------------------------------------------------------------------===// 953 // TargetLowering queries 954 //===----------------------------------------------------------------------===// 955 956 // v_mad_mix* support a conversion from f16 to f32. 957 // 958 // There is only one special case when denormals are enabled we don't currently, 959 // where this is OK to use. 960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 961 EVT DestVT, EVT SrcVT) const { 962 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 963 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 964 DestVT.getScalarType() == MVT::f32 && 965 SrcVT.getScalarType() == MVT::f16 && 966 // TODO: This probably only requires no input flushing? 967 !hasFP32Denormals(DAG.getMachineFunction()); 968 } 969 970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 971 LLT DestTy, LLT SrcTy) const { 972 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 973 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 974 DestTy.getScalarSizeInBits() == 32 && 975 SrcTy.getScalarSizeInBits() == 16 && 976 // TODO: This probably only requires no input flushing? 977 !hasFP32Denormals(*MI.getMF()); 978 } 979 980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 981 // SI has some legal vector types, but no legal vector operations. Say no 982 // shuffles are legal in order to prefer scalarizing some vector operations. 983 return false; 984 } 985 986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 987 CallingConv::ID CC, 988 EVT VT) const { 989 if (CC == CallingConv::AMDGPU_KERNEL) 990 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 991 992 if (VT.isVector()) { 993 EVT ScalarVT = VT.getScalarType(); 994 unsigned Size = ScalarVT.getSizeInBits(); 995 if (Size == 16) { 996 if (Subtarget->has16BitInsts()) 997 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 998 return VT.isInteger() ? MVT::i32 : MVT::f32; 999 } 1000 1001 if (Size < 16) 1002 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1003 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1004 } 1005 1006 if (VT.getSizeInBits() > 32) 1007 return MVT::i32; 1008 1009 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1010 } 1011 1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1013 CallingConv::ID CC, 1014 EVT VT) const { 1015 if (CC == CallingConv::AMDGPU_KERNEL) 1016 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1017 1018 if (VT.isVector()) { 1019 unsigned NumElts = VT.getVectorNumElements(); 1020 EVT ScalarVT = VT.getScalarType(); 1021 unsigned Size = ScalarVT.getSizeInBits(); 1022 1023 // FIXME: Should probably promote 8-bit vectors to i16. 1024 if (Size == 16 && Subtarget->has16BitInsts()) 1025 return (NumElts + 1) / 2; 1026 1027 if (Size <= 32) 1028 return NumElts; 1029 1030 if (Size > 32) 1031 return NumElts * ((Size + 31) / 32); 1032 } else if (VT.getSizeInBits() > 32) 1033 return (VT.getSizeInBits() + 31) / 32; 1034 1035 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1036 } 1037 1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1039 LLVMContext &Context, CallingConv::ID CC, 1040 EVT VT, EVT &IntermediateVT, 1041 unsigned &NumIntermediates, MVT &RegisterVT) const { 1042 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1043 unsigned NumElts = VT.getVectorNumElements(); 1044 EVT ScalarVT = VT.getScalarType(); 1045 unsigned Size = ScalarVT.getSizeInBits(); 1046 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1047 // support, but unless we can properly handle 3-vectors, it will be still be 1048 // inconsistent. 1049 if (Size == 16 && Subtarget->has16BitInsts()) { 1050 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1051 IntermediateVT = RegisterVT; 1052 NumIntermediates = (NumElts + 1) / 2; 1053 return NumIntermediates; 1054 } 1055 1056 if (Size == 32) { 1057 RegisterVT = ScalarVT.getSimpleVT(); 1058 IntermediateVT = RegisterVT; 1059 NumIntermediates = NumElts; 1060 return NumIntermediates; 1061 } 1062 1063 if (Size < 16 && Subtarget->has16BitInsts()) { 1064 // FIXME: Should probably form v2i16 pieces 1065 RegisterVT = MVT::i16; 1066 IntermediateVT = ScalarVT; 1067 NumIntermediates = NumElts; 1068 return NumIntermediates; 1069 } 1070 1071 1072 if (Size != 16 && Size <= 32) { 1073 RegisterVT = MVT::i32; 1074 IntermediateVT = ScalarVT; 1075 NumIntermediates = NumElts; 1076 return NumIntermediates; 1077 } 1078 1079 if (Size > 32) { 1080 RegisterVT = MVT::i32; 1081 IntermediateVT = RegisterVT; 1082 NumIntermediates = NumElts * ((Size + 31) / 32); 1083 return NumIntermediates; 1084 } 1085 } 1086 1087 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1088 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1089 } 1090 1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1092 assert(DMaskLanes != 0); 1093 1094 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1095 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1096 return EVT::getVectorVT(Ty->getContext(), 1097 EVT::getEVT(VT->getElementType()), 1098 NumElts); 1099 } 1100 1101 return EVT::getEVT(Ty); 1102 } 1103 1104 // Peek through TFE struct returns to only use the data size. 1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1106 auto *ST = dyn_cast<StructType>(Ty); 1107 if (!ST) 1108 return memVTFromImageData(Ty, DMaskLanes); 1109 1110 // Some intrinsics return an aggregate type - special case to work out the 1111 // correct memVT. 1112 // 1113 // Only limited forms of aggregate type currently expected. 1114 if (ST->getNumContainedTypes() != 2 || 1115 !ST->getContainedType(1)->isIntegerTy(32)) 1116 return EVT(); 1117 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1118 } 1119 1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1121 const CallInst &CI, 1122 MachineFunction &MF, 1123 unsigned IntrID) const { 1124 Info.flags = MachineMemOperand::MONone; 1125 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1126 Info.flags |= MachineMemOperand::MOInvariant; 1127 1128 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1129 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1130 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1131 (Intrinsic::ID)IntrID); 1132 if (Attr.hasFnAttr(Attribute::ReadNone)) 1133 return false; 1134 1135 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1136 1137 if (RsrcIntr->IsImage) { 1138 Info.ptrVal = 1139 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1140 Info.align.reset(); 1141 } else { 1142 Info.ptrVal = 1143 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1144 } 1145 1146 Info.flags |= MachineMemOperand::MODereferenceable; 1147 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1148 unsigned DMaskLanes = 4; 1149 1150 if (RsrcIntr->IsImage) { 1151 const AMDGPU::ImageDimIntrinsicInfo *Intr 1152 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1153 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1154 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1155 1156 if (!BaseOpcode->Gather4) { 1157 // If this isn't a gather, we may have excess loaded elements in the 1158 // IR type. Check the dmask for the real number of elements loaded. 1159 unsigned DMask 1160 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1161 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1162 } 1163 1164 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1165 } else 1166 Info.memVT = EVT::getEVT(CI.getType()); 1167 1168 // FIXME: What does alignment mean for an image? 1169 Info.opc = ISD::INTRINSIC_W_CHAIN; 1170 Info.flags |= MachineMemOperand::MOLoad; 1171 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1172 Info.opc = ISD::INTRINSIC_VOID; 1173 1174 Type *DataTy = CI.getArgOperand(0)->getType(); 1175 if (RsrcIntr->IsImage) { 1176 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1177 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1178 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1179 } else 1180 Info.memVT = EVT::getEVT(DataTy); 1181 1182 Info.flags |= MachineMemOperand::MOStore; 1183 } else { 1184 // Atomic 1185 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1186 ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1188 Info.flags |= MachineMemOperand::MOLoad | 1189 MachineMemOperand::MOStore | 1190 MachineMemOperand::MODereferenceable; 1191 1192 // XXX - Should this be volatile without known ordering? 1193 Info.flags |= MachineMemOperand::MOVolatile; 1194 } 1195 return true; 1196 } 1197 1198 switch (IntrID) { 1199 case Intrinsic::amdgcn_atomic_inc: 1200 case Intrinsic::amdgcn_atomic_dec: 1201 case Intrinsic::amdgcn_ds_ordered_add: 1202 case Intrinsic::amdgcn_ds_ordered_swap: 1203 case Intrinsic::amdgcn_ds_fadd: 1204 case Intrinsic::amdgcn_ds_fmin: 1205 case Intrinsic::amdgcn_ds_fmax: { 1206 Info.opc = ISD::INTRINSIC_W_CHAIN; 1207 Info.memVT = MVT::getVT(CI.getType()); 1208 Info.ptrVal = CI.getOperand(0); 1209 Info.align.reset(); 1210 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1211 1212 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1213 if (!Vol->isZero()) 1214 Info.flags |= MachineMemOperand::MOVolatile; 1215 1216 return true; 1217 } 1218 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1219 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1220 1221 Info.opc = ISD::INTRINSIC_W_CHAIN; 1222 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1223 Info.ptrVal = 1224 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1225 Info.align.reset(); 1226 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1227 1228 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1229 if (!Vol || !Vol->isZero()) 1230 Info.flags |= MachineMemOperand::MOVolatile; 1231 1232 return true; 1233 } 1234 case Intrinsic::amdgcn_ds_append: 1235 case Intrinsic::amdgcn_ds_consume: { 1236 Info.opc = ISD::INTRINSIC_W_CHAIN; 1237 Info.memVT = MVT::getVT(CI.getType()); 1238 Info.ptrVal = CI.getOperand(0); 1239 Info.align.reset(); 1240 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1241 1242 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1243 if (!Vol->isZero()) 1244 Info.flags |= MachineMemOperand::MOVolatile; 1245 1246 return true; 1247 } 1248 case Intrinsic::amdgcn_global_atomic_csub: { 1249 Info.opc = ISD::INTRINSIC_W_CHAIN; 1250 Info.memVT = MVT::getVT(CI.getType()); 1251 Info.ptrVal = CI.getOperand(0); 1252 Info.align.reset(); 1253 Info.flags |= MachineMemOperand::MOLoad | 1254 MachineMemOperand::MOStore | 1255 MachineMemOperand::MOVolatile; 1256 return true; 1257 } 1258 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1259 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1260 Info.opc = ISD::INTRINSIC_W_CHAIN; 1261 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1262 Info.ptrVal = 1263 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1264 Info.align.reset(); 1265 Info.flags |= MachineMemOperand::MOLoad | 1266 MachineMemOperand::MODereferenceable; 1267 return true; 1268 } 1269 case Intrinsic::amdgcn_global_atomic_fadd: 1270 case Intrinsic::amdgcn_global_atomic_fmin: 1271 case Intrinsic::amdgcn_global_atomic_fmax: 1272 case Intrinsic::amdgcn_flat_atomic_fadd: 1273 case Intrinsic::amdgcn_flat_atomic_fmin: 1274 case Intrinsic::amdgcn_flat_atomic_fmax: 1275 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1276 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1277 Info.opc = ISD::INTRINSIC_W_CHAIN; 1278 Info.memVT = MVT::getVT(CI.getType()); 1279 Info.ptrVal = CI.getOperand(0); 1280 Info.align.reset(); 1281 Info.flags |= MachineMemOperand::MOLoad | 1282 MachineMemOperand::MOStore | 1283 MachineMemOperand::MODereferenceable | 1284 MachineMemOperand::MOVolatile; 1285 return true; 1286 } 1287 case Intrinsic::amdgcn_ds_gws_init: 1288 case Intrinsic::amdgcn_ds_gws_barrier: 1289 case Intrinsic::amdgcn_ds_gws_sema_v: 1290 case Intrinsic::amdgcn_ds_gws_sema_br: 1291 case Intrinsic::amdgcn_ds_gws_sema_p: 1292 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1293 Info.opc = ISD::INTRINSIC_VOID; 1294 1295 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1296 Info.ptrVal = 1297 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1298 1299 // This is an abstract access, but we need to specify a type and size. 1300 Info.memVT = MVT::i32; 1301 Info.size = 4; 1302 Info.align = Align(4); 1303 1304 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1305 Info.flags |= MachineMemOperand::MOLoad; 1306 else 1307 Info.flags |= MachineMemOperand::MOStore; 1308 return true; 1309 } 1310 default: 1311 return false; 1312 } 1313 } 1314 1315 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1316 SmallVectorImpl<Value*> &Ops, 1317 Type *&AccessTy) const { 1318 switch (II->getIntrinsicID()) { 1319 case Intrinsic::amdgcn_atomic_inc: 1320 case Intrinsic::amdgcn_atomic_dec: 1321 case Intrinsic::amdgcn_ds_ordered_add: 1322 case Intrinsic::amdgcn_ds_ordered_swap: 1323 case Intrinsic::amdgcn_ds_append: 1324 case Intrinsic::amdgcn_ds_consume: 1325 case Intrinsic::amdgcn_ds_fadd: 1326 case Intrinsic::amdgcn_ds_fmin: 1327 case Intrinsic::amdgcn_ds_fmax: 1328 case Intrinsic::amdgcn_global_atomic_fadd: 1329 case Intrinsic::amdgcn_flat_atomic_fadd: 1330 case Intrinsic::amdgcn_flat_atomic_fmin: 1331 case Intrinsic::amdgcn_flat_atomic_fmax: 1332 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1333 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1334 case Intrinsic::amdgcn_global_atomic_csub: { 1335 Value *Ptr = II->getArgOperand(0); 1336 AccessTy = II->getType(); 1337 Ops.push_back(Ptr); 1338 return true; 1339 } 1340 default: 1341 return false; 1342 } 1343 } 1344 1345 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1346 if (!Subtarget->hasFlatInstOffsets()) { 1347 // Flat instructions do not have offsets, and only have the register 1348 // address. 1349 return AM.BaseOffs == 0 && AM.Scale == 0; 1350 } 1351 1352 return AM.Scale == 0 && 1353 (AM.BaseOffs == 0 || 1354 Subtarget->getInstrInfo()->isLegalFLATOffset( 1355 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1356 } 1357 1358 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1359 if (Subtarget->hasFlatGlobalInsts()) 1360 return AM.Scale == 0 && 1361 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1362 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1363 SIInstrFlags::FlatGlobal)); 1364 1365 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1366 // Assume the we will use FLAT for all global memory accesses 1367 // on VI. 1368 // FIXME: This assumption is currently wrong. On VI we still use 1369 // MUBUF instructions for the r + i addressing mode. As currently 1370 // implemented, the MUBUF instructions only work on buffer < 4GB. 1371 // It may be possible to support > 4GB buffers with MUBUF instructions, 1372 // by setting the stride value in the resource descriptor which would 1373 // increase the size limit to (stride * 4GB). However, this is risky, 1374 // because it has never been validated. 1375 return isLegalFlatAddressingMode(AM); 1376 } 1377 1378 return isLegalMUBUFAddressingMode(AM); 1379 } 1380 1381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1382 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1383 // additionally can do r + r + i with addr64. 32-bit has more addressing 1384 // mode options. Depending on the resource constant, it can also do 1385 // (i64 r0) + (i32 r1) * (i14 i). 1386 // 1387 // Private arrays end up using a scratch buffer most of the time, so also 1388 // assume those use MUBUF instructions. Scratch loads / stores are currently 1389 // implemented as mubuf instructions with offen bit set, so slightly 1390 // different than the normal addr64. 1391 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1392 return false; 1393 1394 // FIXME: Since we can split immediate into soffset and immediate offset, 1395 // would it make sense to allow any immediate? 1396 1397 switch (AM.Scale) { 1398 case 0: // r + i or just i, depending on HasBaseReg. 1399 return true; 1400 case 1: 1401 return true; // We have r + r or r + i. 1402 case 2: 1403 if (AM.HasBaseReg) { 1404 // Reject 2 * r + r. 1405 return false; 1406 } 1407 1408 // Allow 2 * r as r + r 1409 // Or 2 * r + i is allowed as r + r + i. 1410 return true; 1411 default: // Don't allow n * r 1412 return false; 1413 } 1414 } 1415 1416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1417 const AddrMode &AM, Type *Ty, 1418 unsigned AS, Instruction *I) const { 1419 // No global is ever allowed as a base. 1420 if (AM.BaseGV) 1421 return false; 1422 1423 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1424 return isLegalGlobalAddressingMode(AM); 1425 1426 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1427 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1428 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1429 // If the offset isn't a multiple of 4, it probably isn't going to be 1430 // correctly aligned. 1431 // FIXME: Can we get the real alignment here? 1432 if (AM.BaseOffs % 4 != 0) 1433 return isLegalMUBUFAddressingMode(AM); 1434 1435 // There are no SMRD extloads, so if we have to do a small type access we 1436 // will use a MUBUF load. 1437 // FIXME?: We also need to do this if unaligned, but we don't know the 1438 // alignment here. 1439 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1440 return isLegalGlobalAddressingMode(AM); 1441 1442 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1443 // SMRD instructions have an 8-bit, dword offset on SI. 1444 if (!isUInt<8>(AM.BaseOffs / 4)) 1445 return false; 1446 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1447 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1448 // in 8-bits, it can use a smaller encoding. 1449 if (!isUInt<32>(AM.BaseOffs / 4)) 1450 return false; 1451 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1452 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1453 if (!isUInt<20>(AM.BaseOffs)) 1454 return false; 1455 } else 1456 llvm_unreachable("unhandled generation"); 1457 1458 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1459 return true; 1460 1461 if (AM.Scale == 1 && AM.HasBaseReg) 1462 return true; 1463 1464 return false; 1465 1466 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1467 return isLegalMUBUFAddressingMode(AM); 1468 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1469 AS == AMDGPUAS::REGION_ADDRESS) { 1470 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1471 // field. 1472 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1473 // an 8-bit dword offset but we don't know the alignment here. 1474 if (!isUInt<16>(AM.BaseOffs)) 1475 return false; 1476 1477 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1478 return true; 1479 1480 if (AM.Scale == 1 && AM.HasBaseReg) 1481 return true; 1482 1483 return false; 1484 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1485 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1486 // For an unknown address space, this usually means that this is for some 1487 // reason being used for pure arithmetic, and not based on some addressing 1488 // computation. We don't have instructions that compute pointers with any 1489 // addressing modes, so treat them as having no offset like flat 1490 // instructions. 1491 return isLegalFlatAddressingMode(AM); 1492 } 1493 1494 // Assume a user alias of global for unknown address spaces. 1495 return isLegalGlobalAddressingMode(AM); 1496 } 1497 1498 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1499 const MachineFunction &MF) const { 1500 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1501 return (MemVT.getSizeInBits() <= 4 * 32); 1502 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1503 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1504 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1505 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1506 return (MemVT.getSizeInBits() <= 2 * 32); 1507 } 1508 return true; 1509 } 1510 1511 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1512 unsigned Size, unsigned AddrSpace, Align Alignment, 1513 MachineMemOperand::Flags Flags, bool *IsFast) const { 1514 if (IsFast) 1515 *IsFast = false; 1516 1517 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1518 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1519 // Check if alignment requirements for ds_read/write instructions are 1520 // disabled. 1521 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4)) 1522 return false; 1523 1524 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment. 1525 if (Subtarget->hasLDSMisalignedBug() && Size > 32 && 1526 Alignment < RequiredAlignment) 1527 return false; 1528 1529 // Either, the alignment requirements are "enabled", or there is an 1530 // unaligned LDS access related hardware bug though alignment requirements 1531 // are "disabled". In either case, we need to check for proper alignment 1532 // requirements. 1533 // 1534 switch (Size) { 1535 case 64: 1536 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1537 // address is negative, then the instruction is incorrectly treated as 1538 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1539 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1540 // load later in the SILoadStoreOptimizer. 1541 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1542 return false; 1543 1544 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1545 // can do a 4 byte aligned, 8 byte access in a single operation using 1546 // ds_read2/write2_b32 with adjacent offsets. 1547 RequiredAlignment = Align(4); 1548 1549 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1550 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/ 1551 // ds_write2_b32 depending on the alignment. In either case with either 1552 // alignment there is no faster way of doing this. 1553 if (IsFast) 1554 *IsFast = true; 1555 return true; 1556 } 1557 1558 break; 1559 case 96: 1560 if (!Subtarget->hasDS96AndDS128()) 1561 return false; 1562 1563 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1564 // gfx8 and older. 1565 1566 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1567 // Naturally aligned access is fastest. However, also report it is Fast 1568 // if memory is aligned less than DWORD. A narrow load or store will be 1569 // be equally slow as a single ds_read_b96/ds_write_b96, but there will 1570 // be more of them, so overall we will pay less penalty issuing a single 1571 // instruction. 1572 if (IsFast) 1573 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1574 return true; 1575 } 1576 1577 break; 1578 case 128: 1579 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128()) 1580 return false; 1581 1582 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1583 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1584 // single operation using ds_read2/write2_b64. 1585 RequiredAlignment = Align(8); 1586 1587 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1588 // Naturally aligned access is fastest. However, also report it is Fast 1589 // if memory is aligned less than DWORD. A narrow load or store will be 1590 // be equally slow as a single ds_read_b128/ds_write_b128, but there 1591 // will be more of them, so overall we will pay less penalty issuing a 1592 // single instruction. 1593 if (IsFast) 1594 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1595 return true; 1596 } 1597 1598 break; 1599 default: 1600 if (Size > 32) 1601 return false; 1602 1603 break; 1604 } 1605 1606 if (IsFast) 1607 *IsFast = Alignment >= RequiredAlignment; 1608 1609 return Alignment >= RequiredAlignment || 1610 Subtarget->hasUnalignedDSAccessEnabled(); 1611 } 1612 1613 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1614 bool AlignedBy4 = Alignment >= Align(4); 1615 if (IsFast) 1616 *IsFast = AlignedBy4; 1617 1618 return AlignedBy4 || 1619 Subtarget->enableFlatScratch() || 1620 Subtarget->hasUnalignedScratchAccess(); 1621 } 1622 1623 // FIXME: We have to be conservative here and assume that flat operations 1624 // will access scratch. If we had access to the IR function, then we 1625 // could determine if any private memory was used in the function. 1626 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1627 !Subtarget->hasUnalignedScratchAccess()) { 1628 bool AlignedBy4 = Alignment >= Align(4); 1629 if (IsFast) 1630 *IsFast = AlignedBy4; 1631 1632 return AlignedBy4; 1633 } 1634 1635 if (Subtarget->hasUnalignedBufferAccessEnabled()) { 1636 // If we have a uniform constant load, it still requires using a slow 1637 // buffer instruction if unaligned. 1638 if (IsFast) { 1639 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1640 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1641 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1642 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1643 Alignment >= Align(4) : Alignment != Align(2); 1644 } 1645 1646 return true; 1647 } 1648 1649 // Smaller than dword value must be aligned. 1650 if (Size < 32) 1651 return false; 1652 1653 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1654 // byte-address are ignored, thus forcing Dword alignment. 1655 // This applies to private, global, and constant memory. 1656 if (IsFast) 1657 *IsFast = true; 1658 1659 return Size >= 32 && Alignment >= Align(4); 1660 } 1661 1662 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1663 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1664 bool *IsFast) const { 1665 bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1666 Alignment, Flags, IsFast); 1667 1668 if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() && 1669 (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1670 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1671 // Lie it is fast if +unaligned-access-mode is passed so that DS accesses 1672 // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a 1673 // misaligned data which is faster than a pair of ds_read_b*/ds_write_b* 1674 // which would be equally misaligned. 1675 // This is only used by the common passes, selection always calls the 1676 // allowsMisalignedMemoryAccessesImpl version. 1677 *IsFast = true; 1678 } 1679 1680 return Allow; 1681 } 1682 1683 EVT SITargetLowering::getOptimalMemOpType( 1684 const MemOp &Op, const AttributeList &FuncAttributes) const { 1685 // FIXME: Should account for address space here. 1686 1687 // The default fallback uses the private pointer size as a guess for a type to 1688 // use. Make sure we switch these to 64-bit accesses. 1689 1690 if (Op.size() >= 16 && 1691 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1692 return MVT::v4i32; 1693 1694 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1695 return MVT::v2i32; 1696 1697 // Use the default. 1698 return MVT::Other; 1699 } 1700 1701 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1702 const MemSDNode *MemNode = cast<MemSDNode>(N); 1703 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1704 } 1705 1706 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1707 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1708 AS == AMDGPUAS::PRIVATE_ADDRESS; 1709 } 1710 1711 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1712 unsigned DestAS) const { 1713 // Flat -> private/local is a simple truncate. 1714 // Flat -> global is no-op 1715 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1716 return true; 1717 1718 const GCNTargetMachine &TM = 1719 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1720 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1721 } 1722 1723 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1724 const MemSDNode *MemNode = cast<MemSDNode>(N); 1725 1726 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1727 } 1728 1729 TargetLoweringBase::LegalizeTypeAction 1730 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1731 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1732 VT.getScalarType().bitsLE(MVT::i16)) 1733 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1734 return TargetLoweringBase::getPreferredVectorAction(VT); 1735 } 1736 1737 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1738 Type *Ty) const { 1739 // FIXME: Could be smarter if called for vector constants. 1740 return true; 1741 } 1742 1743 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1744 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1745 switch (Op) { 1746 case ISD::LOAD: 1747 case ISD::STORE: 1748 1749 // These operations are done with 32-bit instructions anyway. 1750 case ISD::AND: 1751 case ISD::OR: 1752 case ISD::XOR: 1753 case ISD::SELECT: 1754 // TODO: Extensions? 1755 return true; 1756 default: 1757 return false; 1758 } 1759 } 1760 1761 // SimplifySetCC uses this function to determine whether or not it should 1762 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1763 if (VT == MVT::i1 && Op == ISD::SETCC) 1764 return false; 1765 1766 return TargetLowering::isTypeDesirableForOp(Op, VT); 1767 } 1768 1769 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1770 const SDLoc &SL, 1771 SDValue Chain, 1772 uint64_t Offset) const { 1773 const DataLayout &DL = DAG.getDataLayout(); 1774 MachineFunction &MF = DAG.getMachineFunction(); 1775 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1776 1777 const ArgDescriptor *InputPtrReg; 1778 const TargetRegisterClass *RC; 1779 LLT ArgTy; 1780 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1781 1782 std::tie(InputPtrReg, RC, ArgTy) = 1783 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1784 1785 // We may not have the kernarg segment argument if we have no kernel 1786 // arguments. 1787 if (!InputPtrReg) 1788 return DAG.getConstant(0, SL, PtrVT); 1789 1790 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1791 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1792 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1793 1794 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1795 } 1796 1797 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1798 const SDLoc &SL) const { 1799 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1800 FIRST_IMPLICIT); 1801 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1802 } 1803 1804 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1805 const SDLoc &SL, SDValue Val, 1806 bool Signed, 1807 const ISD::InputArg *Arg) const { 1808 // First, if it is a widened vector, narrow it. 1809 if (VT.isVector() && 1810 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1811 EVT NarrowedVT = 1812 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1813 VT.getVectorNumElements()); 1814 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1815 DAG.getConstant(0, SL, MVT::i32)); 1816 } 1817 1818 // Then convert the vector elements or scalar value. 1819 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1820 VT.bitsLT(MemVT)) { 1821 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1822 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1823 } 1824 1825 if (MemVT.isFloatingPoint()) 1826 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1827 else if (Signed) 1828 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1829 else 1830 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1831 1832 return Val; 1833 } 1834 1835 SDValue SITargetLowering::lowerKernargMemParameter( 1836 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1837 uint64_t Offset, Align Alignment, bool Signed, 1838 const ISD::InputArg *Arg) const { 1839 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1840 1841 // Try to avoid using an extload by loading earlier than the argument address, 1842 // and extracting the relevant bits. The load should hopefully be merged with 1843 // the previous argument. 1844 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1845 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1846 int64_t AlignDownOffset = alignDown(Offset, 4); 1847 int64_t OffsetDiff = Offset - AlignDownOffset; 1848 1849 EVT IntVT = MemVT.changeTypeToInteger(); 1850 1851 // TODO: If we passed in the base kernel offset we could have a better 1852 // alignment than 4, but we don't really need it. 1853 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1854 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1855 MachineMemOperand::MODereferenceable | 1856 MachineMemOperand::MOInvariant); 1857 1858 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1859 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1860 1861 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1862 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1863 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1864 1865 1866 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1867 } 1868 1869 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1870 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1871 MachineMemOperand::MODereferenceable | 1872 MachineMemOperand::MOInvariant); 1873 1874 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1875 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1876 } 1877 1878 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1879 const SDLoc &SL, SDValue Chain, 1880 const ISD::InputArg &Arg) const { 1881 MachineFunction &MF = DAG.getMachineFunction(); 1882 MachineFrameInfo &MFI = MF.getFrameInfo(); 1883 1884 if (Arg.Flags.isByVal()) { 1885 unsigned Size = Arg.Flags.getByValSize(); 1886 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1887 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1888 } 1889 1890 unsigned ArgOffset = VA.getLocMemOffset(); 1891 unsigned ArgSize = VA.getValVT().getStoreSize(); 1892 1893 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1894 1895 // Create load nodes to retrieve arguments from the stack. 1896 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1897 SDValue ArgValue; 1898 1899 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1900 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1901 MVT MemVT = VA.getValVT(); 1902 1903 switch (VA.getLocInfo()) { 1904 default: 1905 break; 1906 case CCValAssign::BCvt: 1907 MemVT = VA.getLocVT(); 1908 break; 1909 case CCValAssign::SExt: 1910 ExtType = ISD::SEXTLOAD; 1911 break; 1912 case CCValAssign::ZExt: 1913 ExtType = ISD::ZEXTLOAD; 1914 break; 1915 case CCValAssign::AExt: 1916 ExtType = ISD::EXTLOAD; 1917 break; 1918 } 1919 1920 ArgValue = DAG.getExtLoad( 1921 ExtType, SL, VA.getLocVT(), Chain, FIN, 1922 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1923 MemVT); 1924 return ArgValue; 1925 } 1926 1927 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1928 const SIMachineFunctionInfo &MFI, 1929 EVT VT, 1930 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1931 const ArgDescriptor *Reg; 1932 const TargetRegisterClass *RC; 1933 LLT Ty; 1934 1935 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1936 if (!Reg) { 1937 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1938 // It's possible for a kernarg intrinsic call to appear in a kernel with 1939 // no allocated segment, in which case we do not add the user sgpr 1940 // argument, so just return null. 1941 return DAG.getConstant(0, SDLoc(), VT); 1942 } 1943 1944 // It's undefined behavior if a function marked with the amdgpu-no-* 1945 // attributes uses the corresponding intrinsic. 1946 return DAG.getUNDEF(VT); 1947 } 1948 1949 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1950 } 1951 1952 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1953 CallingConv::ID CallConv, 1954 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1955 FunctionType *FType, 1956 SIMachineFunctionInfo *Info) { 1957 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1958 const ISD::InputArg *Arg = &Ins[I]; 1959 1960 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1961 "vector type argument should have been split"); 1962 1963 // First check if it's a PS input addr. 1964 if (CallConv == CallingConv::AMDGPU_PS && 1965 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1966 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1967 1968 // Inconveniently only the first part of the split is marked as isSplit, 1969 // so skip to the end. We only want to increment PSInputNum once for the 1970 // entire split argument. 1971 if (Arg->Flags.isSplit()) { 1972 while (!Arg->Flags.isSplitEnd()) { 1973 assert((!Arg->VT.isVector() || 1974 Arg->VT.getScalarSizeInBits() == 16) && 1975 "unexpected vector split in ps argument type"); 1976 if (!SkipArg) 1977 Splits.push_back(*Arg); 1978 Arg = &Ins[++I]; 1979 } 1980 } 1981 1982 if (SkipArg) { 1983 // We can safely skip PS inputs. 1984 Skipped.set(Arg->getOrigArgIndex()); 1985 ++PSInputNum; 1986 continue; 1987 } 1988 1989 Info->markPSInputAllocated(PSInputNum); 1990 if (Arg->Used) 1991 Info->markPSInputEnabled(PSInputNum); 1992 1993 ++PSInputNum; 1994 } 1995 1996 Splits.push_back(*Arg); 1997 } 1998 } 1999 2000 // Allocate special inputs passed in VGPRs. 2001 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 2002 MachineFunction &MF, 2003 const SIRegisterInfo &TRI, 2004 SIMachineFunctionInfo &Info) const { 2005 const LLT S32 = LLT::scalar(32); 2006 MachineRegisterInfo &MRI = MF.getRegInfo(); 2007 2008 if (Info.hasWorkItemIDX()) { 2009 Register Reg = AMDGPU::VGPR0; 2010 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2011 2012 CCInfo.AllocateReg(Reg); 2013 unsigned Mask = (Subtarget->hasPackedTID() && 2014 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 2015 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2016 } 2017 2018 if (Info.hasWorkItemIDY()) { 2019 assert(Info.hasWorkItemIDX()); 2020 if (Subtarget->hasPackedTID()) { 2021 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2022 0x3ff << 10)); 2023 } else { 2024 unsigned Reg = AMDGPU::VGPR1; 2025 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2026 2027 CCInfo.AllocateReg(Reg); 2028 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 2029 } 2030 } 2031 2032 if (Info.hasWorkItemIDZ()) { 2033 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 2034 if (Subtarget->hasPackedTID()) { 2035 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2036 0x3ff << 20)); 2037 } else { 2038 unsigned Reg = AMDGPU::VGPR2; 2039 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2040 2041 CCInfo.AllocateReg(Reg); 2042 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 2043 } 2044 } 2045 } 2046 2047 // Try to allocate a VGPR at the end of the argument list, or if no argument 2048 // VGPRs are left allocating a stack slot. 2049 // If \p Mask is is given it indicates bitfield position in the register. 2050 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2051 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2052 ArgDescriptor Arg = ArgDescriptor()) { 2053 if (Arg.isSet()) 2054 return ArgDescriptor::createArg(Arg, Mask); 2055 2056 ArrayRef<MCPhysReg> ArgVGPRs 2057 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2058 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2059 if (RegIdx == ArgVGPRs.size()) { 2060 // Spill to stack required. 2061 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2062 2063 return ArgDescriptor::createStack(Offset, Mask); 2064 } 2065 2066 unsigned Reg = ArgVGPRs[RegIdx]; 2067 Reg = CCInfo.AllocateReg(Reg); 2068 assert(Reg != AMDGPU::NoRegister); 2069 2070 MachineFunction &MF = CCInfo.getMachineFunction(); 2071 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2072 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2073 return ArgDescriptor::createRegister(Reg, Mask); 2074 } 2075 2076 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2077 const TargetRegisterClass *RC, 2078 unsigned NumArgRegs) { 2079 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2080 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2081 if (RegIdx == ArgSGPRs.size()) 2082 report_fatal_error("ran out of SGPRs for arguments"); 2083 2084 unsigned Reg = ArgSGPRs[RegIdx]; 2085 Reg = CCInfo.AllocateReg(Reg); 2086 assert(Reg != AMDGPU::NoRegister); 2087 2088 MachineFunction &MF = CCInfo.getMachineFunction(); 2089 MF.addLiveIn(Reg, RC); 2090 return ArgDescriptor::createRegister(Reg); 2091 } 2092 2093 // If this has a fixed position, we still should allocate the register in the 2094 // CCInfo state. Technically we could get away with this for values passed 2095 // outside of the normal argument range. 2096 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2097 const TargetRegisterClass *RC, 2098 MCRegister Reg) { 2099 Reg = CCInfo.AllocateReg(Reg); 2100 assert(Reg != AMDGPU::NoRegister); 2101 MachineFunction &MF = CCInfo.getMachineFunction(); 2102 MF.addLiveIn(Reg, RC); 2103 } 2104 2105 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2106 if (Arg) { 2107 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2108 Arg.getRegister()); 2109 } else 2110 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2111 } 2112 2113 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2114 if (Arg) { 2115 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2116 Arg.getRegister()); 2117 } else 2118 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2119 } 2120 2121 /// Allocate implicit function VGPR arguments at the end of allocated user 2122 /// arguments. 2123 void SITargetLowering::allocateSpecialInputVGPRs( 2124 CCState &CCInfo, MachineFunction &MF, 2125 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2126 const unsigned Mask = 0x3ff; 2127 ArgDescriptor Arg; 2128 2129 if (Info.hasWorkItemIDX()) { 2130 Arg = allocateVGPR32Input(CCInfo, Mask); 2131 Info.setWorkItemIDX(Arg); 2132 } 2133 2134 if (Info.hasWorkItemIDY()) { 2135 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2136 Info.setWorkItemIDY(Arg); 2137 } 2138 2139 if (Info.hasWorkItemIDZ()) 2140 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2141 } 2142 2143 /// Allocate implicit function VGPR arguments in fixed registers. 2144 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2145 CCState &CCInfo, MachineFunction &MF, 2146 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2147 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2148 if (!Reg) 2149 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2150 2151 const unsigned Mask = 0x3ff; 2152 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2153 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2154 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2155 } 2156 2157 void SITargetLowering::allocateSpecialInputSGPRs( 2158 CCState &CCInfo, 2159 MachineFunction &MF, 2160 const SIRegisterInfo &TRI, 2161 SIMachineFunctionInfo &Info) const { 2162 auto &ArgInfo = Info.getArgInfo(); 2163 2164 // TODO: Unify handling with private memory pointers. 2165 if (Info.hasDispatchPtr()) 2166 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2167 2168 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2169 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2170 2171 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2172 // constant offset from the kernarg segment. 2173 if (Info.hasImplicitArgPtr()) 2174 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2175 2176 if (Info.hasDispatchID()) 2177 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2178 2179 // flat_scratch_init is not applicable for non-kernel functions. 2180 2181 if (Info.hasWorkGroupIDX()) 2182 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2183 2184 if (Info.hasWorkGroupIDY()) 2185 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2186 2187 if (Info.hasWorkGroupIDZ()) 2188 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2189 } 2190 2191 // Allocate special inputs passed in user SGPRs. 2192 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2193 MachineFunction &MF, 2194 const SIRegisterInfo &TRI, 2195 SIMachineFunctionInfo &Info) const { 2196 if (Info.hasImplicitBufferPtr()) { 2197 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2198 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2199 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2200 } 2201 2202 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2203 if (Info.hasPrivateSegmentBuffer()) { 2204 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2205 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2206 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2207 } 2208 2209 if (Info.hasDispatchPtr()) { 2210 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2211 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2212 CCInfo.AllocateReg(DispatchPtrReg); 2213 } 2214 2215 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2216 Register QueuePtrReg = Info.addQueuePtr(TRI); 2217 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2218 CCInfo.AllocateReg(QueuePtrReg); 2219 } 2220 2221 if (Info.hasKernargSegmentPtr()) { 2222 MachineRegisterInfo &MRI = MF.getRegInfo(); 2223 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2224 CCInfo.AllocateReg(InputPtrReg); 2225 2226 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2227 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2228 } 2229 2230 if (Info.hasDispatchID()) { 2231 Register DispatchIDReg = Info.addDispatchID(TRI); 2232 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2233 CCInfo.AllocateReg(DispatchIDReg); 2234 } 2235 2236 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2237 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2238 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2239 CCInfo.AllocateReg(FlatScratchInitReg); 2240 } 2241 2242 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2243 // these from the dispatch pointer. 2244 } 2245 2246 // Allocate special input registers that are initialized per-wave. 2247 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2248 MachineFunction &MF, 2249 SIMachineFunctionInfo &Info, 2250 CallingConv::ID CallConv, 2251 bool IsShader) const { 2252 if (Info.hasWorkGroupIDX()) { 2253 Register Reg = Info.addWorkGroupIDX(); 2254 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2255 CCInfo.AllocateReg(Reg); 2256 } 2257 2258 if (Info.hasWorkGroupIDY()) { 2259 Register Reg = Info.addWorkGroupIDY(); 2260 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2261 CCInfo.AllocateReg(Reg); 2262 } 2263 2264 if (Info.hasWorkGroupIDZ()) { 2265 Register Reg = Info.addWorkGroupIDZ(); 2266 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2267 CCInfo.AllocateReg(Reg); 2268 } 2269 2270 if (Info.hasWorkGroupInfo()) { 2271 Register Reg = Info.addWorkGroupInfo(); 2272 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2273 CCInfo.AllocateReg(Reg); 2274 } 2275 2276 if (Info.hasPrivateSegmentWaveByteOffset()) { 2277 // Scratch wave offset passed in system SGPR. 2278 unsigned PrivateSegmentWaveByteOffsetReg; 2279 2280 if (IsShader) { 2281 PrivateSegmentWaveByteOffsetReg = 2282 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2283 2284 // This is true if the scratch wave byte offset doesn't have a fixed 2285 // location. 2286 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2287 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2288 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2289 } 2290 } else 2291 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2292 2293 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2294 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2295 } 2296 } 2297 2298 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2299 MachineFunction &MF, 2300 const SIRegisterInfo &TRI, 2301 SIMachineFunctionInfo &Info) { 2302 // Now that we've figured out where the scratch register inputs are, see if 2303 // should reserve the arguments and use them directly. 2304 MachineFrameInfo &MFI = MF.getFrameInfo(); 2305 bool HasStackObjects = MFI.hasStackObjects(); 2306 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2307 2308 // Record that we know we have non-spill stack objects so we don't need to 2309 // check all stack objects later. 2310 if (HasStackObjects) 2311 Info.setHasNonSpillStackObjects(true); 2312 2313 // Everything live out of a block is spilled with fast regalloc, so it's 2314 // almost certain that spilling will be required. 2315 if (TM.getOptLevel() == CodeGenOpt::None) 2316 HasStackObjects = true; 2317 2318 // For now assume stack access is needed in any callee functions, so we need 2319 // the scratch registers to pass in. 2320 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2321 2322 if (!ST.enableFlatScratch()) { 2323 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2324 // If we have stack objects, we unquestionably need the private buffer 2325 // resource. For the Code Object V2 ABI, this will be the first 4 user 2326 // SGPR inputs. We can reserve those and use them directly. 2327 2328 Register PrivateSegmentBufferReg = 2329 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2330 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2331 } else { 2332 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2333 // We tentatively reserve the last registers (skipping the last registers 2334 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2335 // we'll replace these with the ones immediately after those which were 2336 // really allocated. In the prologue copies will be inserted from the 2337 // argument to these reserved registers. 2338 2339 // Without HSA, relocations are used for the scratch pointer and the 2340 // buffer resource setup is always inserted in the prologue. Scratch wave 2341 // offset is still in an input SGPR. 2342 Info.setScratchRSrcReg(ReservedBufferReg); 2343 } 2344 } 2345 2346 MachineRegisterInfo &MRI = MF.getRegInfo(); 2347 2348 // For entry functions we have to set up the stack pointer if we use it, 2349 // whereas non-entry functions get this "for free". This means there is no 2350 // intrinsic advantage to using S32 over S34 in cases where we do not have 2351 // calls but do need a frame pointer (i.e. if we are requested to have one 2352 // because frame pointer elimination is disabled). To keep things simple we 2353 // only ever use S32 as the call ABI stack pointer, and so using it does not 2354 // imply we need a separate frame pointer. 2355 // 2356 // Try to use s32 as the SP, but move it if it would interfere with input 2357 // arguments. This won't work with calls though. 2358 // 2359 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2360 // registers. 2361 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2362 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2363 } else { 2364 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2365 2366 if (MFI.hasCalls()) 2367 report_fatal_error("call in graphics shader with too many input SGPRs"); 2368 2369 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2370 if (!MRI.isLiveIn(Reg)) { 2371 Info.setStackPtrOffsetReg(Reg); 2372 break; 2373 } 2374 } 2375 2376 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2377 report_fatal_error("failed to find register for SP"); 2378 } 2379 2380 // hasFP should be accurate for entry functions even before the frame is 2381 // finalized, because it does not rely on the known stack size, only 2382 // properties like whether variable sized objects are present. 2383 if (ST.getFrameLowering()->hasFP(MF)) { 2384 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2385 } 2386 } 2387 2388 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2389 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2390 return !Info->isEntryFunction(); 2391 } 2392 2393 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2394 2395 } 2396 2397 void SITargetLowering::insertCopiesSplitCSR( 2398 MachineBasicBlock *Entry, 2399 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2400 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2401 2402 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2403 if (!IStart) 2404 return; 2405 2406 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2407 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2408 MachineBasicBlock::iterator MBBI = Entry->begin(); 2409 for (const MCPhysReg *I = IStart; *I; ++I) { 2410 const TargetRegisterClass *RC = nullptr; 2411 if (AMDGPU::SReg_64RegClass.contains(*I)) 2412 RC = &AMDGPU::SGPR_64RegClass; 2413 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2414 RC = &AMDGPU::SGPR_32RegClass; 2415 else 2416 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2417 2418 Register NewVR = MRI->createVirtualRegister(RC); 2419 // Create copy from CSR to a virtual register. 2420 Entry->addLiveIn(*I); 2421 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2422 .addReg(*I); 2423 2424 // Insert the copy-back instructions right before the terminator. 2425 for (auto *Exit : Exits) 2426 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2427 TII->get(TargetOpcode::COPY), *I) 2428 .addReg(NewVR); 2429 } 2430 } 2431 2432 SDValue SITargetLowering::LowerFormalArguments( 2433 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2434 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2435 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2436 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2437 2438 MachineFunction &MF = DAG.getMachineFunction(); 2439 const Function &Fn = MF.getFunction(); 2440 FunctionType *FType = MF.getFunction().getFunctionType(); 2441 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2442 2443 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2444 DiagnosticInfoUnsupported NoGraphicsHSA( 2445 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2446 DAG.getContext()->diagnose(NoGraphicsHSA); 2447 return DAG.getEntryNode(); 2448 } 2449 2450 Info->allocateModuleLDSGlobal(Fn.getParent()); 2451 2452 SmallVector<ISD::InputArg, 16> Splits; 2453 SmallVector<CCValAssign, 16> ArgLocs; 2454 BitVector Skipped(Ins.size()); 2455 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2456 *DAG.getContext()); 2457 2458 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2459 bool IsKernel = AMDGPU::isKernel(CallConv); 2460 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2461 2462 if (IsGraphics) { 2463 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2464 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2465 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2466 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2467 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2468 !Info->hasWorkItemIDZ()); 2469 } 2470 2471 if (CallConv == CallingConv::AMDGPU_PS) { 2472 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2473 2474 // At least one interpolation mode must be enabled or else the GPU will 2475 // hang. 2476 // 2477 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2478 // set PSInputAddr, the user wants to enable some bits after the compilation 2479 // based on run-time states. Since we can't know what the final PSInputEna 2480 // will look like, so we shouldn't do anything here and the user should take 2481 // responsibility for the correct programming. 2482 // 2483 // Otherwise, the following restrictions apply: 2484 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2485 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2486 // enabled too. 2487 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2488 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2489 CCInfo.AllocateReg(AMDGPU::VGPR0); 2490 CCInfo.AllocateReg(AMDGPU::VGPR1); 2491 Info->markPSInputAllocated(0); 2492 Info->markPSInputEnabled(0); 2493 } 2494 if (Subtarget->isAmdPalOS()) { 2495 // For isAmdPalOS, the user does not enable some bits after compilation 2496 // based on run-time states; the register values being generated here are 2497 // the final ones set in hardware. Therefore we need to apply the 2498 // workaround to PSInputAddr and PSInputEnable together. (The case where 2499 // a bit is set in PSInputAddr but not PSInputEnable is where the 2500 // frontend set up an input arg for a particular interpolation mode, but 2501 // nothing uses that input arg. Really we should have an earlier pass 2502 // that removes such an arg.) 2503 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2504 if ((PsInputBits & 0x7F) == 0 || 2505 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2506 Info->markPSInputEnabled( 2507 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2508 } 2509 } else if (IsKernel) { 2510 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2511 } else { 2512 Splits.append(Ins.begin(), Ins.end()); 2513 } 2514 2515 if (IsEntryFunc) { 2516 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2517 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2518 } else if (!IsGraphics) { 2519 // For the fixed ABI, pass workitem IDs in the last argument register. 2520 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2521 } 2522 2523 if (IsKernel) { 2524 analyzeFormalArgumentsCompute(CCInfo, Ins); 2525 } else { 2526 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2527 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2528 } 2529 2530 SmallVector<SDValue, 16> Chains; 2531 2532 // FIXME: This is the minimum kernel argument alignment. We should improve 2533 // this to the maximum alignment of the arguments. 2534 // 2535 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2536 // kern arg offset. 2537 const Align KernelArgBaseAlign = Align(16); 2538 2539 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2540 const ISD::InputArg &Arg = Ins[i]; 2541 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2542 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2543 continue; 2544 } 2545 2546 CCValAssign &VA = ArgLocs[ArgIdx++]; 2547 MVT VT = VA.getLocVT(); 2548 2549 if (IsEntryFunc && VA.isMemLoc()) { 2550 VT = Ins[i].VT; 2551 EVT MemVT = VA.getLocVT(); 2552 2553 const uint64_t Offset = VA.getLocMemOffset(); 2554 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2555 2556 if (Arg.Flags.isByRef()) { 2557 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2558 2559 const GCNTargetMachine &TM = 2560 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2561 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2562 Arg.Flags.getPointerAddrSpace())) { 2563 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2564 Arg.Flags.getPointerAddrSpace()); 2565 } 2566 2567 InVals.push_back(Ptr); 2568 continue; 2569 } 2570 2571 SDValue Arg = lowerKernargMemParameter( 2572 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2573 Chains.push_back(Arg.getValue(1)); 2574 2575 auto *ParamTy = 2576 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2577 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2578 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2579 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2580 // On SI local pointers are just offsets into LDS, so they are always 2581 // less than 16-bits. On CI and newer they could potentially be 2582 // real pointers, so we can't guarantee their size. 2583 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2584 DAG.getValueType(MVT::i16)); 2585 } 2586 2587 InVals.push_back(Arg); 2588 continue; 2589 } else if (!IsEntryFunc && VA.isMemLoc()) { 2590 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2591 InVals.push_back(Val); 2592 if (!Arg.Flags.isByVal()) 2593 Chains.push_back(Val.getValue(1)); 2594 continue; 2595 } 2596 2597 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2598 2599 Register Reg = VA.getLocReg(); 2600 const TargetRegisterClass *RC = nullptr; 2601 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2602 RC = &AMDGPU::VGPR_32RegClass; 2603 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2604 RC = &AMDGPU::SGPR_32RegClass; 2605 else 2606 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2607 EVT ValVT = VA.getValVT(); 2608 2609 Reg = MF.addLiveIn(Reg, RC); 2610 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2611 2612 if (Arg.Flags.isSRet()) { 2613 // The return object should be reasonably addressable. 2614 2615 // FIXME: This helps when the return is a real sret. If it is a 2616 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2617 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2618 unsigned NumBits 2619 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2620 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2621 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2622 } 2623 2624 // If this is an 8 or 16-bit value, it is really passed promoted 2625 // to 32 bits. Insert an assert[sz]ext to capture this, then 2626 // truncate to the right size. 2627 switch (VA.getLocInfo()) { 2628 case CCValAssign::Full: 2629 break; 2630 case CCValAssign::BCvt: 2631 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2632 break; 2633 case CCValAssign::SExt: 2634 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2635 DAG.getValueType(ValVT)); 2636 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2637 break; 2638 case CCValAssign::ZExt: 2639 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2640 DAG.getValueType(ValVT)); 2641 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2642 break; 2643 case CCValAssign::AExt: 2644 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2645 break; 2646 default: 2647 llvm_unreachable("Unknown loc info!"); 2648 } 2649 2650 InVals.push_back(Val); 2651 } 2652 2653 // Start adding system SGPRs. 2654 if (IsEntryFunc) { 2655 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2656 } else { 2657 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2658 if (!IsGraphics) 2659 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2660 } 2661 2662 auto &ArgUsageInfo = 2663 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2664 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2665 2666 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2667 Info->setBytesInStackArgArea(StackArgSize); 2668 2669 return Chains.empty() ? Chain : 2670 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2671 } 2672 2673 // TODO: If return values can't fit in registers, we should return as many as 2674 // possible in registers before passing on stack. 2675 bool SITargetLowering::CanLowerReturn( 2676 CallingConv::ID CallConv, 2677 MachineFunction &MF, bool IsVarArg, 2678 const SmallVectorImpl<ISD::OutputArg> &Outs, 2679 LLVMContext &Context) const { 2680 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2681 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2682 // for shaders. Vector types should be explicitly handled by CC. 2683 if (AMDGPU::isEntryFunctionCC(CallConv)) 2684 return true; 2685 2686 SmallVector<CCValAssign, 16> RVLocs; 2687 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2688 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2689 } 2690 2691 SDValue 2692 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2693 bool isVarArg, 2694 const SmallVectorImpl<ISD::OutputArg> &Outs, 2695 const SmallVectorImpl<SDValue> &OutVals, 2696 const SDLoc &DL, SelectionDAG &DAG) const { 2697 MachineFunction &MF = DAG.getMachineFunction(); 2698 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2699 2700 if (AMDGPU::isKernel(CallConv)) { 2701 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2702 OutVals, DL, DAG); 2703 } 2704 2705 bool IsShader = AMDGPU::isShader(CallConv); 2706 2707 Info->setIfReturnsVoid(Outs.empty()); 2708 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2709 2710 // CCValAssign - represent the assignment of the return value to a location. 2711 SmallVector<CCValAssign, 48> RVLocs; 2712 SmallVector<ISD::OutputArg, 48> Splits; 2713 2714 // CCState - Info about the registers and stack slots. 2715 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2716 *DAG.getContext()); 2717 2718 // Analyze outgoing return values. 2719 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2720 2721 SDValue Flag; 2722 SmallVector<SDValue, 48> RetOps; 2723 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2724 2725 // Copy the result values into the output registers. 2726 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2727 ++I, ++RealRVLocIdx) { 2728 CCValAssign &VA = RVLocs[I]; 2729 assert(VA.isRegLoc() && "Can only return in registers!"); 2730 // TODO: Partially return in registers if return values don't fit. 2731 SDValue Arg = OutVals[RealRVLocIdx]; 2732 2733 // Copied from other backends. 2734 switch (VA.getLocInfo()) { 2735 case CCValAssign::Full: 2736 break; 2737 case CCValAssign::BCvt: 2738 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2739 break; 2740 case CCValAssign::SExt: 2741 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2742 break; 2743 case CCValAssign::ZExt: 2744 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2745 break; 2746 case CCValAssign::AExt: 2747 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2748 break; 2749 default: 2750 llvm_unreachable("Unknown loc info!"); 2751 } 2752 2753 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2754 Flag = Chain.getValue(1); 2755 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2756 } 2757 2758 // FIXME: Does sret work properly? 2759 if (!Info->isEntryFunction()) { 2760 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2761 const MCPhysReg *I = 2762 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2763 if (I) { 2764 for (; *I; ++I) { 2765 if (AMDGPU::SReg_64RegClass.contains(*I)) 2766 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2767 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2768 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2769 else 2770 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2771 } 2772 } 2773 } 2774 2775 // Update chain and glue. 2776 RetOps[0] = Chain; 2777 if (Flag.getNode()) 2778 RetOps.push_back(Flag); 2779 2780 unsigned Opc = AMDGPUISD::ENDPGM; 2781 if (!IsWaveEnd) 2782 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2783 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2784 } 2785 2786 SDValue SITargetLowering::LowerCallResult( 2787 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2788 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2789 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2790 SDValue ThisVal) const { 2791 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2792 2793 // Assign locations to each value returned by this call. 2794 SmallVector<CCValAssign, 16> RVLocs; 2795 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2796 *DAG.getContext()); 2797 CCInfo.AnalyzeCallResult(Ins, RetCC); 2798 2799 // Copy all of the result registers out of their specified physreg. 2800 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2801 CCValAssign VA = RVLocs[i]; 2802 SDValue Val; 2803 2804 if (VA.isRegLoc()) { 2805 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2806 Chain = Val.getValue(1); 2807 InFlag = Val.getValue(2); 2808 } else if (VA.isMemLoc()) { 2809 report_fatal_error("TODO: return values in memory"); 2810 } else 2811 llvm_unreachable("unknown argument location type"); 2812 2813 switch (VA.getLocInfo()) { 2814 case CCValAssign::Full: 2815 break; 2816 case CCValAssign::BCvt: 2817 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2818 break; 2819 case CCValAssign::ZExt: 2820 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2821 DAG.getValueType(VA.getValVT())); 2822 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2823 break; 2824 case CCValAssign::SExt: 2825 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2826 DAG.getValueType(VA.getValVT())); 2827 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2828 break; 2829 case CCValAssign::AExt: 2830 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2831 break; 2832 default: 2833 llvm_unreachable("Unknown loc info!"); 2834 } 2835 2836 InVals.push_back(Val); 2837 } 2838 2839 return Chain; 2840 } 2841 2842 // Add code to pass special inputs required depending on used features separate 2843 // from the explicit user arguments present in the IR. 2844 void SITargetLowering::passSpecialInputs( 2845 CallLoweringInfo &CLI, 2846 CCState &CCInfo, 2847 const SIMachineFunctionInfo &Info, 2848 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2849 SmallVectorImpl<SDValue> &MemOpChains, 2850 SDValue Chain) const { 2851 // If we don't have a call site, this was a call inserted by 2852 // legalization. These can never use special inputs. 2853 if (!CLI.CB) 2854 return; 2855 2856 SelectionDAG &DAG = CLI.DAG; 2857 const SDLoc &DL = CLI.DL; 2858 const Function &F = DAG.getMachineFunction().getFunction(); 2859 2860 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2861 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2862 2863 const AMDGPUFunctionArgInfo *CalleeArgInfo 2864 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2865 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2866 auto &ArgUsageInfo = 2867 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2868 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2869 } 2870 2871 // TODO: Unify with private memory register handling. This is complicated by 2872 // the fact that at least in kernels, the input argument is not necessarily 2873 // in the same location as the input. 2874 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2875 StringLiteral> ImplicitAttrs[] = { 2876 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2877 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2878 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2879 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2880 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2881 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2882 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2883 }; 2884 2885 for (auto Attr : ImplicitAttrs) { 2886 const ArgDescriptor *OutgoingArg; 2887 const TargetRegisterClass *ArgRC; 2888 LLT ArgTy; 2889 2890 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2891 2892 // If the callee does not use the attribute value, skip copying the value. 2893 if (CLI.CB->hasFnAttr(Attr.second)) 2894 continue; 2895 2896 std::tie(OutgoingArg, ArgRC, ArgTy) = 2897 CalleeArgInfo->getPreloadedValue(InputID); 2898 if (!OutgoingArg) 2899 continue; 2900 2901 const ArgDescriptor *IncomingArg; 2902 const TargetRegisterClass *IncomingArgRC; 2903 LLT Ty; 2904 std::tie(IncomingArg, IncomingArgRC, Ty) = 2905 CallerArgInfo.getPreloadedValue(InputID); 2906 assert(IncomingArgRC == ArgRC); 2907 2908 // All special arguments are ints for now. 2909 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2910 SDValue InputReg; 2911 2912 if (IncomingArg) { 2913 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2914 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2915 // The implicit arg ptr is special because it doesn't have a corresponding 2916 // input for kernels, and is computed from the kernarg segment pointer. 2917 InputReg = getImplicitArgPtr(DAG, DL); 2918 } else { 2919 // We may have proven the input wasn't needed, although the ABI is 2920 // requiring it. We just need to allocate the register appropriately. 2921 InputReg = DAG.getUNDEF(ArgVT); 2922 } 2923 2924 if (OutgoingArg->isRegister()) { 2925 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2926 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2927 report_fatal_error("failed to allocate implicit input argument"); 2928 } else { 2929 unsigned SpecialArgOffset = 2930 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2931 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2932 SpecialArgOffset); 2933 MemOpChains.push_back(ArgStore); 2934 } 2935 } 2936 2937 // Pack workitem IDs into a single register or pass it as is if already 2938 // packed. 2939 const ArgDescriptor *OutgoingArg; 2940 const TargetRegisterClass *ArgRC; 2941 LLT Ty; 2942 2943 std::tie(OutgoingArg, ArgRC, Ty) = 2944 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2945 if (!OutgoingArg) 2946 std::tie(OutgoingArg, ArgRC, Ty) = 2947 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2948 if (!OutgoingArg) 2949 std::tie(OutgoingArg, ArgRC, Ty) = 2950 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2951 if (!OutgoingArg) 2952 return; 2953 2954 const ArgDescriptor *IncomingArgX = std::get<0>( 2955 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2956 const ArgDescriptor *IncomingArgY = std::get<0>( 2957 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2958 const ArgDescriptor *IncomingArgZ = std::get<0>( 2959 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2960 2961 SDValue InputReg; 2962 SDLoc SL; 2963 2964 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2965 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2966 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2967 2968 // If incoming ids are not packed we need to pack them. 2969 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2970 NeedWorkItemIDX) { 2971 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2972 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2973 } else { 2974 InputReg = DAG.getConstant(0, DL, MVT::i32); 2975 } 2976 } 2977 2978 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2979 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2980 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2981 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2982 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2983 InputReg = InputReg.getNode() ? 2984 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2985 } 2986 2987 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2988 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2989 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2990 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2991 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2992 InputReg = InputReg.getNode() ? 2993 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2994 } 2995 2996 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2997 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2998 // We're in a situation where the outgoing function requires the workitem 2999 // ID, but the calling function does not have it (e.g a graphics function 3000 // calling a C calling convention function). This is illegal, but we need 3001 // to produce something. 3002 InputReg = DAG.getUNDEF(MVT::i32); 3003 } else { 3004 // Workitem ids are already packed, any of present incoming arguments 3005 // will carry all required fields. 3006 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 3007 IncomingArgX ? *IncomingArgX : 3008 IncomingArgY ? *IncomingArgY : 3009 *IncomingArgZ, ~0u); 3010 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 3011 } 3012 } 3013 3014 if (OutgoingArg->isRegister()) { 3015 if (InputReg) 3016 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 3017 3018 CCInfo.AllocateReg(OutgoingArg->getRegister()); 3019 } else { 3020 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 3021 if (InputReg) { 3022 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 3023 SpecialArgOffset); 3024 MemOpChains.push_back(ArgStore); 3025 } 3026 } 3027 } 3028 3029 static bool canGuaranteeTCO(CallingConv::ID CC) { 3030 return CC == CallingConv::Fast; 3031 } 3032 3033 /// Return true if we might ever do TCO for calls with this calling convention. 3034 static bool mayTailCallThisCC(CallingConv::ID CC) { 3035 switch (CC) { 3036 case CallingConv::C: 3037 case CallingConv::AMDGPU_Gfx: 3038 return true; 3039 default: 3040 return canGuaranteeTCO(CC); 3041 } 3042 } 3043 3044 bool SITargetLowering::isEligibleForTailCallOptimization( 3045 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 3046 const SmallVectorImpl<ISD::OutputArg> &Outs, 3047 const SmallVectorImpl<SDValue> &OutVals, 3048 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3049 if (!mayTailCallThisCC(CalleeCC)) 3050 return false; 3051 3052 // For a divergent call target, we need to do a waterfall loop over the 3053 // possible callees which precludes us from using a simple jump. 3054 if (Callee->isDivergent()) 3055 return false; 3056 3057 MachineFunction &MF = DAG.getMachineFunction(); 3058 const Function &CallerF = MF.getFunction(); 3059 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3060 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3061 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3062 3063 // Kernels aren't callable, and don't have a live in return address so it 3064 // doesn't make sense to do a tail call with entry functions. 3065 if (!CallerPreserved) 3066 return false; 3067 3068 bool CCMatch = CallerCC == CalleeCC; 3069 3070 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3071 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3072 return true; 3073 return false; 3074 } 3075 3076 // TODO: Can we handle var args? 3077 if (IsVarArg) 3078 return false; 3079 3080 for (const Argument &Arg : CallerF.args()) { 3081 if (Arg.hasByValAttr()) 3082 return false; 3083 } 3084 3085 LLVMContext &Ctx = *DAG.getContext(); 3086 3087 // Check that the call results are passed in the same way. 3088 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3089 CCAssignFnForCall(CalleeCC, IsVarArg), 3090 CCAssignFnForCall(CallerCC, IsVarArg))) 3091 return false; 3092 3093 // The callee has to preserve all registers the caller needs to preserve. 3094 if (!CCMatch) { 3095 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3096 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3097 return false; 3098 } 3099 3100 // Nothing more to check if the callee is taking no arguments. 3101 if (Outs.empty()) 3102 return true; 3103 3104 SmallVector<CCValAssign, 16> ArgLocs; 3105 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3106 3107 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3108 3109 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3110 // If the stack arguments for this call do not fit into our own save area then 3111 // the call cannot be made tail. 3112 // TODO: Is this really necessary? 3113 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3114 return false; 3115 3116 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3117 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3118 } 3119 3120 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3121 if (!CI->isTailCall()) 3122 return false; 3123 3124 const Function *ParentFn = CI->getParent()->getParent(); 3125 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3126 return false; 3127 return true; 3128 } 3129 3130 // The wave scratch offset register is used as the global base pointer. 3131 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3132 SmallVectorImpl<SDValue> &InVals) const { 3133 SelectionDAG &DAG = CLI.DAG; 3134 const SDLoc &DL = CLI.DL; 3135 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3136 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3137 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3138 SDValue Chain = CLI.Chain; 3139 SDValue Callee = CLI.Callee; 3140 bool &IsTailCall = CLI.IsTailCall; 3141 CallingConv::ID CallConv = CLI.CallConv; 3142 bool IsVarArg = CLI.IsVarArg; 3143 bool IsSibCall = false; 3144 bool IsThisReturn = false; 3145 MachineFunction &MF = DAG.getMachineFunction(); 3146 3147 if (Callee.isUndef() || isNullConstant(Callee)) { 3148 if (!CLI.IsTailCall) { 3149 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3150 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3151 } 3152 3153 return Chain; 3154 } 3155 3156 if (IsVarArg) { 3157 return lowerUnhandledCall(CLI, InVals, 3158 "unsupported call to variadic function "); 3159 } 3160 3161 if (!CLI.CB) 3162 report_fatal_error("unsupported libcall legalization"); 3163 3164 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3165 return lowerUnhandledCall(CLI, InVals, 3166 "unsupported required tail call to function "); 3167 } 3168 3169 if (AMDGPU::isShader(CallConv)) { 3170 // Note the issue is with the CC of the called function, not of the call 3171 // itself. 3172 return lowerUnhandledCall(CLI, InVals, 3173 "unsupported call to a shader function "); 3174 } 3175 3176 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3177 CallConv != CallingConv::AMDGPU_Gfx) { 3178 // Only allow calls with specific calling conventions. 3179 return lowerUnhandledCall(CLI, InVals, 3180 "unsupported calling convention for call from " 3181 "graphics shader of function "); 3182 } 3183 3184 if (IsTailCall) { 3185 IsTailCall = isEligibleForTailCallOptimization( 3186 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3187 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3188 report_fatal_error("failed to perform tail call elimination on a call " 3189 "site marked musttail"); 3190 } 3191 3192 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3193 3194 // A sibling call is one where we're under the usual C ABI and not planning 3195 // to change that but can still do a tail call: 3196 if (!TailCallOpt && IsTailCall) 3197 IsSibCall = true; 3198 3199 if (IsTailCall) 3200 ++NumTailCalls; 3201 } 3202 3203 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3204 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3205 SmallVector<SDValue, 8> MemOpChains; 3206 3207 // Analyze operands of the call, assigning locations to each operand. 3208 SmallVector<CCValAssign, 16> ArgLocs; 3209 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3210 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3211 3212 if (CallConv != CallingConv::AMDGPU_Gfx) { 3213 // With a fixed ABI, allocate fixed registers before user arguments. 3214 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3215 } 3216 3217 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3218 3219 // Get a count of how many bytes are to be pushed on the stack. 3220 unsigned NumBytes = CCInfo.getNextStackOffset(); 3221 3222 if (IsSibCall) { 3223 // Since we're not changing the ABI to make this a tail call, the memory 3224 // operands are already available in the caller's incoming argument space. 3225 NumBytes = 0; 3226 } 3227 3228 // FPDiff is the byte offset of the call's argument area from the callee's. 3229 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3230 // by this amount for a tail call. In a sibling call it must be 0 because the 3231 // caller will deallocate the entire stack and the callee still expects its 3232 // arguments to begin at SP+0. Completely unused for non-tail calls. 3233 int32_t FPDiff = 0; 3234 MachineFrameInfo &MFI = MF.getFrameInfo(); 3235 3236 // Adjust the stack pointer for the new arguments... 3237 // These operations are automatically eliminated by the prolog/epilog pass 3238 if (!IsSibCall) { 3239 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3240 3241 if (!Subtarget->enableFlatScratch()) { 3242 SmallVector<SDValue, 4> CopyFromChains; 3243 3244 // In the HSA case, this should be an identity copy. 3245 SDValue ScratchRSrcReg 3246 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3247 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3248 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3249 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3250 } 3251 } 3252 3253 MVT PtrVT = MVT::i32; 3254 3255 // Walk the register/memloc assignments, inserting copies/loads. 3256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3257 CCValAssign &VA = ArgLocs[i]; 3258 SDValue Arg = OutVals[i]; 3259 3260 // Promote the value if needed. 3261 switch (VA.getLocInfo()) { 3262 case CCValAssign::Full: 3263 break; 3264 case CCValAssign::BCvt: 3265 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3266 break; 3267 case CCValAssign::ZExt: 3268 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3269 break; 3270 case CCValAssign::SExt: 3271 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3272 break; 3273 case CCValAssign::AExt: 3274 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3275 break; 3276 case CCValAssign::FPExt: 3277 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3278 break; 3279 default: 3280 llvm_unreachable("Unknown loc info!"); 3281 } 3282 3283 if (VA.isRegLoc()) { 3284 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3285 } else { 3286 assert(VA.isMemLoc()); 3287 3288 SDValue DstAddr; 3289 MachinePointerInfo DstInfo; 3290 3291 unsigned LocMemOffset = VA.getLocMemOffset(); 3292 int32_t Offset = LocMemOffset; 3293 3294 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3295 MaybeAlign Alignment; 3296 3297 if (IsTailCall) { 3298 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3299 unsigned OpSize = Flags.isByVal() ? 3300 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3301 3302 // FIXME: We can have better than the minimum byval required alignment. 3303 Alignment = 3304 Flags.isByVal() 3305 ? Flags.getNonZeroByValAlign() 3306 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3307 3308 Offset = Offset + FPDiff; 3309 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3310 3311 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3312 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3313 3314 // Make sure any stack arguments overlapping with where we're storing 3315 // are loaded before this eventual operation. Otherwise they'll be 3316 // clobbered. 3317 3318 // FIXME: Why is this really necessary? This seems to just result in a 3319 // lot of code to copy the stack and write them back to the same 3320 // locations, which are supposed to be immutable? 3321 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3322 } else { 3323 // Stores to the argument stack area are relative to the stack pointer. 3324 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3325 MVT::i32); 3326 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3327 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3328 Alignment = 3329 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3330 } 3331 3332 if (Outs[i].Flags.isByVal()) { 3333 SDValue SizeNode = 3334 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3335 SDValue Cpy = 3336 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3337 Outs[i].Flags.getNonZeroByValAlign(), 3338 /*isVol = */ false, /*AlwaysInline = */ true, 3339 /*isTailCall = */ false, DstInfo, 3340 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3341 3342 MemOpChains.push_back(Cpy); 3343 } else { 3344 SDValue Store = 3345 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3346 MemOpChains.push_back(Store); 3347 } 3348 } 3349 } 3350 3351 if (!MemOpChains.empty()) 3352 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3353 3354 // Build a sequence of copy-to-reg nodes chained together with token chain 3355 // and flag operands which copy the outgoing args into the appropriate regs. 3356 SDValue InFlag; 3357 for (auto &RegToPass : RegsToPass) { 3358 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3359 RegToPass.second, InFlag); 3360 InFlag = Chain.getValue(1); 3361 } 3362 3363 3364 // We don't usually want to end the call-sequence here because we would tidy 3365 // the frame up *after* the call, however in the ABI-changing tail-call case 3366 // we've carefully laid out the parameters so that when sp is reset they'll be 3367 // in the correct location. 3368 if (IsTailCall && !IsSibCall) { 3369 Chain = DAG.getCALLSEQ_END(Chain, 3370 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3371 DAG.getTargetConstant(0, DL, MVT::i32), 3372 InFlag, DL); 3373 InFlag = Chain.getValue(1); 3374 } 3375 3376 std::vector<SDValue> Ops; 3377 Ops.push_back(Chain); 3378 Ops.push_back(Callee); 3379 // Add a redundant copy of the callee global which will not be legalized, as 3380 // we need direct access to the callee later. 3381 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3382 const GlobalValue *GV = GSD->getGlobal(); 3383 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3384 } else { 3385 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3386 } 3387 3388 if (IsTailCall) { 3389 // Each tail call may have to adjust the stack by a different amount, so 3390 // this information must travel along with the operation for eventual 3391 // consumption by emitEpilogue. 3392 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3393 } 3394 3395 // Add argument registers to the end of the list so that they are known live 3396 // into the call. 3397 for (auto &RegToPass : RegsToPass) { 3398 Ops.push_back(DAG.getRegister(RegToPass.first, 3399 RegToPass.second.getValueType())); 3400 } 3401 3402 // Add a register mask operand representing the call-preserved registers. 3403 3404 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3405 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3406 assert(Mask && "Missing call preserved mask for calling convention"); 3407 Ops.push_back(DAG.getRegisterMask(Mask)); 3408 3409 if (InFlag.getNode()) 3410 Ops.push_back(InFlag); 3411 3412 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3413 3414 // If we're doing a tall call, use a TC_RETURN here rather than an 3415 // actual call instruction. 3416 if (IsTailCall) { 3417 MFI.setHasTailCall(); 3418 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3419 } 3420 3421 // Returns a chain and a flag for retval copy to use. 3422 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3423 Chain = Call.getValue(0); 3424 InFlag = Call.getValue(1); 3425 3426 uint64_t CalleePopBytes = NumBytes; 3427 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3428 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3429 InFlag, DL); 3430 if (!Ins.empty()) 3431 InFlag = Chain.getValue(1); 3432 3433 // Handle result values, copying them out of physregs into vregs that we 3434 // return. 3435 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3436 InVals, IsThisReturn, 3437 IsThisReturn ? OutVals[0] : SDValue()); 3438 } 3439 3440 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3441 // except for applying the wave size scale to the increment amount. 3442 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3443 SDValue Op, SelectionDAG &DAG) const { 3444 const MachineFunction &MF = DAG.getMachineFunction(); 3445 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3446 3447 SDLoc dl(Op); 3448 EVT VT = Op.getValueType(); 3449 SDValue Tmp1 = Op; 3450 SDValue Tmp2 = Op.getValue(1); 3451 SDValue Tmp3 = Op.getOperand(2); 3452 SDValue Chain = Tmp1.getOperand(0); 3453 3454 Register SPReg = Info->getStackPtrOffsetReg(); 3455 3456 // Chain the dynamic stack allocation so that it doesn't modify the stack 3457 // pointer when other instructions are using the stack. 3458 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3459 3460 SDValue Size = Tmp2.getOperand(1); 3461 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3462 Chain = SP.getValue(1); 3463 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3464 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3465 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3466 unsigned Opc = 3467 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3468 ISD::ADD : ISD::SUB; 3469 3470 SDValue ScaledSize = DAG.getNode( 3471 ISD::SHL, dl, VT, Size, 3472 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3473 3474 Align StackAlign = TFL->getStackAlign(); 3475 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3476 if (Alignment && *Alignment > StackAlign) { 3477 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3478 DAG.getConstant(-(uint64_t)Alignment->value() 3479 << ST.getWavefrontSizeLog2(), 3480 dl, VT)); 3481 } 3482 3483 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3484 Tmp2 = DAG.getCALLSEQ_END( 3485 Chain, DAG.getIntPtrConstant(0, dl, true), 3486 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3487 3488 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3489 } 3490 3491 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3492 SelectionDAG &DAG) const { 3493 // We only handle constant sizes here to allow non-entry block, static sized 3494 // allocas. A truly dynamic value is more difficult to support because we 3495 // don't know if the size value is uniform or not. If the size isn't uniform, 3496 // we would need to do a wave reduction to get the maximum size to know how 3497 // much to increment the uniform stack pointer. 3498 SDValue Size = Op.getOperand(1); 3499 if (isa<ConstantSDNode>(Size)) 3500 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3501 3502 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3503 } 3504 3505 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3506 const MachineFunction &MF) const { 3507 Register Reg = StringSwitch<Register>(RegName) 3508 .Case("m0", AMDGPU::M0) 3509 .Case("exec", AMDGPU::EXEC) 3510 .Case("exec_lo", AMDGPU::EXEC_LO) 3511 .Case("exec_hi", AMDGPU::EXEC_HI) 3512 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3513 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3514 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3515 .Default(Register()); 3516 3517 if (Reg == AMDGPU::NoRegister) { 3518 report_fatal_error(Twine("invalid register name \"" 3519 + StringRef(RegName) + "\".")); 3520 3521 } 3522 3523 if (!Subtarget->hasFlatScrRegister() && 3524 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3525 report_fatal_error(Twine("invalid register \"" 3526 + StringRef(RegName) + "\" for subtarget.")); 3527 } 3528 3529 switch (Reg) { 3530 case AMDGPU::M0: 3531 case AMDGPU::EXEC_LO: 3532 case AMDGPU::EXEC_HI: 3533 case AMDGPU::FLAT_SCR_LO: 3534 case AMDGPU::FLAT_SCR_HI: 3535 if (VT.getSizeInBits() == 32) 3536 return Reg; 3537 break; 3538 case AMDGPU::EXEC: 3539 case AMDGPU::FLAT_SCR: 3540 if (VT.getSizeInBits() == 64) 3541 return Reg; 3542 break; 3543 default: 3544 llvm_unreachable("missing register type checking"); 3545 } 3546 3547 report_fatal_error(Twine("invalid type for register \"" 3548 + StringRef(RegName) + "\".")); 3549 } 3550 3551 // If kill is not the last instruction, split the block so kill is always a 3552 // proper terminator. 3553 MachineBasicBlock * 3554 SITargetLowering::splitKillBlock(MachineInstr &MI, 3555 MachineBasicBlock *BB) const { 3556 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3557 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3558 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3559 return SplitBB; 3560 } 3561 3562 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3563 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3564 // be the first instruction in the remainder block. 3565 // 3566 /// \returns { LoopBody, Remainder } 3567 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3568 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3569 MachineFunction *MF = MBB.getParent(); 3570 MachineBasicBlock::iterator I(&MI); 3571 3572 // To insert the loop we need to split the block. Move everything after this 3573 // point to a new block, and insert a new empty block between the two. 3574 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3575 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3576 MachineFunction::iterator MBBI(MBB); 3577 ++MBBI; 3578 3579 MF->insert(MBBI, LoopBB); 3580 MF->insert(MBBI, RemainderBB); 3581 3582 LoopBB->addSuccessor(LoopBB); 3583 LoopBB->addSuccessor(RemainderBB); 3584 3585 // Move the rest of the block into a new block. 3586 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3587 3588 if (InstInLoop) { 3589 auto Next = std::next(I); 3590 3591 // Move instruction to loop body. 3592 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3593 3594 // Move the rest of the block. 3595 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3596 } else { 3597 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3598 } 3599 3600 MBB.addSuccessor(LoopBB); 3601 3602 return std::make_pair(LoopBB, RemainderBB); 3603 } 3604 3605 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3606 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3607 MachineBasicBlock *MBB = MI.getParent(); 3608 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3609 auto I = MI.getIterator(); 3610 auto E = std::next(I); 3611 3612 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3613 .addImm(0); 3614 3615 MIBundleBuilder Bundler(*MBB, I, E); 3616 finalizeBundle(*MBB, Bundler.begin()); 3617 } 3618 3619 MachineBasicBlock * 3620 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3621 MachineBasicBlock *BB) const { 3622 const DebugLoc &DL = MI.getDebugLoc(); 3623 3624 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3625 3626 MachineBasicBlock *LoopBB; 3627 MachineBasicBlock *RemainderBB; 3628 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3629 3630 // Apparently kill flags are only valid if the def is in the same block? 3631 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3632 Src->setIsKill(false); 3633 3634 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3635 3636 MachineBasicBlock::iterator I = LoopBB->end(); 3637 3638 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3639 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3640 3641 // Clear TRAP_STS.MEM_VIOL 3642 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3643 .addImm(0) 3644 .addImm(EncodedReg); 3645 3646 bundleInstWithWaitcnt(MI); 3647 3648 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3649 3650 // Load and check TRAP_STS.MEM_VIOL 3651 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3652 .addImm(EncodedReg); 3653 3654 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3655 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3656 .addReg(Reg, RegState::Kill) 3657 .addImm(0); 3658 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3659 .addMBB(LoopBB); 3660 3661 return RemainderBB; 3662 } 3663 3664 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3665 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3666 // will only do one iteration. In the worst case, this will loop 64 times. 3667 // 3668 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3669 static MachineBasicBlock::iterator 3670 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3671 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3672 const DebugLoc &DL, const MachineOperand &Idx, 3673 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3674 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3675 Register &SGPRIdxReg) { 3676 3677 MachineFunction *MF = OrigBB.getParent(); 3678 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3679 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3680 MachineBasicBlock::iterator I = LoopBB.begin(); 3681 3682 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3683 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3684 Register NewExec = MRI.createVirtualRegister(BoolRC); 3685 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3686 Register CondReg = MRI.createVirtualRegister(BoolRC); 3687 3688 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3689 .addReg(InitReg) 3690 .addMBB(&OrigBB) 3691 .addReg(ResultReg) 3692 .addMBB(&LoopBB); 3693 3694 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3695 .addReg(InitSaveExecReg) 3696 .addMBB(&OrigBB) 3697 .addReg(NewExec) 3698 .addMBB(&LoopBB); 3699 3700 // Read the next variant <- also loop target. 3701 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3702 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3703 3704 // Compare the just read M0 value to all possible Idx values. 3705 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3706 .addReg(CurrentIdxReg) 3707 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3708 3709 // Update EXEC, save the original EXEC value to VCC. 3710 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3711 : AMDGPU::S_AND_SAVEEXEC_B64), 3712 NewExec) 3713 .addReg(CondReg, RegState::Kill); 3714 3715 MRI.setSimpleHint(NewExec, CondReg); 3716 3717 if (UseGPRIdxMode) { 3718 if (Offset == 0) { 3719 SGPRIdxReg = CurrentIdxReg; 3720 } else { 3721 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3722 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3723 .addReg(CurrentIdxReg, RegState::Kill) 3724 .addImm(Offset); 3725 } 3726 } else { 3727 // Move index from VCC into M0 3728 if (Offset == 0) { 3729 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3730 .addReg(CurrentIdxReg, RegState::Kill); 3731 } else { 3732 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3733 .addReg(CurrentIdxReg, RegState::Kill) 3734 .addImm(Offset); 3735 } 3736 } 3737 3738 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3739 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3740 MachineInstr *InsertPt = 3741 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3742 : AMDGPU::S_XOR_B64_term), Exec) 3743 .addReg(Exec) 3744 .addReg(NewExec); 3745 3746 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3747 // s_cbranch_scc0? 3748 3749 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3750 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3751 .addMBB(&LoopBB); 3752 3753 return InsertPt->getIterator(); 3754 } 3755 3756 // This has slightly sub-optimal regalloc when the source vector is killed by 3757 // the read. The register allocator does not understand that the kill is 3758 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3759 // subregister from it, using 1 more VGPR than necessary. This was saved when 3760 // this was expanded after register allocation. 3761 static MachineBasicBlock::iterator 3762 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3763 unsigned InitResultReg, unsigned PhiReg, int Offset, 3764 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3765 MachineFunction *MF = MBB.getParent(); 3766 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3767 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3768 MachineRegisterInfo &MRI = MF->getRegInfo(); 3769 const DebugLoc &DL = MI.getDebugLoc(); 3770 MachineBasicBlock::iterator I(&MI); 3771 3772 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3773 Register DstReg = MI.getOperand(0).getReg(); 3774 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3775 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3776 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3777 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3778 3779 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3780 3781 // Save the EXEC mask 3782 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3783 .addReg(Exec); 3784 3785 MachineBasicBlock *LoopBB; 3786 MachineBasicBlock *RemainderBB; 3787 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3788 3789 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3790 3791 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3792 InitResultReg, DstReg, PhiReg, TmpExec, 3793 Offset, UseGPRIdxMode, SGPRIdxReg); 3794 3795 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3796 MachineFunction::iterator MBBI(LoopBB); 3797 ++MBBI; 3798 MF->insert(MBBI, LandingPad); 3799 LoopBB->removeSuccessor(RemainderBB); 3800 LandingPad->addSuccessor(RemainderBB); 3801 LoopBB->addSuccessor(LandingPad); 3802 MachineBasicBlock::iterator First = LandingPad->begin(); 3803 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3804 .addReg(SaveExec); 3805 3806 return InsPt; 3807 } 3808 3809 // Returns subreg index, offset 3810 static std::pair<unsigned, int> 3811 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3812 const TargetRegisterClass *SuperRC, 3813 unsigned VecReg, 3814 int Offset) { 3815 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3816 3817 // Skip out of bounds offsets, or else we would end up using an undefined 3818 // register. 3819 if (Offset >= NumElts || Offset < 0) 3820 return std::make_pair(AMDGPU::sub0, Offset); 3821 3822 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3823 } 3824 3825 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3826 MachineRegisterInfo &MRI, MachineInstr &MI, 3827 int Offset) { 3828 MachineBasicBlock *MBB = MI.getParent(); 3829 const DebugLoc &DL = MI.getDebugLoc(); 3830 MachineBasicBlock::iterator I(&MI); 3831 3832 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3833 3834 assert(Idx->getReg() != AMDGPU::NoRegister); 3835 3836 if (Offset == 0) { 3837 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3838 } else { 3839 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3840 .add(*Idx) 3841 .addImm(Offset); 3842 } 3843 } 3844 3845 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3846 MachineRegisterInfo &MRI, MachineInstr &MI, 3847 int Offset) { 3848 MachineBasicBlock *MBB = MI.getParent(); 3849 const DebugLoc &DL = MI.getDebugLoc(); 3850 MachineBasicBlock::iterator I(&MI); 3851 3852 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3853 3854 if (Offset == 0) 3855 return Idx->getReg(); 3856 3857 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3858 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3859 .add(*Idx) 3860 .addImm(Offset); 3861 return Tmp; 3862 } 3863 3864 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3865 MachineBasicBlock &MBB, 3866 const GCNSubtarget &ST) { 3867 const SIInstrInfo *TII = ST.getInstrInfo(); 3868 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3869 MachineFunction *MF = MBB.getParent(); 3870 MachineRegisterInfo &MRI = MF->getRegInfo(); 3871 3872 Register Dst = MI.getOperand(0).getReg(); 3873 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3874 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3875 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3876 3877 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3878 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3879 3880 unsigned SubReg; 3881 std::tie(SubReg, Offset) 3882 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3883 3884 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3885 3886 // Check for a SGPR index. 3887 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3888 MachineBasicBlock::iterator I(&MI); 3889 const DebugLoc &DL = MI.getDebugLoc(); 3890 3891 if (UseGPRIdxMode) { 3892 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3893 // to avoid interfering with other uses, so probably requires a new 3894 // optimization pass. 3895 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3896 3897 const MCInstrDesc &GPRIDXDesc = 3898 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3899 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3900 .addReg(SrcReg) 3901 .addReg(Idx) 3902 .addImm(SubReg); 3903 } else { 3904 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3905 3906 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3907 .addReg(SrcReg, 0, SubReg) 3908 .addReg(SrcReg, RegState::Implicit); 3909 } 3910 3911 MI.eraseFromParent(); 3912 3913 return &MBB; 3914 } 3915 3916 // Control flow needs to be inserted if indexing with a VGPR. 3917 const DebugLoc &DL = MI.getDebugLoc(); 3918 MachineBasicBlock::iterator I(&MI); 3919 3920 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3921 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3922 3923 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3924 3925 Register SGPRIdxReg; 3926 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3927 UseGPRIdxMode, SGPRIdxReg); 3928 3929 MachineBasicBlock *LoopBB = InsPt->getParent(); 3930 3931 if (UseGPRIdxMode) { 3932 const MCInstrDesc &GPRIDXDesc = 3933 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3934 3935 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3936 .addReg(SrcReg) 3937 .addReg(SGPRIdxReg) 3938 .addImm(SubReg); 3939 } else { 3940 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3941 .addReg(SrcReg, 0, SubReg) 3942 .addReg(SrcReg, RegState::Implicit); 3943 } 3944 3945 MI.eraseFromParent(); 3946 3947 return LoopBB; 3948 } 3949 3950 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3951 MachineBasicBlock &MBB, 3952 const GCNSubtarget &ST) { 3953 const SIInstrInfo *TII = ST.getInstrInfo(); 3954 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3955 MachineFunction *MF = MBB.getParent(); 3956 MachineRegisterInfo &MRI = MF->getRegInfo(); 3957 3958 Register Dst = MI.getOperand(0).getReg(); 3959 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3960 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3961 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3962 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3963 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3964 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3965 3966 // This can be an immediate, but will be folded later. 3967 assert(Val->getReg()); 3968 3969 unsigned SubReg; 3970 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3971 SrcVec->getReg(), 3972 Offset); 3973 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3974 3975 if (Idx->getReg() == AMDGPU::NoRegister) { 3976 MachineBasicBlock::iterator I(&MI); 3977 const DebugLoc &DL = MI.getDebugLoc(); 3978 3979 assert(Offset == 0); 3980 3981 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3982 .add(*SrcVec) 3983 .add(*Val) 3984 .addImm(SubReg); 3985 3986 MI.eraseFromParent(); 3987 return &MBB; 3988 } 3989 3990 // Check for a SGPR index. 3991 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3992 MachineBasicBlock::iterator I(&MI); 3993 const DebugLoc &DL = MI.getDebugLoc(); 3994 3995 if (UseGPRIdxMode) { 3996 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3997 3998 const MCInstrDesc &GPRIDXDesc = 3999 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4000 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 4001 .addReg(SrcVec->getReg()) 4002 .add(*Val) 4003 .addReg(Idx) 4004 .addImm(SubReg); 4005 } else { 4006 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 4007 4008 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4009 TRI.getRegSizeInBits(*VecRC), 32, false); 4010 BuildMI(MBB, I, DL, MovRelDesc, Dst) 4011 .addReg(SrcVec->getReg()) 4012 .add(*Val) 4013 .addImm(SubReg); 4014 } 4015 MI.eraseFromParent(); 4016 return &MBB; 4017 } 4018 4019 // Control flow needs to be inserted if indexing with a VGPR. 4020 if (Val->isReg()) 4021 MRI.clearKillFlags(Val->getReg()); 4022 4023 const DebugLoc &DL = MI.getDebugLoc(); 4024 4025 Register PhiReg = MRI.createVirtualRegister(VecRC); 4026 4027 Register SGPRIdxReg; 4028 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 4029 UseGPRIdxMode, SGPRIdxReg); 4030 MachineBasicBlock *LoopBB = InsPt->getParent(); 4031 4032 if (UseGPRIdxMode) { 4033 const MCInstrDesc &GPRIDXDesc = 4034 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4035 4036 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 4037 .addReg(PhiReg) 4038 .add(*Val) 4039 .addReg(SGPRIdxReg) 4040 .addImm(AMDGPU::sub0); 4041 } else { 4042 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4043 TRI.getRegSizeInBits(*VecRC), 32, false); 4044 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 4045 .addReg(PhiReg) 4046 .add(*Val) 4047 .addImm(AMDGPU::sub0); 4048 } 4049 4050 MI.eraseFromParent(); 4051 return LoopBB; 4052 } 4053 4054 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4055 MachineInstr &MI, MachineBasicBlock *BB) const { 4056 4057 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4058 MachineFunction *MF = BB->getParent(); 4059 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4060 4061 switch (MI.getOpcode()) { 4062 case AMDGPU::S_UADDO_PSEUDO: 4063 case AMDGPU::S_USUBO_PSEUDO: { 4064 const DebugLoc &DL = MI.getDebugLoc(); 4065 MachineOperand &Dest0 = MI.getOperand(0); 4066 MachineOperand &Dest1 = MI.getOperand(1); 4067 MachineOperand &Src0 = MI.getOperand(2); 4068 MachineOperand &Src1 = MI.getOperand(3); 4069 4070 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4071 ? AMDGPU::S_ADD_I32 4072 : AMDGPU::S_SUB_I32; 4073 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4074 4075 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4076 .addImm(1) 4077 .addImm(0); 4078 4079 MI.eraseFromParent(); 4080 return BB; 4081 } 4082 case AMDGPU::S_ADD_U64_PSEUDO: 4083 case AMDGPU::S_SUB_U64_PSEUDO: { 4084 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4085 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4086 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4087 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4088 const DebugLoc &DL = MI.getDebugLoc(); 4089 4090 MachineOperand &Dest = MI.getOperand(0); 4091 MachineOperand &Src0 = MI.getOperand(1); 4092 MachineOperand &Src1 = MI.getOperand(2); 4093 4094 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4095 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4096 4097 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4098 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4099 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4100 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4101 4102 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4103 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4104 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4105 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4106 4107 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4108 4109 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4110 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4111 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4112 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4113 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4114 .addReg(DestSub0) 4115 .addImm(AMDGPU::sub0) 4116 .addReg(DestSub1) 4117 .addImm(AMDGPU::sub1); 4118 MI.eraseFromParent(); 4119 return BB; 4120 } 4121 case AMDGPU::V_ADD_U64_PSEUDO: 4122 case AMDGPU::V_SUB_U64_PSEUDO: { 4123 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4124 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4125 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4126 const DebugLoc &DL = MI.getDebugLoc(); 4127 4128 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4129 4130 MachineOperand &Dest = MI.getOperand(0); 4131 MachineOperand &Src0 = MI.getOperand(1); 4132 MachineOperand &Src1 = MI.getOperand(2); 4133 4134 if (IsAdd && ST.hasLshlAddB64()) { 4135 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4136 Dest.getReg()) 4137 .add(Src0) 4138 .addImm(0) 4139 .add(Src1); 4140 TII->legalizeOperands(*Add); 4141 MI.eraseFromParent(); 4142 return BB; 4143 } 4144 4145 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4146 4147 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4148 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4149 4150 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4151 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4152 4153 const TargetRegisterClass *Src0RC = Src0.isReg() 4154 ? MRI.getRegClass(Src0.getReg()) 4155 : &AMDGPU::VReg_64RegClass; 4156 const TargetRegisterClass *Src1RC = Src1.isReg() 4157 ? MRI.getRegClass(Src1.getReg()) 4158 : &AMDGPU::VReg_64RegClass; 4159 4160 const TargetRegisterClass *Src0SubRC = 4161 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4162 const TargetRegisterClass *Src1SubRC = 4163 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4164 4165 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4166 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4167 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4168 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4169 4170 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4171 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4172 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4173 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4174 4175 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4176 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4177 .addReg(CarryReg, RegState::Define) 4178 .add(SrcReg0Sub0) 4179 .add(SrcReg1Sub0) 4180 .addImm(0); // clamp bit 4181 4182 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4183 MachineInstr *HiHalf = 4184 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4185 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4186 .add(SrcReg0Sub1) 4187 .add(SrcReg1Sub1) 4188 .addReg(CarryReg, RegState::Kill) 4189 .addImm(0); // clamp bit 4190 4191 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4192 .addReg(DestSub0) 4193 .addImm(AMDGPU::sub0) 4194 .addReg(DestSub1) 4195 .addImm(AMDGPU::sub1); 4196 TII->legalizeOperands(*LoHalf); 4197 TII->legalizeOperands(*HiHalf); 4198 MI.eraseFromParent(); 4199 return BB; 4200 } 4201 case AMDGPU::S_ADD_CO_PSEUDO: 4202 case AMDGPU::S_SUB_CO_PSEUDO: { 4203 // This pseudo has a chance to be selected 4204 // only from uniform add/subcarry node. All the VGPR operands 4205 // therefore assumed to be splat vectors. 4206 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4207 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4208 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4209 MachineBasicBlock::iterator MII = MI; 4210 const DebugLoc &DL = MI.getDebugLoc(); 4211 MachineOperand &Dest = MI.getOperand(0); 4212 MachineOperand &CarryDest = MI.getOperand(1); 4213 MachineOperand &Src0 = MI.getOperand(2); 4214 MachineOperand &Src1 = MI.getOperand(3); 4215 MachineOperand &Src2 = MI.getOperand(4); 4216 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4217 ? AMDGPU::S_ADDC_U32 4218 : AMDGPU::S_SUBB_U32; 4219 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4220 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4221 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4222 .addReg(Src0.getReg()); 4223 Src0.setReg(RegOp0); 4224 } 4225 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4226 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4227 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4228 .addReg(Src1.getReg()); 4229 Src1.setReg(RegOp1); 4230 } 4231 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4232 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4233 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4234 .addReg(Src2.getReg()); 4235 Src2.setReg(RegOp2); 4236 } 4237 4238 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4239 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4240 assert(WaveSize == 64 || WaveSize == 32); 4241 4242 if (WaveSize == 64) { 4243 if (ST.hasScalarCompareEq64()) { 4244 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4245 .addReg(Src2.getReg()) 4246 .addImm(0); 4247 } else { 4248 const TargetRegisterClass *SubRC = 4249 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4250 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4251 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4252 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4253 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4254 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4255 4256 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4257 .add(Src2Sub0) 4258 .add(Src2Sub1); 4259 4260 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4261 .addReg(Src2_32, RegState::Kill) 4262 .addImm(0); 4263 } 4264 } else { 4265 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4266 .addReg(Src2.getReg()) 4267 .addImm(0); 4268 } 4269 4270 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4271 4272 unsigned SelOpc = 4273 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4274 4275 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4276 .addImm(-1) 4277 .addImm(0); 4278 4279 MI.eraseFromParent(); 4280 return BB; 4281 } 4282 case AMDGPU::SI_INIT_M0: { 4283 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4284 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4285 .add(MI.getOperand(0)); 4286 MI.eraseFromParent(); 4287 return BB; 4288 } 4289 case AMDGPU::GET_GROUPSTATICSIZE: { 4290 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4291 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4292 DebugLoc DL = MI.getDebugLoc(); 4293 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4294 .add(MI.getOperand(0)) 4295 .addImm(MFI->getLDSSize()); 4296 MI.eraseFromParent(); 4297 return BB; 4298 } 4299 case AMDGPU::SI_INDIRECT_SRC_V1: 4300 case AMDGPU::SI_INDIRECT_SRC_V2: 4301 case AMDGPU::SI_INDIRECT_SRC_V4: 4302 case AMDGPU::SI_INDIRECT_SRC_V8: 4303 case AMDGPU::SI_INDIRECT_SRC_V16: 4304 case AMDGPU::SI_INDIRECT_SRC_V32: 4305 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4306 case AMDGPU::SI_INDIRECT_DST_V1: 4307 case AMDGPU::SI_INDIRECT_DST_V2: 4308 case AMDGPU::SI_INDIRECT_DST_V4: 4309 case AMDGPU::SI_INDIRECT_DST_V8: 4310 case AMDGPU::SI_INDIRECT_DST_V16: 4311 case AMDGPU::SI_INDIRECT_DST_V32: 4312 return emitIndirectDst(MI, *BB, *getSubtarget()); 4313 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4314 case AMDGPU::SI_KILL_I1_PSEUDO: 4315 return splitKillBlock(MI, BB); 4316 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4317 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4318 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4319 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4320 4321 Register Dst = MI.getOperand(0).getReg(); 4322 Register Src0 = MI.getOperand(1).getReg(); 4323 Register Src1 = MI.getOperand(2).getReg(); 4324 const DebugLoc &DL = MI.getDebugLoc(); 4325 Register SrcCond = MI.getOperand(3).getReg(); 4326 4327 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4328 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4329 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4330 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4331 4332 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4333 .addReg(SrcCond); 4334 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4335 .addImm(0) 4336 .addReg(Src0, 0, AMDGPU::sub0) 4337 .addImm(0) 4338 .addReg(Src1, 0, AMDGPU::sub0) 4339 .addReg(SrcCondCopy); 4340 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4341 .addImm(0) 4342 .addReg(Src0, 0, AMDGPU::sub1) 4343 .addImm(0) 4344 .addReg(Src1, 0, AMDGPU::sub1) 4345 .addReg(SrcCondCopy); 4346 4347 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4348 .addReg(DstLo) 4349 .addImm(AMDGPU::sub0) 4350 .addReg(DstHi) 4351 .addImm(AMDGPU::sub1); 4352 MI.eraseFromParent(); 4353 return BB; 4354 } 4355 case AMDGPU::SI_BR_UNDEF: { 4356 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4357 const DebugLoc &DL = MI.getDebugLoc(); 4358 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4359 .add(MI.getOperand(0)); 4360 Br->getOperand(1).setIsUndef(true); // read undef SCC 4361 MI.eraseFromParent(); 4362 return BB; 4363 } 4364 case AMDGPU::ADJCALLSTACKUP: 4365 case AMDGPU::ADJCALLSTACKDOWN: { 4366 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4367 MachineInstrBuilder MIB(*MF, &MI); 4368 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4369 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4370 return BB; 4371 } 4372 case AMDGPU::SI_CALL_ISEL: { 4373 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4374 const DebugLoc &DL = MI.getDebugLoc(); 4375 4376 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4377 4378 MachineInstrBuilder MIB; 4379 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4380 4381 for (const MachineOperand &MO : MI.operands()) 4382 MIB.add(MO); 4383 4384 MIB.cloneMemRefs(MI); 4385 MI.eraseFromParent(); 4386 return BB; 4387 } 4388 case AMDGPU::V_ADD_CO_U32_e32: 4389 case AMDGPU::V_SUB_CO_U32_e32: 4390 case AMDGPU::V_SUBREV_CO_U32_e32: { 4391 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4392 const DebugLoc &DL = MI.getDebugLoc(); 4393 unsigned Opc = MI.getOpcode(); 4394 4395 bool NeedClampOperand = false; 4396 if (TII->pseudoToMCOpcode(Opc) == -1) { 4397 Opc = AMDGPU::getVOPe64(Opc); 4398 NeedClampOperand = true; 4399 } 4400 4401 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4402 if (TII->isVOP3(*I)) { 4403 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4404 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4405 I.addReg(TRI->getVCC(), RegState::Define); 4406 } 4407 I.add(MI.getOperand(1)) 4408 .add(MI.getOperand(2)); 4409 if (NeedClampOperand) 4410 I.addImm(0); // clamp bit for e64 encoding 4411 4412 TII->legalizeOperands(*I); 4413 4414 MI.eraseFromParent(); 4415 return BB; 4416 } 4417 case AMDGPU::V_ADDC_U32_e32: 4418 case AMDGPU::V_SUBB_U32_e32: 4419 case AMDGPU::V_SUBBREV_U32_e32: 4420 // These instructions have an implicit use of vcc which counts towards the 4421 // constant bus limit. 4422 TII->legalizeOperands(MI); 4423 return BB; 4424 case AMDGPU::DS_GWS_INIT: 4425 case AMDGPU::DS_GWS_SEMA_BR: 4426 case AMDGPU::DS_GWS_BARRIER: 4427 if (Subtarget->needsAlignedVGPRs()) { 4428 // Add implicit aligned super-reg to force alignment on the data operand. 4429 const DebugLoc &DL = MI.getDebugLoc(); 4430 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4431 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4432 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4433 Register DataReg = Op->getReg(); 4434 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4435 Register Undef = MRI.createVirtualRegister( 4436 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4437 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4438 Register NewVR = 4439 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4440 : &AMDGPU::VReg_64_Align2RegClass); 4441 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4442 .addReg(DataReg, 0, Op->getSubReg()) 4443 .addImm(AMDGPU::sub0) 4444 .addReg(Undef) 4445 .addImm(AMDGPU::sub1); 4446 Op->setReg(NewVR); 4447 Op->setSubReg(AMDGPU::sub0); 4448 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4449 } 4450 LLVM_FALLTHROUGH; 4451 case AMDGPU::DS_GWS_SEMA_V: 4452 case AMDGPU::DS_GWS_SEMA_P: 4453 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4454 // A s_waitcnt 0 is required to be the instruction immediately following. 4455 if (getSubtarget()->hasGWSAutoReplay()) { 4456 bundleInstWithWaitcnt(MI); 4457 return BB; 4458 } 4459 4460 return emitGWSMemViolTestLoop(MI, BB); 4461 case AMDGPU::S_SETREG_B32: { 4462 // Try to optimize cases that only set the denormal mode or rounding mode. 4463 // 4464 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4465 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4466 // instead. 4467 // 4468 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4469 // allow you to have a no side effect instruction in the output of a 4470 // sideeffecting pattern. 4471 unsigned ID, Offset, Width; 4472 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4473 if (ID != AMDGPU::Hwreg::ID_MODE) 4474 return BB; 4475 4476 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4477 const unsigned SetMask = WidthMask << Offset; 4478 4479 if (getSubtarget()->hasDenormModeInst()) { 4480 unsigned SetDenormOp = 0; 4481 unsigned SetRoundOp = 0; 4482 4483 // The dedicated instructions can only set the whole denorm or round mode 4484 // at once, not a subset of bits in either. 4485 if (SetMask == 4486 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4487 // If this fully sets both the round and denorm mode, emit the two 4488 // dedicated instructions for these. 4489 SetRoundOp = AMDGPU::S_ROUND_MODE; 4490 SetDenormOp = AMDGPU::S_DENORM_MODE; 4491 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4492 SetRoundOp = AMDGPU::S_ROUND_MODE; 4493 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4494 SetDenormOp = AMDGPU::S_DENORM_MODE; 4495 } 4496 4497 if (SetRoundOp || SetDenormOp) { 4498 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4499 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4500 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4501 unsigned ImmVal = Def->getOperand(1).getImm(); 4502 if (SetRoundOp) { 4503 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4504 .addImm(ImmVal & 0xf); 4505 4506 // If we also have the denorm mode, get just the denorm mode bits. 4507 ImmVal >>= 4; 4508 } 4509 4510 if (SetDenormOp) { 4511 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4512 .addImm(ImmVal & 0xf); 4513 } 4514 4515 MI.eraseFromParent(); 4516 return BB; 4517 } 4518 } 4519 } 4520 4521 // If only FP bits are touched, used the no side effects pseudo. 4522 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4523 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4524 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4525 4526 return BB; 4527 } 4528 default: 4529 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4530 } 4531 } 4532 4533 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4534 return isTypeLegal(VT.getScalarType()); 4535 } 4536 4537 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4538 // This currently forces unfolding various combinations of fsub into fma with 4539 // free fneg'd operands. As long as we have fast FMA (controlled by 4540 // isFMAFasterThanFMulAndFAdd), we should perform these. 4541 4542 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4543 // most of these combines appear to be cycle neutral but save on instruction 4544 // count / code size. 4545 return true; 4546 } 4547 4548 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4549 4550 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4551 EVT VT) const { 4552 if (!VT.isVector()) { 4553 return MVT::i1; 4554 } 4555 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4556 } 4557 4558 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4559 // TODO: Should i16 be used always if legal? For now it would force VALU 4560 // shifts. 4561 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4562 } 4563 4564 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4565 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4566 ? Ty.changeElementSize(16) 4567 : Ty.changeElementSize(32); 4568 } 4569 4570 // Answering this is somewhat tricky and depends on the specific device which 4571 // have different rates for fma or all f64 operations. 4572 // 4573 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4574 // regardless of which device (although the number of cycles differs between 4575 // devices), so it is always profitable for f64. 4576 // 4577 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4578 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4579 // which we can always do even without fused FP ops since it returns the same 4580 // result as the separate operations and since it is always full 4581 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4582 // however does not support denormals, so we do report fma as faster if we have 4583 // a fast fma device and require denormals. 4584 // 4585 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4586 EVT VT) const { 4587 VT = VT.getScalarType(); 4588 4589 switch (VT.getSimpleVT().SimpleTy) { 4590 case MVT::f32: { 4591 // If mad is not available this depends only on if f32 fma is full rate. 4592 if (!Subtarget->hasMadMacF32Insts()) 4593 return Subtarget->hasFastFMAF32(); 4594 4595 // Otherwise f32 mad is always full rate and returns the same result as 4596 // the separate operations so should be preferred over fma. 4597 // However does not support denormals. 4598 if (hasFP32Denormals(MF)) 4599 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4600 4601 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4602 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4603 } 4604 case MVT::f64: 4605 return true; 4606 case MVT::f16: 4607 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4608 default: 4609 break; 4610 } 4611 4612 return false; 4613 } 4614 4615 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4616 LLT Ty) const { 4617 switch (Ty.getScalarSizeInBits()) { 4618 case 16: 4619 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4620 case 32: 4621 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4622 case 64: 4623 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4624 default: 4625 break; 4626 } 4627 4628 return false; 4629 } 4630 4631 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4632 if (!Ty.isScalar()) 4633 return false; 4634 4635 if (Ty.getScalarSizeInBits() == 16) 4636 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4637 if (Ty.getScalarSizeInBits() == 32) 4638 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4639 4640 return false; 4641 } 4642 4643 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4644 const SDNode *N) const { 4645 // TODO: Check future ftz flag 4646 // v_mad_f32/v_mac_f32 do not support denormals. 4647 EVT VT = N->getValueType(0); 4648 if (VT == MVT::f32) 4649 return Subtarget->hasMadMacF32Insts() && 4650 !hasFP32Denormals(DAG.getMachineFunction()); 4651 if (VT == MVT::f16) { 4652 return Subtarget->hasMadF16() && 4653 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4654 } 4655 4656 return false; 4657 } 4658 4659 //===----------------------------------------------------------------------===// 4660 // Custom DAG Lowering Operations 4661 //===----------------------------------------------------------------------===// 4662 4663 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4664 // wider vector type is legal. 4665 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4666 SelectionDAG &DAG) const { 4667 unsigned Opc = Op.getOpcode(); 4668 EVT VT = Op.getValueType(); 4669 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4670 4671 SDValue Lo, Hi; 4672 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4673 4674 SDLoc SL(Op); 4675 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4676 Op->getFlags()); 4677 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4678 Op->getFlags()); 4679 4680 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4681 } 4682 4683 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4684 // wider vector type is legal. 4685 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4686 SelectionDAG &DAG) const { 4687 unsigned Opc = Op.getOpcode(); 4688 EVT VT = Op.getValueType(); 4689 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4690 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4691 VT == MVT::v16f32 || VT == MVT::v32f32); 4692 4693 SDValue Lo0, Hi0; 4694 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4695 SDValue Lo1, Hi1; 4696 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4697 4698 SDLoc SL(Op); 4699 4700 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4701 Op->getFlags()); 4702 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4703 Op->getFlags()); 4704 4705 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4706 } 4707 4708 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4709 SelectionDAG &DAG) const { 4710 unsigned Opc = Op.getOpcode(); 4711 EVT VT = Op.getValueType(); 4712 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4713 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4714 VT == MVT::v16f32 || VT == MVT::v32f32); 4715 4716 SDValue Lo0, Hi0; 4717 SDValue Op0 = Op.getOperand(0); 4718 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4719 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4720 : std::make_pair(Op0, Op0); 4721 SDValue Lo1, Hi1; 4722 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4723 SDValue Lo2, Hi2; 4724 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4725 4726 SDLoc SL(Op); 4727 auto ResVT = DAG.GetSplitDestVTs(VT); 4728 4729 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4730 Op->getFlags()); 4731 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4732 Op->getFlags()); 4733 4734 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4735 } 4736 4737 4738 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4739 switch (Op.getOpcode()) { 4740 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4741 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4742 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4743 case ISD::LOAD: { 4744 SDValue Result = LowerLOAD(Op, DAG); 4745 assert((!Result.getNode() || 4746 Result.getNode()->getNumValues() == 2) && 4747 "Load should return a value and a chain"); 4748 return Result; 4749 } 4750 4751 case ISD::FSIN: 4752 case ISD::FCOS: 4753 return LowerTrig(Op, DAG); 4754 case ISD::SELECT: return LowerSELECT(Op, DAG); 4755 case ISD::FDIV: return LowerFDIV(Op, DAG); 4756 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4757 case ISD::STORE: return LowerSTORE(Op, DAG); 4758 case ISD::GlobalAddress: { 4759 MachineFunction &MF = DAG.getMachineFunction(); 4760 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4761 return LowerGlobalAddress(MFI, Op, DAG); 4762 } 4763 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4764 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4765 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4766 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4767 case ISD::INSERT_SUBVECTOR: 4768 return lowerINSERT_SUBVECTOR(Op, DAG); 4769 case ISD::INSERT_VECTOR_ELT: 4770 return lowerINSERT_VECTOR_ELT(Op, DAG); 4771 case ISD::EXTRACT_VECTOR_ELT: 4772 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4773 case ISD::VECTOR_SHUFFLE: 4774 return lowerVECTOR_SHUFFLE(Op, DAG); 4775 case ISD::BUILD_VECTOR: 4776 return lowerBUILD_VECTOR(Op, DAG); 4777 case ISD::FP_ROUND: 4778 return lowerFP_ROUND(Op, DAG); 4779 case ISD::FPTRUNC_ROUND: { 4780 unsigned Opc; 4781 SDLoc DL(Op); 4782 4783 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4784 return SDValue(); 4785 4786 // Get the rounding mode from the last operand 4787 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4788 if (RoundMode == (int)RoundingMode::TowardPositive) 4789 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4790 else if (RoundMode == (int)RoundingMode::TowardNegative) 4791 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4792 else 4793 return SDValue(); 4794 4795 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4796 } 4797 case ISD::TRAP: 4798 return lowerTRAP(Op, DAG); 4799 case ISD::DEBUGTRAP: 4800 return lowerDEBUGTRAP(Op, DAG); 4801 case ISD::FABS: 4802 case ISD::FNEG: 4803 case ISD::FCANONICALIZE: 4804 case ISD::BSWAP: 4805 return splitUnaryVectorOp(Op, DAG); 4806 case ISD::FMINNUM: 4807 case ISD::FMAXNUM: 4808 return lowerFMINNUM_FMAXNUM(Op, DAG); 4809 case ISD::FMA: 4810 return splitTernaryVectorOp(Op, DAG); 4811 case ISD::FP_TO_SINT: 4812 case ISD::FP_TO_UINT: 4813 return LowerFP_TO_INT(Op, DAG); 4814 case ISD::SHL: 4815 case ISD::SRA: 4816 case ISD::SRL: 4817 case ISD::ADD: 4818 case ISD::SUB: 4819 case ISD::MUL: 4820 case ISD::SMIN: 4821 case ISD::SMAX: 4822 case ISD::UMIN: 4823 case ISD::UMAX: 4824 case ISD::FADD: 4825 case ISD::FMUL: 4826 case ISD::FMINNUM_IEEE: 4827 case ISD::FMAXNUM_IEEE: 4828 case ISD::UADDSAT: 4829 case ISD::USUBSAT: 4830 case ISD::SADDSAT: 4831 case ISD::SSUBSAT: 4832 return splitBinaryVectorOp(Op, DAG); 4833 case ISD::SMULO: 4834 case ISD::UMULO: 4835 return lowerXMULO(Op, DAG); 4836 case ISD::SMUL_LOHI: 4837 case ISD::UMUL_LOHI: 4838 return lowerXMUL_LOHI(Op, DAG); 4839 case ISD::DYNAMIC_STACKALLOC: 4840 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4841 } 4842 return SDValue(); 4843 } 4844 4845 // Used for D16: Casts the result of an instruction into the right vector, 4846 // packs values if loads return unpacked values. 4847 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4848 const SDLoc &DL, 4849 SelectionDAG &DAG, bool Unpacked) { 4850 if (!LoadVT.isVector()) 4851 return Result; 4852 4853 // Cast back to the original packed type or to a larger type that is a 4854 // multiple of 32 bit for D16. Widening the return type is a required for 4855 // legalization. 4856 EVT FittingLoadVT = LoadVT; 4857 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4858 FittingLoadVT = 4859 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4860 LoadVT.getVectorNumElements() + 1); 4861 } 4862 4863 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4864 // Truncate to v2i16/v4i16. 4865 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4866 4867 // Workaround legalizer not scalarizing truncate after vector op 4868 // legalization but not creating intermediate vector trunc. 4869 SmallVector<SDValue, 4> Elts; 4870 DAG.ExtractVectorElements(Result, Elts); 4871 for (SDValue &Elt : Elts) 4872 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4873 4874 // Pad illegal v1i16/v3fi6 to v4i16 4875 if ((LoadVT.getVectorNumElements() % 2) == 1) 4876 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4877 4878 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4879 4880 // Bitcast to original type (v2f16/v4f16). 4881 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4882 } 4883 4884 // Cast back to the original packed type. 4885 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4886 } 4887 4888 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4889 MemSDNode *M, 4890 SelectionDAG &DAG, 4891 ArrayRef<SDValue> Ops, 4892 bool IsIntrinsic) const { 4893 SDLoc DL(M); 4894 4895 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4896 EVT LoadVT = M->getValueType(0); 4897 4898 EVT EquivLoadVT = LoadVT; 4899 if (LoadVT.isVector()) { 4900 if (Unpacked) { 4901 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4902 LoadVT.getVectorNumElements()); 4903 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4904 // Widen v3f16 to legal type 4905 EquivLoadVT = 4906 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4907 LoadVT.getVectorNumElements() + 1); 4908 } 4909 } 4910 4911 // Change from v4f16/v2f16 to EquivLoadVT. 4912 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4913 4914 SDValue Load 4915 = DAG.getMemIntrinsicNode( 4916 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4917 VTList, Ops, M->getMemoryVT(), 4918 M->getMemOperand()); 4919 4920 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4921 4922 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4923 } 4924 4925 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4926 SelectionDAG &DAG, 4927 ArrayRef<SDValue> Ops) const { 4928 SDLoc DL(M); 4929 EVT LoadVT = M->getValueType(0); 4930 EVT EltType = LoadVT.getScalarType(); 4931 EVT IntVT = LoadVT.changeTypeToInteger(); 4932 4933 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4934 4935 unsigned Opc = 4936 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4937 4938 if (IsD16) { 4939 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4940 } 4941 4942 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4943 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4944 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4945 4946 if (isTypeLegal(LoadVT)) { 4947 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4948 M->getMemOperand(), DAG); 4949 } 4950 4951 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4952 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4953 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4954 M->getMemOperand(), DAG); 4955 return DAG.getMergeValues( 4956 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4957 DL); 4958 } 4959 4960 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4961 SDNode *N, SelectionDAG &DAG) { 4962 EVT VT = N->getValueType(0); 4963 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4964 unsigned CondCode = CD->getZExtValue(); 4965 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4966 return DAG.getUNDEF(VT); 4967 4968 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4969 4970 SDValue LHS = N->getOperand(1); 4971 SDValue RHS = N->getOperand(2); 4972 4973 SDLoc DL(N); 4974 4975 EVT CmpVT = LHS.getValueType(); 4976 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4977 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4978 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4979 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4980 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4981 } 4982 4983 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4984 4985 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4986 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4987 4988 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4989 DAG.getCondCode(CCOpcode)); 4990 if (VT.bitsEq(CCVT)) 4991 return SetCC; 4992 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4993 } 4994 4995 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4996 SDNode *N, SelectionDAG &DAG) { 4997 EVT VT = N->getValueType(0); 4998 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4999 5000 unsigned CondCode = CD->getZExtValue(); 5001 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 5002 return DAG.getUNDEF(VT); 5003 5004 SDValue Src0 = N->getOperand(1); 5005 SDValue Src1 = N->getOperand(2); 5006 EVT CmpVT = Src0.getValueType(); 5007 SDLoc SL(N); 5008 5009 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 5010 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5011 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5012 } 5013 5014 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 5015 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 5016 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 5017 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 5018 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 5019 Src1, DAG.getCondCode(CCOpcode)); 5020 if (VT.bitsEq(CCVT)) 5021 return SetCC; 5022 return DAG.getZExtOrTrunc(SetCC, SL, VT); 5023 } 5024 5025 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 5026 SelectionDAG &DAG) { 5027 EVT VT = N->getValueType(0); 5028 SDValue Src = N->getOperand(1); 5029 SDLoc SL(N); 5030 5031 if (Src.getOpcode() == ISD::SETCC) { 5032 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 5033 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 5034 Src.getOperand(1), Src.getOperand(2)); 5035 } 5036 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 5037 // (ballot 0) -> 0 5038 if (Arg->isZero()) 5039 return DAG.getConstant(0, SL, VT); 5040 5041 // (ballot 1) -> EXEC/EXEC_LO 5042 if (Arg->isOne()) { 5043 Register Exec; 5044 if (VT.getScalarSizeInBits() == 32) 5045 Exec = AMDGPU::EXEC_LO; 5046 else if (VT.getScalarSizeInBits() == 64) 5047 Exec = AMDGPU::EXEC; 5048 else 5049 return SDValue(); 5050 5051 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 5052 } 5053 } 5054 5055 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5056 // ISD::SETNE) 5057 return DAG.getNode( 5058 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5059 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5060 } 5061 5062 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5063 SmallVectorImpl<SDValue> &Results, 5064 SelectionDAG &DAG) const { 5065 switch (N->getOpcode()) { 5066 case ISD::INSERT_VECTOR_ELT: { 5067 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5068 Results.push_back(Res); 5069 return; 5070 } 5071 case ISD::EXTRACT_VECTOR_ELT: { 5072 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5073 Results.push_back(Res); 5074 return; 5075 } 5076 case ISD::INTRINSIC_WO_CHAIN: { 5077 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5078 switch (IID) { 5079 case Intrinsic::amdgcn_cvt_pkrtz: { 5080 SDValue Src0 = N->getOperand(1); 5081 SDValue Src1 = N->getOperand(2); 5082 SDLoc SL(N); 5083 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5084 Src0, Src1); 5085 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5086 return; 5087 } 5088 case Intrinsic::amdgcn_cvt_pknorm_i16: 5089 case Intrinsic::amdgcn_cvt_pknorm_u16: 5090 case Intrinsic::amdgcn_cvt_pk_i16: 5091 case Intrinsic::amdgcn_cvt_pk_u16: { 5092 SDValue Src0 = N->getOperand(1); 5093 SDValue Src1 = N->getOperand(2); 5094 SDLoc SL(N); 5095 unsigned Opcode; 5096 5097 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5098 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5099 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5100 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5101 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5102 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5103 else 5104 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5105 5106 EVT VT = N->getValueType(0); 5107 if (isTypeLegal(VT)) 5108 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5109 else { 5110 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5111 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5112 } 5113 return; 5114 } 5115 } 5116 break; 5117 } 5118 case ISD::INTRINSIC_W_CHAIN: { 5119 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5120 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5121 // FIXME: Hacky 5122 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5123 Results.push_back(Res.getOperand(I)); 5124 } 5125 } else { 5126 Results.push_back(Res); 5127 Results.push_back(Res.getValue(1)); 5128 } 5129 return; 5130 } 5131 5132 break; 5133 } 5134 case ISD::SELECT: { 5135 SDLoc SL(N); 5136 EVT VT = N->getValueType(0); 5137 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5138 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5139 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5140 5141 EVT SelectVT = NewVT; 5142 if (NewVT.bitsLT(MVT::i32)) { 5143 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5144 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5145 SelectVT = MVT::i32; 5146 } 5147 5148 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5149 N->getOperand(0), LHS, RHS); 5150 5151 if (NewVT != SelectVT) 5152 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5153 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5154 return; 5155 } 5156 case ISD::FNEG: { 5157 if (N->getValueType(0) != MVT::v2f16) 5158 break; 5159 5160 SDLoc SL(N); 5161 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5162 5163 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5164 BC, 5165 DAG.getConstant(0x80008000, SL, MVT::i32)); 5166 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5167 return; 5168 } 5169 case ISD::FABS: { 5170 if (N->getValueType(0) != MVT::v2f16) 5171 break; 5172 5173 SDLoc SL(N); 5174 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5175 5176 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5177 BC, 5178 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5179 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5180 return; 5181 } 5182 default: 5183 break; 5184 } 5185 } 5186 5187 /// Helper function for LowerBRCOND 5188 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5189 5190 SDNode *Parent = Value.getNode(); 5191 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5192 I != E; ++I) { 5193 5194 if (I.getUse().get() != Value) 5195 continue; 5196 5197 if (I->getOpcode() == Opcode) 5198 return *I; 5199 } 5200 return nullptr; 5201 } 5202 5203 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5204 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5205 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5206 case Intrinsic::amdgcn_if: 5207 return AMDGPUISD::IF; 5208 case Intrinsic::amdgcn_else: 5209 return AMDGPUISD::ELSE; 5210 case Intrinsic::amdgcn_loop: 5211 return AMDGPUISD::LOOP; 5212 case Intrinsic::amdgcn_end_cf: 5213 llvm_unreachable("should not occur"); 5214 default: 5215 return 0; 5216 } 5217 } 5218 5219 // break, if_break, else_break are all only used as inputs to loop, not 5220 // directly as branch conditions. 5221 return 0; 5222 } 5223 5224 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5225 const Triple &TT = getTargetMachine().getTargetTriple(); 5226 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5227 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5228 AMDGPU::shouldEmitConstantsToTextSection(TT); 5229 } 5230 5231 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5232 // FIXME: Either avoid relying on address space here or change the default 5233 // address space for functions to avoid the explicit check. 5234 return (GV->getValueType()->isFunctionTy() || 5235 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5236 !shouldEmitFixup(GV) && 5237 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5238 } 5239 5240 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5241 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5242 } 5243 5244 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5245 if (!GV->hasExternalLinkage()) 5246 return true; 5247 5248 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5249 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5250 } 5251 5252 /// This transforms the control flow intrinsics to get the branch destination as 5253 /// last parameter, also switches branch target with BR if the need arise 5254 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5255 SelectionDAG &DAG) const { 5256 SDLoc DL(BRCOND); 5257 5258 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5259 SDValue Target = BRCOND.getOperand(2); 5260 SDNode *BR = nullptr; 5261 SDNode *SetCC = nullptr; 5262 5263 if (Intr->getOpcode() == ISD::SETCC) { 5264 // As long as we negate the condition everything is fine 5265 SetCC = Intr; 5266 Intr = SetCC->getOperand(0).getNode(); 5267 5268 } else { 5269 // Get the target from BR if we don't negate the condition 5270 BR = findUser(BRCOND, ISD::BR); 5271 assert(BR && "brcond missing unconditional branch user"); 5272 Target = BR->getOperand(1); 5273 } 5274 5275 unsigned CFNode = isCFIntrinsic(Intr); 5276 if (CFNode == 0) { 5277 // This is a uniform branch so we don't need to legalize. 5278 return BRCOND; 5279 } 5280 5281 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5282 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5283 5284 assert(!SetCC || 5285 (SetCC->getConstantOperandVal(1) == 1 && 5286 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5287 ISD::SETNE)); 5288 5289 // operands of the new intrinsic call 5290 SmallVector<SDValue, 4> Ops; 5291 if (HaveChain) 5292 Ops.push_back(BRCOND.getOperand(0)); 5293 5294 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5295 Ops.push_back(Target); 5296 5297 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5298 5299 // build the new intrinsic call 5300 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5301 5302 if (!HaveChain) { 5303 SDValue Ops[] = { 5304 SDValue(Result, 0), 5305 BRCOND.getOperand(0) 5306 }; 5307 5308 Result = DAG.getMergeValues(Ops, DL).getNode(); 5309 } 5310 5311 if (BR) { 5312 // Give the branch instruction our target 5313 SDValue Ops[] = { 5314 BR->getOperand(0), 5315 BRCOND.getOperand(2) 5316 }; 5317 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5318 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5319 } 5320 5321 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5322 5323 // Copy the intrinsic results to registers 5324 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5325 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5326 if (!CopyToReg) 5327 continue; 5328 5329 Chain = DAG.getCopyToReg( 5330 Chain, DL, 5331 CopyToReg->getOperand(1), 5332 SDValue(Result, i - 1), 5333 SDValue()); 5334 5335 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5336 } 5337 5338 // Remove the old intrinsic from the chain 5339 DAG.ReplaceAllUsesOfValueWith( 5340 SDValue(Intr, Intr->getNumValues() - 1), 5341 Intr->getOperand(0)); 5342 5343 return Chain; 5344 } 5345 5346 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5347 SelectionDAG &DAG) const { 5348 MVT VT = Op.getSimpleValueType(); 5349 SDLoc DL(Op); 5350 // Checking the depth 5351 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5352 return DAG.getConstant(0, DL, VT); 5353 5354 MachineFunction &MF = DAG.getMachineFunction(); 5355 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5356 // Check for kernel and shader functions 5357 if (Info->isEntryFunction()) 5358 return DAG.getConstant(0, DL, VT); 5359 5360 MachineFrameInfo &MFI = MF.getFrameInfo(); 5361 // There is a call to @llvm.returnaddress in this function 5362 MFI.setReturnAddressIsTaken(true); 5363 5364 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5365 // Get the return address reg and mark it as an implicit live-in 5366 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5367 5368 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5369 } 5370 5371 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5372 SDValue Op, 5373 const SDLoc &DL, 5374 EVT VT) const { 5375 return Op.getValueType().bitsLE(VT) ? 5376 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5377 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5378 DAG.getTargetConstant(0, DL, MVT::i32)); 5379 } 5380 5381 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5382 assert(Op.getValueType() == MVT::f16 && 5383 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5384 5385 SDValue Src = Op.getOperand(0); 5386 EVT SrcVT = Src.getValueType(); 5387 if (SrcVT != MVT::f64) 5388 return Op; 5389 5390 SDLoc DL(Op); 5391 5392 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5393 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5394 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5395 } 5396 5397 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5398 SelectionDAG &DAG) const { 5399 EVT VT = Op.getValueType(); 5400 const MachineFunction &MF = DAG.getMachineFunction(); 5401 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5402 bool IsIEEEMode = Info->getMode().IEEE; 5403 5404 // FIXME: Assert during selection that this is only selected for 5405 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5406 // mode functions, but this happens to be OK since it's only done in cases 5407 // where there is known no sNaN. 5408 if (IsIEEEMode) 5409 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5410 5411 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5412 return splitBinaryVectorOp(Op, DAG); 5413 return Op; 5414 } 5415 5416 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5417 EVT VT = Op.getValueType(); 5418 SDLoc SL(Op); 5419 SDValue LHS = Op.getOperand(0); 5420 SDValue RHS = Op.getOperand(1); 5421 bool isSigned = Op.getOpcode() == ISD::SMULO; 5422 5423 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5424 const APInt &C = RHSC->getAPIntValue(); 5425 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5426 if (C.isPowerOf2()) { 5427 // smulo(x, signed_min) is same as umulo(x, signed_min). 5428 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5429 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5430 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5431 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5432 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5433 SL, VT, Result, ShiftAmt), 5434 LHS, ISD::SETNE); 5435 return DAG.getMergeValues({ Result, Overflow }, SL); 5436 } 5437 } 5438 5439 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5440 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5441 SL, VT, LHS, RHS); 5442 5443 SDValue Sign = isSigned 5444 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5445 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5446 : DAG.getConstant(0, SL, VT); 5447 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5448 5449 return DAG.getMergeValues({ Result, Overflow }, SL); 5450 } 5451 5452 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5453 if (Op->isDivergent()) { 5454 // Select to V_MAD_[IU]64_[IU]32. 5455 return Op; 5456 } 5457 if (Subtarget->hasSMulHi()) { 5458 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5459 return SDValue(); 5460 } 5461 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5462 // calculate the high part, so we might as well do the whole thing with 5463 // V_MAD_[IU]64_[IU]32. 5464 return Op; 5465 } 5466 5467 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5468 if (!Subtarget->isTrapHandlerEnabled() || 5469 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5470 return lowerTrapEndpgm(Op, DAG); 5471 5472 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5473 switch (*HsaAbiVer) { 5474 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5475 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5476 return lowerTrapHsaQueuePtr(Op, DAG); 5477 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5478 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5479 return Subtarget->supportsGetDoorbellID() ? 5480 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5481 } 5482 } 5483 5484 llvm_unreachable("Unknown trap handler"); 5485 } 5486 5487 SDValue SITargetLowering::lowerTrapEndpgm( 5488 SDValue Op, SelectionDAG &DAG) const { 5489 SDLoc SL(Op); 5490 SDValue Chain = Op.getOperand(0); 5491 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5492 } 5493 5494 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5495 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5496 MachineFunction &MF = DAG.getMachineFunction(); 5497 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5498 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5499 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5500 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5501 MachineMemOperand::MODereferenceable | 5502 MachineMemOperand::MOInvariant); 5503 } 5504 5505 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5506 SDValue Op, SelectionDAG &DAG) const { 5507 SDLoc SL(Op); 5508 SDValue Chain = Op.getOperand(0); 5509 5510 SDValue QueuePtr; 5511 // For code object version 5, QueuePtr is passed through implicit kernarg. 5512 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5513 QueuePtr = 5514 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5515 } else { 5516 MachineFunction &MF = DAG.getMachineFunction(); 5517 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5518 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5519 5520 if (UserSGPR == AMDGPU::NoRegister) { 5521 // We probably are in a function incorrectly marked with 5522 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5523 // trap, so just use a null pointer. 5524 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5525 } else { 5526 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5527 MVT::i64); 5528 } 5529 } 5530 5531 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5532 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5533 QueuePtr, SDValue()); 5534 5535 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5536 SDValue Ops[] = { 5537 ToReg, 5538 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5539 SGPR01, 5540 ToReg.getValue(1) 5541 }; 5542 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5543 } 5544 5545 SDValue SITargetLowering::lowerTrapHsa( 5546 SDValue Op, SelectionDAG &DAG) const { 5547 SDLoc SL(Op); 5548 SDValue Chain = Op.getOperand(0); 5549 5550 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5551 SDValue Ops[] = { 5552 Chain, 5553 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5554 }; 5555 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5556 } 5557 5558 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5559 SDLoc SL(Op); 5560 SDValue Chain = Op.getOperand(0); 5561 MachineFunction &MF = DAG.getMachineFunction(); 5562 5563 if (!Subtarget->isTrapHandlerEnabled() || 5564 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5565 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5566 "debugtrap handler not supported", 5567 Op.getDebugLoc(), 5568 DS_Warning); 5569 LLVMContext &Ctx = MF.getFunction().getContext(); 5570 Ctx.diagnose(NoTrap); 5571 return Chain; 5572 } 5573 5574 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5575 SDValue Ops[] = { 5576 Chain, 5577 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5578 }; 5579 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5580 } 5581 5582 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5583 SelectionDAG &DAG) const { 5584 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5585 if (Subtarget->hasApertureRegs()) { 5586 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5587 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5588 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5589 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5590 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5591 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5592 unsigned Encoding = 5593 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5594 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5595 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5596 5597 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5598 SDValue ApertureReg = SDValue( 5599 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5600 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5601 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5602 } 5603 5604 // For code object version 5, private_base and shared_base are passed through 5605 // implicit kernargs. 5606 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5607 ImplicitParameter Param = 5608 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5609 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5610 } 5611 5612 MachineFunction &MF = DAG.getMachineFunction(); 5613 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5614 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5615 if (UserSGPR == AMDGPU::NoRegister) { 5616 // We probably are in a function incorrectly marked with 5617 // amdgpu-no-queue-ptr. This is undefined. 5618 return DAG.getUNDEF(MVT::i32); 5619 } 5620 5621 SDValue QueuePtr = CreateLiveInRegister( 5622 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5623 5624 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5625 // private_segment_aperture_base_hi. 5626 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5627 5628 SDValue Ptr = 5629 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5630 5631 // TODO: Use custom target PseudoSourceValue. 5632 // TODO: We should use the value from the IR intrinsic call, but it might not 5633 // be available and how do we get it? 5634 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5635 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5636 commonAlignment(Align(64), StructOffset), 5637 MachineMemOperand::MODereferenceable | 5638 MachineMemOperand::MOInvariant); 5639 } 5640 5641 /// Return true if the value is a known valid address, such that a null check is 5642 /// not necessary. 5643 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5644 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5645 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5646 isa<BasicBlockSDNode>(Val)) 5647 return true; 5648 5649 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5650 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5651 5652 // TODO: Search through arithmetic, handle arguments and loads 5653 // marked nonnull. 5654 return false; 5655 } 5656 5657 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5658 SelectionDAG &DAG) const { 5659 SDLoc SL(Op); 5660 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5661 5662 SDValue Src = ASC->getOperand(0); 5663 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5664 unsigned SrcAS = ASC->getSrcAddressSpace(); 5665 5666 const AMDGPUTargetMachine &TM = 5667 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5668 5669 // flat -> local/private 5670 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5671 unsigned DestAS = ASC->getDestAddressSpace(); 5672 5673 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5674 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5675 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5676 5677 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5678 return Ptr; 5679 5680 unsigned NullVal = TM.getNullPointerValue(DestAS); 5681 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5682 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5683 5684 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5685 SegmentNullPtr); 5686 } 5687 } 5688 5689 // local/private -> flat 5690 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5691 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5692 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5693 5694 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5695 SDValue CvtPtr = 5696 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5697 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5698 5699 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5700 return CvtPtr; 5701 5702 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5703 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5704 5705 SDValue NonNull 5706 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5707 5708 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5709 FlatNullPtr); 5710 } 5711 } 5712 5713 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5714 Op.getValueType() == MVT::i64) { 5715 const SIMachineFunctionInfo *Info = 5716 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5717 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5718 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5719 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5720 } 5721 5722 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5723 Src.getValueType() == MVT::i64) 5724 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5725 5726 // global <-> flat are no-ops and never emitted. 5727 5728 const MachineFunction &MF = DAG.getMachineFunction(); 5729 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5730 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5731 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5732 5733 return DAG.getUNDEF(ASC->getValueType(0)); 5734 } 5735 5736 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5737 // the small vector and inserting them into the big vector. That is better than 5738 // the default expansion of doing it via a stack slot. Even though the use of 5739 // the stack slot would be optimized away afterwards, the stack slot itself 5740 // remains. 5741 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5742 SelectionDAG &DAG) const { 5743 SDValue Vec = Op.getOperand(0); 5744 SDValue Ins = Op.getOperand(1); 5745 SDValue Idx = Op.getOperand(2); 5746 EVT VecVT = Vec.getValueType(); 5747 EVT InsVT = Ins.getValueType(); 5748 EVT EltVT = VecVT.getVectorElementType(); 5749 unsigned InsNumElts = InsVT.getVectorNumElements(); 5750 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5751 SDLoc SL(Op); 5752 5753 for (unsigned I = 0; I != InsNumElts; ++I) { 5754 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5755 DAG.getConstant(I, SL, MVT::i32)); 5756 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5757 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5758 } 5759 return Vec; 5760 } 5761 5762 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5763 SelectionDAG &DAG) const { 5764 SDValue Vec = Op.getOperand(0); 5765 SDValue InsVal = Op.getOperand(1); 5766 SDValue Idx = Op.getOperand(2); 5767 EVT VecVT = Vec.getValueType(); 5768 EVT EltVT = VecVT.getVectorElementType(); 5769 unsigned VecSize = VecVT.getSizeInBits(); 5770 unsigned EltSize = EltVT.getSizeInBits(); 5771 5772 5773 assert(VecSize <= 64); 5774 5775 unsigned NumElts = VecVT.getVectorNumElements(); 5776 SDLoc SL(Op); 5777 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5778 5779 if (NumElts == 4 && EltSize == 16 && KIdx) { 5780 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5781 5782 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5783 DAG.getConstant(0, SL, MVT::i32)); 5784 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5785 DAG.getConstant(1, SL, MVT::i32)); 5786 5787 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5788 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5789 5790 unsigned Idx = KIdx->getZExtValue(); 5791 bool InsertLo = Idx < 2; 5792 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5793 InsertLo ? LoVec : HiVec, 5794 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5795 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5796 5797 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5798 5799 SDValue Concat = InsertLo ? 5800 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5801 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5802 5803 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5804 } 5805 5806 if (isa<ConstantSDNode>(Idx)) 5807 return SDValue(); 5808 5809 MVT IntVT = MVT::getIntegerVT(VecSize); 5810 5811 // Avoid stack access for dynamic indexing. 5812 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5813 5814 // Create a congruent vector with the target value in each element so that 5815 // the required element can be masked and ORed into the target vector. 5816 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5817 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5818 5819 assert(isPowerOf2_32(EltSize)); 5820 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5821 5822 // Convert vector index to bit-index. 5823 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5824 5825 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5826 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5827 DAG.getConstant(0xffff, SL, IntVT), 5828 ScaledIdx); 5829 5830 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5831 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5832 DAG.getNOT(SL, BFM, IntVT), BCVec); 5833 5834 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5835 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5836 } 5837 5838 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5839 SelectionDAG &DAG) const { 5840 SDLoc SL(Op); 5841 5842 EVT ResultVT = Op.getValueType(); 5843 SDValue Vec = Op.getOperand(0); 5844 SDValue Idx = Op.getOperand(1); 5845 EVT VecVT = Vec.getValueType(); 5846 unsigned VecSize = VecVT.getSizeInBits(); 5847 EVT EltVT = VecVT.getVectorElementType(); 5848 5849 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5850 5851 // Make sure we do any optimizations that will make it easier to fold 5852 // source modifiers before obscuring it with bit operations. 5853 5854 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5855 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5856 return Combined; 5857 5858 if (VecSize == 128) { 5859 SDValue Lo, Hi; 5860 EVT LoVT, HiVT; 5861 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5862 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5863 Lo = 5864 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5865 V2, DAG.getConstant(0, SL, MVT::i32))); 5866 Hi = 5867 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5868 V2, DAG.getConstant(1, SL, MVT::i32))); 5869 EVT IdxVT = Idx.getValueType(); 5870 unsigned NElem = VecVT.getVectorNumElements(); 5871 assert(isPowerOf2_32(NElem)); 5872 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5873 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5874 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5875 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5876 } 5877 5878 assert(VecSize <= 64); 5879 5880 unsigned EltSize = EltVT.getSizeInBits(); 5881 assert(isPowerOf2_32(EltSize)); 5882 5883 MVT IntVT = MVT::getIntegerVT(VecSize); 5884 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5885 5886 // Convert vector index to bit-index (* EltSize) 5887 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5888 5889 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5890 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5891 5892 if (ResultVT == MVT::f16) { 5893 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5894 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5895 } 5896 5897 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5898 } 5899 5900 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5901 assert(Elt % 2 == 0); 5902 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5903 } 5904 5905 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5906 SelectionDAG &DAG) const { 5907 SDLoc SL(Op); 5908 EVT ResultVT = Op.getValueType(); 5909 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5910 5911 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5912 EVT EltVT = PackVT.getVectorElementType(); 5913 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5914 5915 // vector_shuffle <0,1,6,7> lhs, rhs 5916 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5917 // 5918 // vector_shuffle <6,7,2,3> lhs, rhs 5919 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5920 // 5921 // vector_shuffle <6,7,0,1> lhs, rhs 5922 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5923 5924 // Avoid scalarizing when both halves are reading from consecutive elements. 5925 SmallVector<SDValue, 4> Pieces; 5926 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5927 if (elementPairIsContiguous(SVN->getMask(), I)) { 5928 const int Idx = SVN->getMaskElt(I); 5929 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5930 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5931 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5932 PackVT, SVN->getOperand(VecIdx), 5933 DAG.getConstant(EltIdx, SL, MVT::i32)); 5934 Pieces.push_back(SubVec); 5935 } else { 5936 const int Idx0 = SVN->getMaskElt(I); 5937 const int Idx1 = SVN->getMaskElt(I + 1); 5938 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5939 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5940 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5941 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5942 5943 SDValue Vec0 = SVN->getOperand(VecIdx0); 5944 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5945 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5946 5947 SDValue Vec1 = SVN->getOperand(VecIdx1); 5948 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5949 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5950 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5951 } 5952 } 5953 5954 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5955 } 5956 5957 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5958 SelectionDAG &DAG) const { 5959 SDLoc SL(Op); 5960 EVT VT = Op.getValueType(); 5961 5962 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5963 VT == MVT::v8i16 || VT == MVT::v8f16) { 5964 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5965 VT.getVectorNumElements() / 2); 5966 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5967 5968 // Turn into pair of packed build_vectors. 5969 // TODO: Special case for constants that can be materialized with s_mov_b64. 5970 SmallVector<SDValue, 4> LoOps, HiOps; 5971 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5972 LoOps.push_back(Op.getOperand(I)); 5973 HiOps.push_back(Op.getOperand(I + E)); 5974 } 5975 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5976 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5977 5978 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5979 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5980 5981 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5982 { CastLo, CastHi }); 5983 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5984 } 5985 5986 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5987 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5988 5989 SDValue Lo = Op.getOperand(0); 5990 SDValue Hi = Op.getOperand(1); 5991 5992 // Avoid adding defined bits with the zero_extend. 5993 if (Hi.isUndef()) { 5994 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5995 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5996 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5997 } 5998 5999 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 6000 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 6001 6002 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 6003 DAG.getConstant(16, SL, MVT::i32)); 6004 if (Lo.isUndef()) 6005 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 6006 6007 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 6008 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 6009 6010 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 6011 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 6012 } 6013 6014 bool 6015 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 6016 // We can fold offsets for anything that doesn't require a GOT relocation. 6017 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 6018 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 6019 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 6020 !shouldEmitGOTReloc(GA->getGlobal()); 6021 } 6022 6023 static SDValue 6024 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 6025 const SDLoc &DL, int64_t Offset, EVT PtrVT, 6026 unsigned GAFlags = SIInstrInfo::MO_NONE) { 6027 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 6028 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 6029 // lowered to the following code sequence: 6030 // 6031 // For constant address space: 6032 // s_getpc_b64 s[0:1] 6033 // s_add_u32 s0, s0, $symbol 6034 // s_addc_u32 s1, s1, 0 6035 // 6036 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6037 // a fixup or relocation is emitted to replace $symbol with a literal 6038 // constant, which is a pc-relative offset from the encoding of the $symbol 6039 // operand to the global variable. 6040 // 6041 // For global address space: 6042 // s_getpc_b64 s[0:1] 6043 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 6044 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 6045 // 6046 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6047 // fixups or relocations are emitted to replace $symbol@*@lo and 6048 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 6049 // which is a 64-bit pc-relative offset from the encoding of the $symbol 6050 // operand to the global variable. 6051 // 6052 // What we want here is an offset from the value returned by s_getpc 6053 // (which is the address of the s_add_u32 instruction) to the global 6054 // variable, but since the encoding of $symbol starts 4 bytes after the start 6055 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 6056 // small. This requires us to add 4 to the global variable offset in order to 6057 // compute the correct address. Similarly for the s_addc_u32 instruction, the 6058 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 6059 // instruction. 6060 SDValue PtrLo = 6061 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 6062 SDValue PtrHi; 6063 if (GAFlags == SIInstrInfo::MO_NONE) { 6064 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 6065 } else { 6066 PtrHi = 6067 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 6068 } 6069 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 6070 } 6071 6072 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 6073 SDValue Op, 6074 SelectionDAG &DAG) const { 6075 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 6076 SDLoc DL(GSD); 6077 EVT PtrVT = Op.getValueType(); 6078 6079 const GlobalValue *GV = GSD->getGlobal(); 6080 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6081 shouldUseLDSConstAddress(GV)) || 6082 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6083 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6084 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6085 GV->hasExternalLinkage()) { 6086 Type *Ty = GV->getValueType(); 6087 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6088 // zero-sized type in other languages to declare the dynamic shared 6089 // memory which size is not known at the compile time. They will be 6090 // allocated by the runtime and placed directly after the static 6091 // allocated ones. They all share the same offset. 6092 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6093 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6094 // Adjust alignment for that dynamic shared memory array. 6095 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6096 return SDValue( 6097 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6098 } 6099 } 6100 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6101 } 6102 6103 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6104 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6105 SIInstrInfo::MO_ABS32_LO); 6106 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6107 } 6108 6109 if (shouldEmitFixup(GV)) 6110 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6111 else if (shouldEmitPCReloc(GV)) 6112 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6113 SIInstrInfo::MO_REL32); 6114 6115 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6116 SIInstrInfo::MO_GOTPCREL32); 6117 6118 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6119 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6120 const DataLayout &DataLayout = DAG.getDataLayout(); 6121 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6122 MachinePointerInfo PtrInfo 6123 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6124 6125 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6126 MachineMemOperand::MODereferenceable | 6127 MachineMemOperand::MOInvariant); 6128 } 6129 6130 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6131 const SDLoc &DL, SDValue V) const { 6132 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6133 // the destination register. 6134 // 6135 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6136 // so we will end up with redundant moves to m0. 6137 // 6138 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6139 6140 // A Null SDValue creates a glue result. 6141 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6142 V, Chain); 6143 return SDValue(M0, 0); 6144 } 6145 6146 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6147 SDValue Op, 6148 MVT VT, 6149 unsigned Offset) const { 6150 SDLoc SL(Op); 6151 SDValue Param = lowerKernargMemParameter( 6152 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6153 // The local size values will have the hi 16-bits as zero. 6154 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6155 DAG.getValueType(VT)); 6156 } 6157 6158 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6159 EVT VT) { 6160 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6161 "non-hsa intrinsic with hsa target", 6162 DL.getDebugLoc()); 6163 DAG.getContext()->diagnose(BadIntrin); 6164 return DAG.getUNDEF(VT); 6165 } 6166 6167 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6168 EVT VT) { 6169 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6170 "intrinsic not supported on subtarget", 6171 DL.getDebugLoc()); 6172 DAG.getContext()->diagnose(BadIntrin); 6173 return DAG.getUNDEF(VT); 6174 } 6175 6176 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6177 ArrayRef<SDValue> Elts) { 6178 assert(!Elts.empty()); 6179 MVT Type; 6180 unsigned NumElts = Elts.size(); 6181 6182 if (NumElts <= 8) { 6183 Type = MVT::getVectorVT(MVT::f32, NumElts); 6184 } else { 6185 assert(Elts.size() <= 16); 6186 Type = MVT::v16f32; 6187 NumElts = 16; 6188 } 6189 6190 SmallVector<SDValue, 16> VecElts(NumElts); 6191 for (unsigned i = 0; i < Elts.size(); ++i) { 6192 SDValue Elt = Elts[i]; 6193 if (Elt.getValueType() != MVT::f32) 6194 Elt = DAG.getBitcast(MVT::f32, Elt); 6195 VecElts[i] = Elt; 6196 } 6197 for (unsigned i = Elts.size(); i < NumElts; ++i) 6198 VecElts[i] = DAG.getUNDEF(MVT::f32); 6199 6200 if (NumElts == 1) 6201 return VecElts[0]; 6202 return DAG.getBuildVector(Type, DL, VecElts); 6203 } 6204 6205 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6206 SDValue Src, int ExtraElts) { 6207 EVT SrcVT = Src.getValueType(); 6208 6209 SmallVector<SDValue, 8> Elts; 6210 6211 if (SrcVT.isVector()) 6212 DAG.ExtractVectorElements(Src, Elts); 6213 else 6214 Elts.push_back(Src); 6215 6216 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6217 while (ExtraElts--) 6218 Elts.push_back(Undef); 6219 6220 return DAG.getBuildVector(CastVT, DL, Elts); 6221 } 6222 6223 // Re-construct the required return value for a image load intrinsic. 6224 // This is more complicated due to the optional use TexFailCtrl which means the required 6225 // return type is an aggregate 6226 static SDValue constructRetValue(SelectionDAG &DAG, 6227 MachineSDNode *Result, 6228 ArrayRef<EVT> ResultTypes, 6229 bool IsTexFail, bool Unpacked, bool IsD16, 6230 int DMaskPop, int NumVDataDwords, 6231 const SDLoc &DL) { 6232 // Determine the required return type. This is the same regardless of IsTexFail flag 6233 EVT ReqRetVT = ResultTypes[0]; 6234 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6235 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6236 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6237 6238 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6239 DMaskPop : (DMaskPop + 1) / 2; 6240 6241 MVT DataDwordVT = NumDataDwords == 1 ? 6242 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6243 6244 MVT MaskPopVT = MaskPopDwords == 1 ? 6245 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6246 6247 SDValue Data(Result, 0); 6248 SDValue TexFail; 6249 6250 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6251 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6252 if (MaskPopVT.isVector()) { 6253 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6254 SDValue(Result, 0), ZeroIdx); 6255 } else { 6256 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6257 SDValue(Result, 0), ZeroIdx); 6258 } 6259 } 6260 6261 if (DataDwordVT.isVector()) 6262 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6263 NumDataDwords - MaskPopDwords); 6264 6265 if (IsD16) 6266 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6267 6268 EVT LegalReqRetVT = ReqRetVT; 6269 if (!ReqRetVT.isVector()) { 6270 if (!Data.getValueType().isInteger()) 6271 Data = DAG.getNode(ISD::BITCAST, DL, 6272 Data.getValueType().changeTypeToInteger(), Data); 6273 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6274 } else { 6275 // We need to widen the return vector to a legal type 6276 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6277 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6278 LegalReqRetVT = 6279 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6280 ReqRetVT.getVectorNumElements() + 1); 6281 } 6282 } 6283 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6284 6285 if (IsTexFail) { 6286 TexFail = 6287 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6288 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6289 6290 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6291 } 6292 6293 if (Result->getNumValues() == 1) 6294 return Data; 6295 6296 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6297 } 6298 6299 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6300 SDValue *LWE, bool &IsTexFail) { 6301 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6302 6303 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6304 if (Value) { 6305 IsTexFail = true; 6306 } 6307 6308 SDLoc DL(TexFailCtrlConst); 6309 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6310 Value &= ~(uint64_t)0x1; 6311 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6312 Value &= ~(uint64_t)0x2; 6313 6314 return Value == 0; 6315 } 6316 6317 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6318 MVT PackVectorVT, 6319 SmallVectorImpl<SDValue> &PackedAddrs, 6320 unsigned DimIdx, unsigned EndIdx, 6321 unsigned NumGradients) { 6322 SDLoc DL(Op); 6323 for (unsigned I = DimIdx; I < EndIdx; I++) { 6324 SDValue Addr = Op.getOperand(I); 6325 6326 // Gradients are packed with undef for each coordinate. 6327 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6328 // 1D: undef,dx/dh; undef,dx/dv 6329 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6330 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6331 if (((I + 1) >= EndIdx) || 6332 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6333 I == DimIdx + NumGradients - 1))) { 6334 if (Addr.getValueType() != MVT::i16) 6335 Addr = DAG.getBitcast(MVT::i16, Addr); 6336 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6337 } else { 6338 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6339 I++; 6340 } 6341 Addr = DAG.getBitcast(MVT::f32, Addr); 6342 PackedAddrs.push_back(Addr); 6343 } 6344 } 6345 6346 SDValue SITargetLowering::lowerImage(SDValue Op, 6347 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6348 SelectionDAG &DAG, bool WithChain) const { 6349 SDLoc DL(Op); 6350 MachineFunction &MF = DAG.getMachineFunction(); 6351 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6352 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6353 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6354 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6355 unsigned IntrOpcode = Intr->BaseOpcode; 6356 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6357 6358 SmallVector<EVT, 3> ResultTypes(Op->values()); 6359 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6360 bool IsD16 = false; 6361 bool IsG16 = false; 6362 bool IsA16 = false; 6363 SDValue VData; 6364 int NumVDataDwords; 6365 bool AdjustRetType = false; 6366 6367 // Offset of intrinsic arguments 6368 const unsigned ArgOffset = WithChain ? 2 : 1; 6369 6370 unsigned DMask; 6371 unsigned DMaskLanes = 0; 6372 6373 if (BaseOpcode->Atomic) { 6374 VData = Op.getOperand(2); 6375 6376 bool Is64Bit = VData.getValueType() == MVT::i64; 6377 if (BaseOpcode->AtomicX2) { 6378 SDValue VData2 = Op.getOperand(3); 6379 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6380 {VData, VData2}); 6381 if (Is64Bit) 6382 VData = DAG.getBitcast(MVT::v4i32, VData); 6383 6384 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6385 DMask = Is64Bit ? 0xf : 0x3; 6386 NumVDataDwords = Is64Bit ? 4 : 2; 6387 } else { 6388 DMask = Is64Bit ? 0x3 : 0x1; 6389 NumVDataDwords = Is64Bit ? 2 : 1; 6390 } 6391 } else { 6392 auto *DMaskConst = 6393 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6394 DMask = DMaskConst->getZExtValue(); 6395 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6396 6397 if (BaseOpcode->Store) { 6398 VData = Op.getOperand(2); 6399 6400 MVT StoreVT = VData.getSimpleValueType(); 6401 if (StoreVT.getScalarType() == MVT::f16) { 6402 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6403 return Op; // D16 is unsupported for this instruction 6404 6405 IsD16 = true; 6406 VData = handleD16VData(VData, DAG, true); 6407 } 6408 6409 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6410 } else { 6411 // Work out the num dwords based on the dmask popcount and underlying type 6412 // and whether packing is supported. 6413 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6414 if (LoadVT.getScalarType() == MVT::f16) { 6415 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6416 return Op; // D16 is unsupported for this instruction 6417 6418 IsD16 = true; 6419 } 6420 6421 // Confirm that the return type is large enough for the dmask specified 6422 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6423 (!LoadVT.isVector() && DMaskLanes > 1)) 6424 return Op; 6425 6426 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6427 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6428 // instructions. 6429 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6430 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6431 NumVDataDwords = (DMaskLanes + 1) / 2; 6432 else 6433 NumVDataDwords = DMaskLanes; 6434 6435 AdjustRetType = true; 6436 } 6437 } 6438 6439 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6440 SmallVector<SDValue, 4> VAddrs; 6441 6442 // Check for 16 bit addresses or derivatives and pack if true. 6443 MVT VAddrVT = 6444 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6445 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6446 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6447 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6448 6449 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6450 VAddrScalarVT = VAddrVT.getScalarType(); 6451 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6452 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6453 6454 // Push back extra arguments. 6455 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6456 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6457 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6458 // Special handling of bias when A16 is on. Bias is of type half but 6459 // occupies full 32-bit. 6460 SDValue Bias = DAG.getBuildVector( 6461 MVT::v2f16, DL, 6462 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6463 VAddrs.push_back(Bias); 6464 } else { 6465 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6466 "Bias needs to be converted to 16 bit in A16 mode"); 6467 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6468 } 6469 } 6470 6471 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6472 // 16 bit gradients are supported, but are tied to the A16 control 6473 // so both gradients and addresses must be 16 bit 6474 LLVM_DEBUG( 6475 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6476 "require 16 bit args for both gradients and addresses"); 6477 return Op; 6478 } 6479 6480 if (IsA16) { 6481 if (!ST->hasA16()) { 6482 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6483 "support 16 bit addresses\n"); 6484 return Op; 6485 } 6486 } 6487 6488 // We've dealt with incorrect input so we know that if IsA16, IsG16 6489 // are set then we have to compress/pack operands (either address, 6490 // gradient or both) 6491 // In the case where a16 and gradients are tied (no G16 support) then we 6492 // have already verified that both IsA16 and IsG16 are true 6493 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6494 // Activate g16 6495 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6496 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6497 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6498 } 6499 6500 // Add gradients (packed or unpacked) 6501 if (IsG16) { 6502 // Pack the gradients 6503 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6504 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6505 ArgOffset + Intr->GradientStart, 6506 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6507 } else { 6508 for (unsigned I = ArgOffset + Intr->GradientStart; 6509 I < ArgOffset + Intr->CoordStart; I++) 6510 VAddrs.push_back(Op.getOperand(I)); 6511 } 6512 6513 // Add addresses (packed or unpacked) 6514 if (IsA16) { 6515 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6516 ArgOffset + Intr->CoordStart, VAddrEnd, 6517 0 /* No gradients */); 6518 } else { 6519 // Add uncompressed address 6520 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6521 VAddrs.push_back(Op.getOperand(I)); 6522 } 6523 6524 // If the register allocator cannot place the address registers contiguously 6525 // without introducing moves, then using the non-sequential address encoding 6526 // is always preferable, since it saves VALU instructions and is usually a 6527 // wash in terms of code size or even better. 6528 // 6529 // However, we currently have no way of hinting to the register allocator that 6530 // MIMG addresses should be placed contiguously when it is possible to do so, 6531 // so force non-NSA for the common 2-address case as a heuristic. 6532 // 6533 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6534 // allocation when possible. 6535 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6536 VAddrs.size() >= 3 && 6537 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6538 SDValue VAddr; 6539 if (!UseNSA) 6540 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6541 6542 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6543 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6544 SDValue Unorm; 6545 if (!BaseOpcode->Sampler) { 6546 Unorm = True; 6547 } else { 6548 auto UnormConst = 6549 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6550 6551 Unorm = UnormConst->getZExtValue() ? True : False; 6552 } 6553 6554 SDValue TFE; 6555 SDValue LWE; 6556 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6557 bool IsTexFail = false; 6558 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6559 return Op; 6560 6561 if (IsTexFail) { 6562 if (!DMaskLanes) { 6563 // Expecting to get an error flag since TFC is on - and dmask is 0 6564 // Force dmask to be at least 1 otherwise the instruction will fail 6565 DMask = 0x1; 6566 DMaskLanes = 1; 6567 NumVDataDwords = 1; 6568 } 6569 NumVDataDwords += 1; 6570 AdjustRetType = true; 6571 } 6572 6573 // Has something earlier tagged that the return type needs adjusting 6574 // This happens if the instruction is a load or has set TexFailCtrl flags 6575 if (AdjustRetType) { 6576 // NumVDataDwords reflects the true number of dwords required in the return type 6577 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6578 // This is a no-op load. This can be eliminated 6579 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6580 if (isa<MemSDNode>(Op)) 6581 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6582 return Undef; 6583 } 6584 6585 EVT NewVT = NumVDataDwords > 1 ? 6586 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6587 : MVT::i32; 6588 6589 ResultTypes[0] = NewVT; 6590 if (ResultTypes.size() == 3) { 6591 // Original result was aggregate type used for TexFailCtrl results 6592 // The actual instruction returns as a vector type which has now been 6593 // created. Remove the aggregate result. 6594 ResultTypes.erase(&ResultTypes[1]); 6595 } 6596 } 6597 6598 unsigned CPol = cast<ConstantSDNode>( 6599 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6600 if (BaseOpcode->Atomic) 6601 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6602 if (CPol & ~AMDGPU::CPol::ALL) 6603 return Op; 6604 6605 SmallVector<SDValue, 26> Ops; 6606 if (BaseOpcode->Store || BaseOpcode->Atomic) 6607 Ops.push_back(VData); // vdata 6608 if (UseNSA) 6609 append_range(Ops, VAddrs); 6610 else 6611 Ops.push_back(VAddr); 6612 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6613 if (BaseOpcode->Sampler) 6614 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6615 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6616 if (IsGFX10Plus) 6617 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6618 Ops.push_back(Unorm); 6619 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6620 Ops.push_back(IsA16 && // r128, a16 for gfx9 6621 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6622 if (IsGFX10Plus) 6623 Ops.push_back(IsA16 ? True : False); 6624 if (!Subtarget->hasGFX90AInsts()) { 6625 Ops.push_back(TFE); //tfe 6626 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6627 report_fatal_error("TFE is not supported on this GPU"); 6628 } 6629 Ops.push_back(LWE); // lwe 6630 if (!IsGFX10Plus) 6631 Ops.push_back(DimInfo->DA ? True : False); 6632 if (BaseOpcode->HasD16) 6633 Ops.push_back(IsD16 ? True : False); 6634 if (isa<MemSDNode>(Op)) 6635 Ops.push_back(Op.getOperand(0)); // chain 6636 6637 int NumVAddrDwords = 6638 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6639 int Opcode = -1; 6640 6641 if (IsGFX10Plus) { 6642 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6643 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6644 : AMDGPU::MIMGEncGfx10Default, 6645 NumVDataDwords, NumVAddrDwords); 6646 } else { 6647 if (Subtarget->hasGFX90AInsts()) { 6648 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6649 NumVDataDwords, NumVAddrDwords); 6650 if (Opcode == -1) 6651 report_fatal_error( 6652 "requested image instruction is not supported on this GPU"); 6653 } 6654 if (Opcode == -1 && 6655 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6656 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6657 NumVDataDwords, NumVAddrDwords); 6658 if (Opcode == -1) 6659 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6660 NumVDataDwords, NumVAddrDwords); 6661 } 6662 assert(Opcode != -1); 6663 6664 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6665 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6666 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6667 DAG.setNodeMemRefs(NewNode, {MemRef}); 6668 } 6669 6670 if (BaseOpcode->AtomicX2) { 6671 SmallVector<SDValue, 1> Elt; 6672 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6673 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6674 } 6675 if (BaseOpcode->Store) 6676 return SDValue(NewNode, 0); 6677 return constructRetValue(DAG, NewNode, 6678 OrigResultTypes, IsTexFail, 6679 Subtarget->hasUnpackedD16VMem(), IsD16, 6680 DMaskLanes, NumVDataDwords, DL); 6681 } 6682 6683 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6684 SDValue Offset, SDValue CachePolicy, 6685 SelectionDAG &DAG) const { 6686 MachineFunction &MF = DAG.getMachineFunction(); 6687 6688 const DataLayout &DataLayout = DAG.getDataLayout(); 6689 Align Alignment = 6690 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6691 6692 MachineMemOperand *MMO = MF.getMachineMemOperand( 6693 MachinePointerInfo(), 6694 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6695 MachineMemOperand::MOInvariant, 6696 VT.getStoreSize(), Alignment); 6697 6698 if (!Offset->isDivergent()) { 6699 SDValue Ops[] = { 6700 Rsrc, 6701 Offset, // Offset 6702 CachePolicy 6703 }; 6704 6705 // Widen vec3 load to vec4. 6706 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6707 EVT WidenedVT = 6708 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6709 auto WidenedOp = DAG.getMemIntrinsicNode( 6710 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6711 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6712 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6713 DAG.getVectorIdxConstant(0, DL)); 6714 return Subvector; 6715 } 6716 6717 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6718 DAG.getVTList(VT), Ops, VT, MMO); 6719 } 6720 6721 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6722 // assume that the buffer is unswizzled. 6723 SmallVector<SDValue, 4> Loads; 6724 unsigned NumLoads = 1; 6725 MVT LoadVT = VT.getSimpleVT(); 6726 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6727 assert((LoadVT.getScalarType() == MVT::i32 || 6728 LoadVT.getScalarType() == MVT::f32)); 6729 6730 if (NumElts == 8 || NumElts == 16) { 6731 NumLoads = NumElts / 4; 6732 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6733 } 6734 6735 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6736 SDValue Ops[] = { 6737 DAG.getEntryNode(), // Chain 6738 Rsrc, // rsrc 6739 DAG.getConstant(0, DL, MVT::i32), // vindex 6740 {}, // voffset 6741 {}, // soffset 6742 {}, // offset 6743 CachePolicy, // cachepolicy 6744 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6745 }; 6746 6747 // Use the alignment to ensure that the required offsets will fit into the 6748 // immediate offsets. 6749 setBufferOffsets(Offset, DAG, &Ops[3], 6750 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6751 6752 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6753 for (unsigned i = 0; i < NumLoads; ++i) { 6754 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6755 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6756 LoadVT, MMO, DAG)); 6757 } 6758 6759 if (NumElts == 8 || NumElts == 16) 6760 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6761 6762 return Loads[0]; 6763 } 6764 6765 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6766 unsigned Dim, 6767 const ArgDescriptor &Arg) const { 6768 SDLoc SL(Op); 6769 MachineFunction &MF = DAG.getMachineFunction(); 6770 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6771 if (MaxID == 0) 6772 return DAG.getConstant(0, SL, MVT::i32); 6773 6774 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6775 SDLoc(DAG.getEntryNode()), Arg); 6776 6777 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6778 // masking operations anyway. 6779 // 6780 // TODO: We could assert the top bit is 0 for the source copy. 6781 if (Arg.isMasked()) 6782 return Val; 6783 6784 // Preserve the known bits after expansion to a copy. 6785 EVT SmallVT = 6786 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6787 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6788 DAG.getValueType(SmallVT)); 6789 } 6790 6791 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6792 SelectionDAG &DAG) const { 6793 MachineFunction &MF = DAG.getMachineFunction(); 6794 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6795 6796 EVT VT = Op.getValueType(); 6797 SDLoc DL(Op); 6798 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6799 6800 // TODO: Should this propagate fast-math-flags? 6801 6802 switch (IntrinsicID) { 6803 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6804 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6805 return emitNonHSAIntrinsicError(DAG, DL, VT); 6806 return getPreloadedValue(DAG, *MFI, VT, 6807 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6808 } 6809 case Intrinsic::amdgcn_dispatch_ptr: 6810 case Intrinsic::amdgcn_queue_ptr: { 6811 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6812 DiagnosticInfoUnsupported BadIntrin( 6813 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6814 DL.getDebugLoc()); 6815 DAG.getContext()->diagnose(BadIntrin); 6816 return DAG.getUNDEF(VT); 6817 } 6818 6819 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6820 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6821 return getPreloadedValue(DAG, *MFI, VT, RegID); 6822 } 6823 case Intrinsic::amdgcn_implicitarg_ptr: { 6824 if (MFI->isEntryFunction()) 6825 return getImplicitArgPtr(DAG, DL); 6826 return getPreloadedValue(DAG, *MFI, VT, 6827 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6828 } 6829 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6830 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6831 // This only makes sense to call in a kernel, so just lower to null. 6832 return DAG.getConstant(0, DL, VT); 6833 } 6834 6835 return getPreloadedValue(DAG, *MFI, VT, 6836 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6837 } 6838 case Intrinsic::amdgcn_dispatch_id: { 6839 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6840 } 6841 case Intrinsic::amdgcn_rcp: 6842 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6843 case Intrinsic::amdgcn_rsq: 6844 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6845 case Intrinsic::amdgcn_rsq_legacy: 6846 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6847 return emitRemovedIntrinsicError(DAG, DL, VT); 6848 return SDValue(); 6849 case Intrinsic::amdgcn_rcp_legacy: 6850 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6851 return emitRemovedIntrinsicError(DAG, DL, VT); 6852 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6853 case Intrinsic::amdgcn_rsq_clamp: { 6854 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6855 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6856 6857 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6858 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6859 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6860 6861 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6862 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6863 DAG.getConstantFP(Max, DL, VT)); 6864 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6865 DAG.getConstantFP(Min, DL, VT)); 6866 } 6867 case Intrinsic::r600_read_ngroups_x: 6868 if (Subtarget->isAmdHsaOS()) 6869 return emitNonHSAIntrinsicError(DAG, DL, VT); 6870 6871 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6872 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6873 false); 6874 case Intrinsic::r600_read_ngroups_y: 6875 if (Subtarget->isAmdHsaOS()) 6876 return emitNonHSAIntrinsicError(DAG, DL, VT); 6877 6878 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6879 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6880 false); 6881 case Intrinsic::r600_read_ngroups_z: 6882 if (Subtarget->isAmdHsaOS()) 6883 return emitNonHSAIntrinsicError(DAG, DL, VT); 6884 6885 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6886 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6887 false); 6888 case Intrinsic::r600_read_global_size_x: 6889 if (Subtarget->isAmdHsaOS()) 6890 return emitNonHSAIntrinsicError(DAG, DL, VT); 6891 6892 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6893 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6894 Align(4), false); 6895 case Intrinsic::r600_read_global_size_y: 6896 if (Subtarget->isAmdHsaOS()) 6897 return emitNonHSAIntrinsicError(DAG, DL, VT); 6898 6899 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6900 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6901 Align(4), false); 6902 case Intrinsic::r600_read_global_size_z: 6903 if (Subtarget->isAmdHsaOS()) 6904 return emitNonHSAIntrinsicError(DAG, DL, VT); 6905 6906 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6907 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6908 Align(4), false); 6909 case Intrinsic::r600_read_local_size_x: 6910 if (Subtarget->isAmdHsaOS()) 6911 return emitNonHSAIntrinsicError(DAG, DL, VT); 6912 6913 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6914 SI::KernelInputOffsets::LOCAL_SIZE_X); 6915 case Intrinsic::r600_read_local_size_y: 6916 if (Subtarget->isAmdHsaOS()) 6917 return emitNonHSAIntrinsicError(DAG, DL, VT); 6918 6919 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6920 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6921 case Intrinsic::r600_read_local_size_z: 6922 if (Subtarget->isAmdHsaOS()) 6923 return emitNonHSAIntrinsicError(DAG, DL, VT); 6924 6925 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6926 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6927 case Intrinsic::amdgcn_workgroup_id_x: 6928 return getPreloadedValue(DAG, *MFI, VT, 6929 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6930 case Intrinsic::amdgcn_workgroup_id_y: 6931 return getPreloadedValue(DAG, *MFI, VT, 6932 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6933 case Intrinsic::amdgcn_workgroup_id_z: 6934 return getPreloadedValue(DAG, *MFI, VT, 6935 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6936 case Intrinsic::amdgcn_workitem_id_x: 6937 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6938 case Intrinsic::amdgcn_workitem_id_y: 6939 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6940 case Intrinsic::amdgcn_workitem_id_z: 6941 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6942 case Intrinsic::amdgcn_wavefrontsize: 6943 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6944 SDLoc(Op), MVT::i32); 6945 case Intrinsic::amdgcn_s_buffer_load: { 6946 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6947 if (CPol & ~AMDGPU::CPol::ALL) 6948 return Op; 6949 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6950 DAG); 6951 } 6952 case Intrinsic::amdgcn_fdiv_fast: 6953 return lowerFDIV_FAST(Op, DAG); 6954 case Intrinsic::amdgcn_sin: 6955 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6956 6957 case Intrinsic::amdgcn_cos: 6958 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6959 6960 case Intrinsic::amdgcn_mul_u24: 6961 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6962 case Intrinsic::amdgcn_mul_i24: 6963 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6964 6965 case Intrinsic::amdgcn_log_clamp: { 6966 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6967 return SDValue(); 6968 6969 return emitRemovedIntrinsicError(DAG, DL, VT); 6970 } 6971 case Intrinsic::amdgcn_ldexp: 6972 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6973 Op.getOperand(1), Op.getOperand(2)); 6974 6975 case Intrinsic::amdgcn_fract: 6976 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6977 6978 case Intrinsic::amdgcn_class: 6979 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6980 Op.getOperand(1), Op.getOperand(2)); 6981 case Intrinsic::amdgcn_div_fmas: 6982 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6983 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6984 Op.getOperand(4)); 6985 6986 case Intrinsic::amdgcn_div_fixup: 6987 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6988 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6989 6990 case Intrinsic::amdgcn_div_scale: { 6991 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6992 6993 // Translate to the operands expected by the machine instruction. The 6994 // first parameter must be the same as the first instruction. 6995 SDValue Numerator = Op.getOperand(1); 6996 SDValue Denominator = Op.getOperand(2); 6997 6998 // Note this order is opposite of the machine instruction's operations, 6999 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 7000 // intrinsic has the numerator as the first operand to match a normal 7001 // division operation. 7002 7003 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 7004 7005 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 7006 Denominator, Numerator); 7007 } 7008 case Intrinsic::amdgcn_icmp: { 7009 // There is a Pat that handles this variant, so return it as-is. 7010 if (Op.getOperand(1).getValueType() == MVT::i1 && 7011 Op.getConstantOperandVal(2) == 0 && 7012 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 7013 return Op; 7014 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 7015 } 7016 case Intrinsic::amdgcn_fcmp: { 7017 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 7018 } 7019 case Intrinsic::amdgcn_ballot: 7020 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 7021 case Intrinsic::amdgcn_fmed3: 7022 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 7023 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7024 case Intrinsic::amdgcn_fdot2: 7025 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 7026 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 7027 Op.getOperand(4)); 7028 case Intrinsic::amdgcn_fmul_legacy: 7029 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 7030 Op.getOperand(1), Op.getOperand(2)); 7031 case Intrinsic::amdgcn_sffbh: 7032 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 7033 case Intrinsic::amdgcn_sbfe: 7034 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 7035 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7036 case Intrinsic::amdgcn_ubfe: 7037 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 7038 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7039 case Intrinsic::amdgcn_cvt_pkrtz: 7040 case Intrinsic::amdgcn_cvt_pknorm_i16: 7041 case Intrinsic::amdgcn_cvt_pknorm_u16: 7042 case Intrinsic::amdgcn_cvt_pk_i16: 7043 case Intrinsic::amdgcn_cvt_pk_u16: { 7044 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 7045 EVT VT = Op.getValueType(); 7046 unsigned Opcode; 7047 7048 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 7049 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 7050 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 7051 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 7052 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 7053 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 7054 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 7055 Opcode = AMDGPUISD::CVT_PK_I16_I32; 7056 else 7057 Opcode = AMDGPUISD::CVT_PK_U16_U32; 7058 7059 if (isTypeLegal(VT)) 7060 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7061 7062 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 7063 Op.getOperand(1), Op.getOperand(2)); 7064 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 7065 } 7066 case Intrinsic::amdgcn_fmad_ftz: 7067 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 7068 Op.getOperand(2), Op.getOperand(3)); 7069 7070 case Intrinsic::amdgcn_if_break: 7071 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 7072 Op->getOperand(1), Op->getOperand(2)), 0); 7073 7074 case Intrinsic::amdgcn_groupstaticsize: { 7075 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 7076 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 7077 return Op; 7078 7079 const Module *M = MF.getFunction().getParent(); 7080 const GlobalValue *GV = 7081 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 7082 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 7083 SIInstrInfo::MO_ABS32_LO); 7084 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7085 } 7086 case Intrinsic::amdgcn_is_shared: 7087 case Intrinsic::amdgcn_is_private: { 7088 SDLoc SL(Op); 7089 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 7090 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7091 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7092 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7093 Op.getOperand(1)); 7094 7095 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7096 DAG.getConstant(1, SL, MVT::i32)); 7097 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7098 } 7099 case Intrinsic::amdgcn_perm: 7100 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7101 Op.getOperand(2), Op.getOperand(3)); 7102 case Intrinsic::amdgcn_reloc_constant: { 7103 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7104 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7105 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7106 auto RelocSymbol = cast<GlobalVariable>( 7107 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7108 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7109 SIInstrInfo::MO_ABS32_LO); 7110 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7111 } 7112 default: 7113 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7114 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7115 return lowerImage(Op, ImageDimIntr, DAG, false); 7116 7117 return Op; 7118 } 7119 } 7120 7121 /// Update \p MMO based on the offset inputs to an intrinsic. 7122 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7123 SDValue SOffset, SDValue Offset, 7124 SDValue VIndex = SDValue()) { 7125 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7126 !isa<ConstantSDNode>(Offset)) { 7127 // The combined offset is not known to be constant, so we cannot represent 7128 // it in the MMO. Give up. 7129 MMO->setValue((Value *)nullptr); 7130 return; 7131 } 7132 7133 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7134 !cast<ConstantSDNode>(VIndex)->isZero())) { 7135 // The strided index component of the address is not known to be zero, so we 7136 // cannot represent it in the MMO. Give up. 7137 MMO->setValue((Value *)nullptr); 7138 return; 7139 } 7140 7141 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7142 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7143 cast<ConstantSDNode>(Offset)->getSExtValue()); 7144 } 7145 7146 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7147 SelectionDAG &DAG, 7148 unsigned NewOpcode) const { 7149 SDLoc DL(Op); 7150 7151 SDValue VData = Op.getOperand(2); 7152 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7153 SDValue Ops[] = { 7154 Op.getOperand(0), // Chain 7155 VData, // vdata 7156 Op.getOperand(3), // rsrc 7157 DAG.getConstant(0, DL, MVT::i32), // vindex 7158 Offsets.first, // voffset 7159 Op.getOperand(5), // soffset 7160 Offsets.second, // offset 7161 Op.getOperand(6), // cachepolicy 7162 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7163 }; 7164 7165 auto *M = cast<MemSDNode>(Op); 7166 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7167 7168 EVT MemVT = VData.getValueType(); 7169 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7170 M->getMemOperand()); 7171 } 7172 7173 // Return a value to use for the idxen operand by examining the vindex operand. 7174 static unsigned getIdxEn(SDValue VIndex) { 7175 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7176 // No need to set idxen if vindex is known to be zero. 7177 return VIndexC->getZExtValue() != 0; 7178 return 1; 7179 } 7180 7181 SDValue 7182 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7183 unsigned NewOpcode) const { 7184 SDLoc DL(Op); 7185 7186 SDValue VData = Op.getOperand(2); 7187 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7188 SDValue Ops[] = { 7189 Op.getOperand(0), // Chain 7190 VData, // vdata 7191 Op.getOperand(3), // rsrc 7192 Op.getOperand(4), // vindex 7193 Offsets.first, // voffset 7194 Op.getOperand(6), // soffset 7195 Offsets.second, // offset 7196 Op.getOperand(7), // cachepolicy 7197 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7198 }; 7199 7200 auto *M = cast<MemSDNode>(Op); 7201 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7202 7203 EVT MemVT = VData.getValueType(); 7204 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7205 M->getMemOperand()); 7206 } 7207 7208 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7209 SelectionDAG &DAG) const { 7210 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7211 SDLoc DL(Op); 7212 7213 switch (IntrID) { 7214 case Intrinsic::amdgcn_ds_ordered_add: 7215 case Intrinsic::amdgcn_ds_ordered_swap: { 7216 MemSDNode *M = cast<MemSDNode>(Op); 7217 SDValue Chain = M->getOperand(0); 7218 SDValue M0 = M->getOperand(2); 7219 SDValue Value = M->getOperand(3); 7220 unsigned IndexOperand = M->getConstantOperandVal(7); 7221 unsigned WaveRelease = M->getConstantOperandVal(8); 7222 unsigned WaveDone = M->getConstantOperandVal(9); 7223 7224 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7225 IndexOperand &= ~0x3f; 7226 unsigned CountDw = 0; 7227 7228 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7229 CountDw = (IndexOperand >> 24) & 0xf; 7230 IndexOperand &= ~(0xf << 24); 7231 7232 if (CountDw < 1 || CountDw > 4) { 7233 report_fatal_error( 7234 "ds_ordered_count: dword count must be between 1 and 4"); 7235 } 7236 } 7237 7238 if (IndexOperand) 7239 report_fatal_error("ds_ordered_count: bad index operand"); 7240 7241 if (WaveDone && !WaveRelease) 7242 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7243 7244 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7245 unsigned ShaderType = 7246 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7247 unsigned Offset0 = OrderedCountIndex << 2; 7248 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7249 (Instruction << 4); 7250 7251 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7252 Offset1 |= (CountDw - 1) << 6; 7253 7254 unsigned Offset = Offset0 | (Offset1 << 8); 7255 7256 SDValue Ops[] = { 7257 Chain, 7258 Value, 7259 DAG.getTargetConstant(Offset, DL, MVT::i16), 7260 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7261 }; 7262 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7263 M->getVTList(), Ops, M->getMemoryVT(), 7264 M->getMemOperand()); 7265 } 7266 case Intrinsic::amdgcn_ds_fadd: { 7267 MemSDNode *M = cast<MemSDNode>(Op); 7268 unsigned Opc; 7269 switch (IntrID) { 7270 case Intrinsic::amdgcn_ds_fadd: 7271 Opc = ISD::ATOMIC_LOAD_FADD; 7272 break; 7273 } 7274 7275 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7276 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7277 M->getMemOperand()); 7278 } 7279 case Intrinsic::amdgcn_atomic_inc: 7280 case Intrinsic::amdgcn_atomic_dec: 7281 case Intrinsic::amdgcn_ds_fmin: 7282 case Intrinsic::amdgcn_ds_fmax: { 7283 MemSDNode *M = cast<MemSDNode>(Op); 7284 unsigned Opc; 7285 switch (IntrID) { 7286 case Intrinsic::amdgcn_atomic_inc: 7287 Opc = AMDGPUISD::ATOMIC_INC; 7288 break; 7289 case Intrinsic::amdgcn_atomic_dec: 7290 Opc = AMDGPUISD::ATOMIC_DEC; 7291 break; 7292 case Intrinsic::amdgcn_ds_fmin: 7293 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7294 break; 7295 case Intrinsic::amdgcn_ds_fmax: 7296 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7297 break; 7298 default: 7299 llvm_unreachable("Unknown intrinsic!"); 7300 } 7301 SDValue Ops[] = { 7302 M->getOperand(0), // Chain 7303 M->getOperand(2), // Ptr 7304 M->getOperand(3) // Value 7305 }; 7306 7307 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7308 M->getMemoryVT(), M->getMemOperand()); 7309 } 7310 case Intrinsic::amdgcn_buffer_load: 7311 case Intrinsic::amdgcn_buffer_load_format: { 7312 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7313 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7314 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7315 SDValue Ops[] = { 7316 Op.getOperand(0), // Chain 7317 Op.getOperand(2), // rsrc 7318 Op.getOperand(3), // vindex 7319 SDValue(), // voffset -- will be set by setBufferOffsets 7320 SDValue(), // soffset -- will be set by setBufferOffsets 7321 SDValue(), // offset -- will be set by setBufferOffsets 7322 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7323 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7324 }; 7325 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7326 7327 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7328 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7329 7330 EVT VT = Op.getValueType(); 7331 EVT IntVT = VT.changeTypeToInteger(); 7332 auto *M = cast<MemSDNode>(Op); 7333 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7334 EVT LoadVT = Op.getValueType(); 7335 7336 if (LoadVT.getScalarType() == MVT::f16) 7337 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7338 M, DAG, Ops); 7339 7340 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7341 if (LoadVT.getScalarType() == MVT::i8 || 7342 LoadVT.getScalarType() == MVT::i16) 7343 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7344 7345 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7346 M->getMemOperand(), DAG); 7347 } 7348 case Intrinsic::amdgcn_raw_buffer_load: 7349 case Intrinsic::amdgcn_raw_buffer_load_format: { 7350 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7351 7352 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7353 SDValue Ops[] = { 7354 Op.getOperand(0), // Chain 7355 Op.getOperand(2), // rsrc 7356 DAG.getConstant(0, DL, MVT::i32), // vindex 7357 Offsets.first, // voffset 7358 Op.getOperand(4), // soffset 7359 Offsets.second, // offset 7360 Op.getOperand(5), // cachepolicy, swizzled buffer 7361 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7362 }; 7363 7364 auto *M = cast<MemSDNode>(Op); 7365 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7366 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7367 } 7368 case Intrinsic::amdgcn_struct_buffer_load: 7369 case Intrinsic::amdgcn_struct_buffer_load_format: { 7370 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7371 7372 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7373 SDValue Ops[] = { 7374 Op.getOperand(0), // Chain 7375 Op.getOperand(2), // rsrc 7376 Op.getOperand(3), // vindex 7377 Offsets.first, // voffset 7378 Op.getOperand(5), // soffset 7379 Offsets.second, // offset 7380 Op.getOperand(6), // cachepolicy, swizzled buffer 7381 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7382 }; 7383 7384 auto *M = cast<MemSDNode>(Op); 7385 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7386 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7387 } 7388 case Intrinsic::amdgcn_tbuffer_load: { 7389 MemSDNode *M = cast<MemSDNode>(Op); 7390 EVT LoadVT = Op.getValueType(); 7391 7392 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7393 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7394 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7395 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7396 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7397 SDValue Ops[] = { 7398 Op.getOperand(0), // Chain 7399 Op.getOperand(2), // rsrc 7400 Op.getOperand(3), // vindex 7401 Op.getOperand(4), // voffset 7402 Op.getOperand(5), // soffset 7403 Op.getOperand(6), // offset 7404 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7405 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7406 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7407 }; 7408 7409 if (LoadVT.getScalarType() == MVT::f16) 7410 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7411 M, DAG, Ops); 7412 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7413 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7414 DAG); 7415 } 7416 case Intrinsic::amdgcn_raw_tbuffer_load: { 7417 MemSDNode *M = cast<MemSDNode>(Op); 7418 EVT LoadVT = Op.getValueType(); 7419 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7420 7421 SDValue Ops[] = { 7422 Op.getOperand(0), // Chain 7423 Op.getOperand(2), // rsrc 7424 DAG.getConstant(0, DL, MVT::i32), // vindex 7425 Offsets.first, // voffset 7426 Op.getOperand(4), // soffset 7427 Offsets.second, // offset 7428 Op.getOperand(5), // format 7429 Op.getOperand(6), // cachepolicy, swizzled buffer 7430 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7431 }; 7432 7433 if (LoadVT.getScalarType() == MVT::f16) 7434 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7435 M, DAG, Ops); 7436 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7437 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7438 DAG); 7439 } 7440 case Intrinsic::amdgcn_struct_tbuffer_load: { 7441 MemSDNode *M = cast<MemSDNode>(Op); 7442 EVT LoadVT = Op.getValueType(); 7443 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7444 7445 SDValue Ops[] = { 7446 Op.getOperand(0), // Chain 7447 Op.getOperand(2), // rsrc 7448 Op.getOperand(3), // vindex 7449 Offsets.first, // voffset 7450 Op.getOperand(5), // soffset 7451 Offsets.second, // offset 7452 Op.getOperand(6), // format 7453 Op.getOperand(7), // cachepolicy, swizzled buffer 7454 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7455 }; 7456 7457 if (LoadVT.getScalarType() == MVT::f16) 7458 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7459 M, DAG, Ops); 7460 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7461 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7462 DAG); 7463 } 7464 case Intrinsic::amdgcn_buffer_atomic_swap: 7465 case Intrinsic::amdgcn_buffer_atomic_add: 7466 case Intrinsic::amdgcn_buffer_atomic_sub: 7467 case Intrinsic::amdgcn_buffer_atomic_csub: 7468 case Intrinsic::amdgcn_buffer_atomic_smin: 7469 case Intrinsic::amdgcn_buffer_atomic_umin: 7470 case Intrinsic::amdgcn_buffer_atomic_smax: 7471 case Intrinsic::amdgcn_buffer_atomic_umax: 7472 case Intrinsic::amdgcn_buffer_atomic_and: 7473 case Intrinsic::amdgcn_buffer_atomic_or: 7474 case Intrinsic::amdgcn_buffer_atomic_xor: 7475 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7476 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7477 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7478 SDValue Ops[] = { 7479 Op.getOperand(0), // Chain 7480 Op.getOperand(2), // vdata 7481 Op.getOperand(3), // rsrc 7482 Op.getOperand(4), // vindex 7483 SDValue(), // voffset -- will be set by setBufferOffsets 7484 SDValue(), // soffset -- will be set by setBufferOffsets 7485 SDValue(), // offset -- will be set by setBufferOffsets 7486 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7487 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7488 }; 7489 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7490 7491 EVT VT = Op.getValueType(); 7492 7493 auto *M = cast<MemSDNode>(Op); 7494 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7495 unsigned Opcode = 0; 7496 7497 switch (IntrID) { 7498 case Intrinsic::amdgcn_buffer_atomic_swap: 7499 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7500 break; 7501 case Intrinsic::amdgcn_buffer_atomic_add: 7502 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7503 break; 7504 case Intrinsic::amdgcn_buffer_atomic_sub: 7505 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7506 break; 7507 case Intrinsic::amdgcn_buffer_atomic_csub: 7508 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7509 break; 7510 case Intrinsic::amdgcn_buffer_atomic_smin: 7511 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7512 break; 7513 case Intrinsic::amdgcn_buffer_atomic_umin: 7514 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7515 break; 7516 case Intrinsic::amdgcn_buffer_atomic_smax: 7517 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7518 break; 7519 case Intrinsic::amdgcn_buffer_atomic_umax: 7520 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7521 break; 7522 case Intrinsic::amdgcn_buffer_atomic_and: 7523 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7524 break; 7525 case Intrinsic::amdgcn_buffer_atomic_or: 7526 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7527 break; 7528 case Intrinsic::amdgcn_buffer_atomic_xor: 7529 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7530 break; 7531 case Intrinsic::amdgcn_buffer_atomic_fadd: 7532 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7533 DiagnosticInfoUnsupported 7534 NoFpRet(DAG.getMachineFunction().getFunction(), 7535 "return versions of fp atomics not supported", 7536 DL.getDebugLoc(), DS_Error); 7537 DAG.getContext()->diagnose(NoFpRet); 7538 return SDValue(); 7539 } 7540 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7541 break; 7542 default: 7543 llvm_unreachable("unhandled atomic opcode"); 7544 } 7545 7546 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7547 M->getMemOperand()); 7548 } 7549 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7550 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7551 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7552 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7553 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7554 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7555 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7556 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7557 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7558 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7559 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7560 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7561 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7562 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7563 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7564 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7565 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7566 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7567 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7568 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7569 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7570 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7571 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7572 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7573 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7574 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7575 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7576 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7577 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7578 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7579 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7580 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7581 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7582 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7583 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7584 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7585 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7586 return lowerStructBufferAtomicIntrin(Op, DAG, 7587 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7588 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7589 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7590 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7591 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7592 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7593 return lowerStructBufferAtomicIntrin(Op, DAG, 7594 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7595 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7596 return lowerStructBufferAtomicIntrin(Op, DAG, 7597 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7598 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7599 return lowerStructBufferAtomicIntrin(Op, DAG, 7600 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7601 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7602 return lowerStructBufferAtomicIntrin(Op, DAG, 7603 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7604 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7605 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7606 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7607 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7608 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7609 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7610 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7611 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7612 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7613 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7614 7615 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7616 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7617 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7618 SDValue Ops[] = { 7619 Op.getOperand(0), // Chain 7620 Op.getOperand(2), // src 7621 Op.getOperand(3), // cmp 7622 Op.getOperand(4), // rsrc 7623 Op.getOperand(5), // vindex 7624 SDValue(), // voffset -- will be set by setBufferOffsets 7625 SDValue(), // soffset -- will be set by setBufferOffsets 7626 SDValue(), // offset -- will be set by setBufferOffsets 7627 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7628 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7629 }; 7630 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7631 7632 EVT VT = Op.getValueType(); 7633 auto *M = cast<MemSDNode>(Op); 7634 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7635 7636 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7637 Op->getVTList(), Ops, VT, M->getMemOperand()); 7638 } 7639 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7640 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7641 SDValue Ops[] = { 7642 Op.getOperand(0), // Chain 7643 Op.getOperand(2), // src 7644 Op.getOperand(3), // cmp 7645 Op.getOperand(4), // rsrc 7646 DAG.getConstant(0, DL, MVT::i32), // vindex 7647 Offsets.first, // voffset 7648 Op.getOperand(6), // soffset 7649 Offsets.second, // offset 7650 Op.getOperand(7), // cachepolicy 7651 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7652 }; 7653 EVT VT = Op.getValueType(); 7654 auto *M = cast<MemSDNode>(Op); 7655 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7656 7657 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7658 Op->getVTList(), Ops, VT, M->getMemOperand()); 7659 } 7660 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7661 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7662 SDValue Ops[] = { 7663 Op.getOperand(0), // Chain 7664 Op.getOperand(2), // src 7665 Op.getOperand(3), // cmp 7666 Op.getOperand(4), // rsrc 7667 Op.getOperand(5), // vindex 7668 Offsets.first, // voffset 7669 Op.getOperand(7), // soffset 7670 Offsets.second, // offset 7671 Op.getOperand(8), // cachepolicy 7672 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7673 }; 7674 EVT VT = Op.getValueType(); 7675 auto *M = cast<MemSDNode>(Op); 7676 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7677 7678 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7679 Op->getVTList(), Ops, VT, M->getMemOperand()); 7680 } 7681 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7682 MemSDNode *M = cast<MemSDNode>(Op); 7683 SDValue NodePtr = M->getOperand(2); 7684 SDValue RayExtent = M->getOperand(3); 7685 SDValue RayOrigin = M->getOperand(4); 7686 SDValue RayDir = M->getOperand(5); 7687 SDValue RayInvDir = M->getOperand(6); 7688 SDValue TDescr = M->getOperand(7); 7689 7690 assert(NodePtr.getValueType() == MVT::i32 || 7691 NodePtr.getValueType() == MVT::i64); 7692 assert(RayDir.getValueType() == MVT::v3f16 || 7693 RayDir.getValueType() == MVT::v3f32); 7694 7695 if (!Subtarget->hasGFX10_AEncoding()) { 7696 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7697 return SDValue(); 7698 } 7699 7700 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7701 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7702 const unsigned NumVDataDwords = 4; 7703 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7704 const bool UseNSA = Subtarget->hasNSAEncoding() && 7705 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7706 const unsigned BaseOpcodes[2][2] = { 7707 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7708 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7709 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7710 int Opcode; 7711 if (UseNSA) { 7712 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7713 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7714 NumVAddrDwords); 7715 } else { 7716 Opcode = AMDGPU::getMIMGOpcode( 7717 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7718 PowerOf2Ceil(NumVAddrDwords)); 7719 } 7720 assert(Opcode != -1); 7721 7722 SmallVector<SDValue, 16> Ops; 7723 7724 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7725 SmallVector<SDValue, 3> Lanes; 7726 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7727 if (Lanes[0].getValueSizeInBits() == 32) { 7728 for (unsigned I = 0; I < 3; ++I) 7729 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7730 } else { 7731 if (IsAligned) { 7732 Ops.push_back( 7733 DAG.getBitcast(MVT::i32, 7734 DAG.getBuildVector(MVT::v2f16, DL, 7735 { Lanes[0], Lanes[1] }))); 7736 Ops.push_back(Lanes[2]); 7737 } else { 7738 SDValue Elt0 = Ops.pop_back_val(); 7739 Ops.push_back( 7740 DAG.getBitcast(MVT::i32, 7741 DAG.getBuildVector(MVT::v2f16, DL, 7742 { Elt0, Lanes[0] }))); 7743 Ops.push_back( 7744 DAG.getBitcast(MVT::i32, 7745 DAG.getBuildVector(MVT::v2f16, DL, 7746 { Lanes[1], Lanes[2] }))); 7747 } 7748 } 7749 }; 7750 7751 if (Is64) 7752 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7753 else 7754 Ops.push_back(NodePtr); 7755 7756 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7757 packLanes(RayOrigin, true); 7758 packLanes(RayDir, true); 7759 packLanes(RayInvDir, false); 7760 7761 if (!UseNSA) { 7762 // Build a single vector containing all the operands so far prepared. 7763 if (NumVAddrDwords > 8) { 7764 SDValue Undef = DAG.getUNDEF(MVT::i32); 7765 Ops.append(16 - Ops.size(), Undef); 7766 } 7767 assert(Ops.size() == 8 || Ops.size() == 16); 7768 SDValue MergedOps = DAG.getBuildVector( 7769 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7770 Ops.clear(); 7771 Ops.push_back(MergedOps); 7772 } 7773 7774 Ops.push_back(TDescr); 7775 if (IsA16) 7776 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7777 Ops.push_back(M->getChain()); 7778 7779 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7780 MachineMemOperand *MemRef = M->getMemOperand(); 7781 DAG.setNodeMemRefs(NewNode, {MemRef}); 7782 return SDValue(NewNode, 0); 7783 } 7784 case Intrinsic::amdgcn_global_atomic_fadd: 7785 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7786 DiagnosticInfoUnsupported 7787 NoFpRet(DAG.getMachineFunction().getFunction(), 7788 "return versions of fp atomics not supported", 7789 DL.getDebugLoc(), DS_Error); 7790 DAG.getContext()->diagnose(NoFpRet); 7791 return SDValue(); 7792 } 7793 LLVM_FALLTHROUGH; 7794 case Intrinsic::amdgcn_global_atomic_fmin: 7795 case Intrinsic::amdgcn_global_atomic_fmax: 7796 case Intrinsic::amdgcn_flat_atomic_fadd: 7797 case Intrinsic::amdgcn_flat_atomic_fmin: 7798 case Intrinsic::amdgcn_flat_atomic_fmax: { 7799 MemSDNode *M = cast<MemSDNode>(Op); 7800 SDValue Ops[] = { 7801 M->getOperand(0), // Chain 7802 M->getOperand(2), // Ptr 7803 M->getOperand(3) // Value 7804 }; 7805 unsigned Opcode = 0; 7806 switch (IntrID) { 7807 case Intrinsic::amdgcn_global_atomic_fadd: 7808 case Intrinsic::amdgcn_flat_atomic_fadd: { 7809 EVT VT = Op.getOperand(3).getValueType(); 7810 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7811 DAG.getVTList(VT, MVT::Other), Ops, 7812 M->getMemOperand()); 7813 } 7814 case Intrinsic::amdgcn_global_atomic_fmin: 7815 case Intrinsic::amdgcn_flat_atomic_fmin: { 7816 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7817 break; 7818 } 7819 case Intrinsic::amdgcn_global_atomic_fmax: 7820 case Intrinsic::amdgcn_flat_atomic_fmax: { 7821 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7822 break; 7823 } 7824 default: 7825 llvm_unreachable("unhandled atomic opcode"); 7826 } 7827 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7828 M->getVTList(), Ops, M->getMemoryVT(), 7829 M->getMemOperand()); 7830 } 7831 default: 7832 7833 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7834 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7835 return lowerImage(Op, ImageDimIntr, DAG, true); 7836 7837 return SDValue(); 7838 } 7839 } 7840 7841 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7842 // dwordx4 if on SI. 7843 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7844 SDVTList VTList, 7845 ArrayRef<SDValue> Ops, EVT MemVT, 7846 MachineMemOperand *MMO, 7847 SelectionDAG &DAG) const { 7848 EVT VT = VTList.VTs[0]; 7849 EVT WidenedVT = VT; 7850 EVT WidenedMemVT = MemVT; 7851 if (!Subtarget->hasDwordx3LoadStores() && 7852 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7853 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7854 WidenedVT.getVectorElementType(), 4); 7855 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7856 WidenedMemVT.getVectorElementType(), 4); 7857 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7858 } 7859 7860 assert(VTList.NumVTs == 2); 7861 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7862 7863 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7864 WidenedMemVT, MMO); 7865 if (WidenedVT != VT) { 7866 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7867 DAG.getVectorIdxConstant(0, DL)); 7868 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7869 } 7870 return NewOp; 7871 } 7872 7873 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7874 bool ImageStore) const { 7875 EVT StoreVT = VData.getValueType(); 7876 7877 // No change for f16 and legal vector D16 types. 7878 if (!StoreVT.isVector()) 7879 return VData; 7880 7881 SDLoc DL(VData); 7882 unsigned NumElements = StoreVT.getVectorNumElements(); 7883 7884 if (Subtarget->hasUnpackedD16VMem()) { 7885 // We need to unpack the packed data to store. 7886 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7887 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7888 7889 EVT EquivStoreVT = 7890 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7891 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7892 return DAG.UnrollVectorOp(ZExt.getNode()); 7893 } 7894 7895 // The sq block of gfx8.1 does not estimate register use correctly for d16 7896 // image store instructions. The data operand is computed as if it were not a 7897 // d16 image instruction. 7898 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7899 // Bitcast to i16 7900 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7901 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7902 7903 // Decompose into scalars 7904 SmallVector<SDValue, 4> Elts; 7905 DAG.ExtractVectorElements(IntVData, Elts); 7906 7907 // Group pairs of i16 into v2i16 and bitcast to i32 7908 SmallVector<SDValue, 4> PackedElts; 7909 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7910 SDValue Pair = 7911 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7912 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7913 PackedElts.push_back(IntPair); 7914 } 7915 if ((NumElements % 2) == 1) { 7916 // Handle v3i16 7917 unsigned I = Elts.size() / 2; 7918 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7919 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7920 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7921 PackedElts.push_back(IntPair); 7922 } 7923 7924 // Pad using UNDEF 7925 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7926 7927 // Build final vector 7928 EVT VecVT = 7929 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7930 return DAG.getBuildVector(VecVT, DL, PackedElts); 7931 } 7932 7933 if (NumElements == 3) { 7934 EVT IntStoreVT = 7935 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7936 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7937 7938 EVT WidenedStoreVT = EVT::getVectorVT( 7939 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7940 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7941 WidenedStoreVT.getStoreSizeInBits()); 7942 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7943 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7944 } 7945 7946 assert(isTypeLegal(StoreVT)); 7947 return VData; 7948 } 7949 7950 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7951 SelectionDAG &DAG) const { 7952 SDLoc DL(Op); 7953 SDValue Chain = Op.getOperand(0); 7954 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7955 MachineFunction &MF = DAG.getMachineFunction(); 7956 7957 switch (IntrinsicID) { 7958 case Intrinsic::amdgcn_exp_compr: { 7959 SDValue Src0 = Op.getOperand(4); 7960 SDValue Src1 = Op.getOperand(5); 7961 // Hack around illegal type on SI by directly selecting it. 7962 if (isTypeLegal(Src0.getValueType())) 7963 return SDValue(); 7964 7965 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7966 SDValue Undef = DAG.getUNDEF(MVT::f32); 7967 const SDValue Ops[] = { 7968 Op.getOperand(2), // tgt 7969 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7970 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7971 Undef, // src2 7972 Undef, // src3 7973 Op.getOperand(7), // vm 7974 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7975 Op.getOperand(3), // en 7976 Op.getOperand(0) // Chain 7977 }; 7978 7979 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7980 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7981 } 7982 case Intrinsic::amdgcn_s_barrier: { 7983 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7984 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7985 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7986 if (WGSize <= ST.getWavefrontSize()) 7987 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7988 Op.getOperand(0)), 0); 7989 } 7990 return SDValue(); 7991 }; 7992 case Intrinsic::amdgcn_tbuffer_store: { 7993 SDValue VData = Op.getOperand(2); 7994 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7995 if (IsD16) 7996 VData = handleD16VData(VData, DAG); 7997 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7998 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7999 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 8000 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 8001 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8002 SDValue Ops[] = { 8003 Chain, 8004 VData, // vdata 8005 Op.getOperand(3), // rsrc 8006 Op.getOperand(4), // vindex 8007 Op.getOperand(5), // voffset 8008 Op.getOperand(6), // soffset 8009 Op.getOperand(7), // offset 8010 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 8011 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8012 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8013 }; 8014 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8015 AMDGPUISD::TBUFFER_STORE_FORMAT; 8016 MemSDNode *M = cast<MemSDNode>(Op); 8017 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8018 M->getMemoryVT(), M->getMemOperand()); 8019 } 8020 8021 case Intrinsic::amdgcn_struct_tbuffer_store: { 8022 SDValue VData = Op.getOperand(2); 8023 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8024 if (IsD16) 8025 VData = handleD16VData(VData, DAG); 8026 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8027 SDValue Ops[] = { 8028 Chain, 8029 VData, // vdata 8030 Op.getOperand(3), // rsrc 8031 Op.getOperand(4), // vindex 8032 Offsets.first, // voffset 8033 Op.getOperand(6), // soffset 8034 Offsets.second, // offset 8035 Op.getOperand(7), // format 8036 Op.getOperand(8), // cachepolicy, swizzled buffer 8037 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8038 }; 8039 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8040 AMDGPUISD::TBUFFER_STORE_FORMAT; 8041 MemSDNode *M = cast<MemSDNode>(Op); 8042 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8043 M->getMemoryVT(), M->getMemOperand()); 8044 } 8045 8046 case Intrinsic::amdgcn_raw_tbuffer_store: { 8047 SDValue VData = Op.getOperand(2); 8048 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8049 if (IsD16) 8050 VData = handleD16VData(VData, DAG); 8051 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8052 SDValue Ops[] = { 8053 Chain, 8054 VData, // vdata 8055 Op.getOperand(3), // rsrc 8056 DAG.getConstant(0, DL, MVT::i32), // vindex 8057 Offsets.first, // voffset 8058 Op.getOperand(5), // soffset 8059 Offsets.second, // offset 8060 Op.getOperand(6), // format 8061 Op.getOperand(7), // cachepolicy, swizzled buffer 8062 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8063 }; 8064 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8065 AMDGPUISD::TBUFFER_STORE_FORMAT; 8066 MemSDNode *M = cast<MemSDNode>(Op); 8067 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8068 M->getMemoryVT(), M->getMemOperand()); 8069 } 8070 8071 case Intrinsic::amdgcn_buffer_store: 8072 case Intrinsic::amdgcn_buffer_store_format: { 8073 SDValue VData = Op.getOperand(2); 8074 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8075 if (IsD16) 8076 VData = handleD16VData(VData, DAG); 8077 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8078 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8079 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8080 SDValue Ops[] = { 8081 Chain, 8082 VData, 8083 Op.getOperand(3), // rsrc 8084 Op.getOperand(4), // vindex 8085 SDValue(), // voffset -- will be set by setBufferOffsets 8086 SDValue(), // soffset -- will be set by setBufferOffsets 8087 SDValue(), // offset -- will be set by setBufferOffsets 8088 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8089 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8090 }; 8091 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8092 8093 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8094 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8095 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8096 MemSDNode *M = cast<MemSDNode>(Op); 8097 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8098 8099 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8100 EVT VDataType = VData.getValueType().getScalarType(); 8101 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8102 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8103 8104 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8105 M->getMemoryVT(), M->getMemOperand()); 8106 } 8107 8108 case Intrinsic::amdgcn_raw_buffer_store: 8109 case Intrinsic::amdgcn_raw_buffer_store_format: { 8110 const bool IsFormat = 8111 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8112 8113 SDValue VData = Op.getOperand(2); 8114 EVT VDataVT = VData.getValueType(); 8115 EVT EltType = VDataVT.getScalarType(); 8116 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8117 if (IsD16) { 8118 VData = handleD16VData(VData, DAG); 8119 VDataVT = VData.getValueType(); 8120 } 8121 8122 if (!isTypeLegal(VDataVT)) { 8123 VData = 8124 DAG.getNode(ISD::BITCAST, DL, 8125 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8126 } 8127 8128 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8129 SDValue Ops[] = { 8130 Chain, 8131 VData, 8132 Op.getOperand(3), // rsrc 8133 DAG.getConstant(0, DL, MVT::i32), // vindex 8134 Offsets.first, // voffset 8135 Op.getOperand(5), // soffset 8136 Offsets.second, // offset 8137 Op.getOperand(6), // cachepolicy, swizzled buffer 8138 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8139 }; 8140 unsigned Opc = 8141 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8142 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8143 MemSDNode *M = cast<MemSDNode>(Op); 8144 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8145 8146 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8147 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8148 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8149 8150 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8151 M->getMemoryVT(), M->getMemOperand()); 8152 } 8153 8154 case Intrinsic::amdgcn_struct_buffer_store: 8155 case Intrinsic::amdgcn_struct_buffer_store_format: { 8156 const bool IsFormat = 8157 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8158 8159 SDValue VData = Op.getOperand(2); 8160 EVT VDataVT = VData.getValueType(); 8161 EVT EltType = VDataVT.getScalarType(); 8162 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8163 8164 if (IsD16) { 8165 VData = handleD16VData(VData, DAG); 8166 VDataVT = VData.getValueType(); 8167 } 8168 8169 if (!isTypeLegal(VDataVT)) { 8170 VData = 8171 DAG.getNode(ISD::BITCAST, DL, 8172 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8173 } 8174 8175 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8176 SDValue Ops[] = { 8177 Chain, 8178 VData, 8179 Op.getOperand(3), // rsrc 8180 Op.getOperand(4), // vindex 8181 Offsets.first, // voffset 8182 Op.getOperand(6), // soffset 8183 Offsets.second, // offset 8184 Op.getOperand(7), // cachepolicy, swizzled buffer 8185 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8186 }; 8187 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8188 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8189 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8190 MemSDNode *M = cast<MemSDNode>(Op); 8191 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8192 8193 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8194 EVT VDataType = VData.getValueType().getScalarType(); 8195 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8196 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8197 8198 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8199 M->getMemoryVT(), M->getMemOperand()); 8200 } 8201 case Intrinsic::amdgcn_end_cf: 8202 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8203 Op->getOperand(2), Chain), 0); 8204 8205 default: { 8206 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8207 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8208 return lowerImage(Op, ImageDimIntr, DAG, true); 8209 8210 return Op; 8211 } 8212 } 8213 } 8214 8215 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8216 // offset (the offset that is included in bounds checking and swizzling, to be 8217 // split between the instruction's voffset and immoffset fields) and soffset 8218 // (the offset that is excluded from bounds checking and swizzling, to go in 8219 // the instruction's soffset field). This function takes the first kind of 8220 // offset and figures out how to split it between voffset and immoffset. 8221 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8222 SDValue Offset, SelectionDAG &DAG) const { 8223 SDLoc DL(Offset); 8224 const unsigned MaxImm = 4095; 8225 SDValue N0 = Offset; 8226 ConstantSDNode *C1 = nullptr; 8227 8228 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8229 N0 = SDValue(); 8230 else if (DAG.isBaseWithConstantOffset(N0)) { 8231 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8232 N0 = N0.getOperand(0); 8233 } 8234 8235 if (C1) { 8236 unsigned ImmOffset = C1->getZExtValue(); 8237 // If the immediate value is too big for the immoffset field, put the value 8238 // and -4096 into the immoffset field so that the value that is copied/added 8239 // for the voffset field is a multiple of 4096, and it stands more chance 8240 // of being CSEd with the copy/add for another similar load/store. 8241 // However, do not do that rounding down to a multiple of 4096 if that is a 8242 // negative number, as it appears to be illegal to have a negative offset 8243 // in the vgpr, even if adding the immediate offset makes it positive. 8244 unsigned Overflow = ImmOffset & ~MaxImm; 8245 ImmOffset -= Overflow; 8246 if ((int32_t)Overflow < 0) { 8247 Overflow += ImmOffset; 8248 ImmOffset = 0; 8249 } 8250 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8251 if (Overflow) { 8252 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8253 if (!N0) 8254 N0 = OverflowVal; 8255 else { 8256 SDValue Ops[] = { N0, OverflowVal }; 8257 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8258 } 8259 } 8260 } 8261 if (!N0) 8262 N0 = DAG.getConstant(0, DL, MVT::i32); 8263 if (!C1) 8264 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8265 return {N0, SDValue(C1, 0)}; 8266 } 8267 8268 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8269 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8270 // pointed to by Offsets. 8271 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8272 SelectionDAG &DAG, SDValue *Offsets, 8273 Align Alignment) const { 8274 SDLoc DL(CombinedOffset); 8275 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8276 uint32_t Imm = C->getZExtValue(); 8277 uint32_t SOffset, ImmOffset; 8278 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8279 Alignment)) { 8280 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8281 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8282 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8283 return; 8284 } 8285 } 8286 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8287 SDValue N0 = CombinedOffset.getOperand(0); 8288 SDValue N1 = CombinedOffset.getOperand(1); 8289 uint32_t SOffset, ImmOffset; 8290 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8291 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8292 Subtarget, Alignment)) { 8293 Offsets[0] = N0; 8294 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8295 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8296 return; 8297 } 8298 } 8299 Offsets[0] = CombinedOffset; 8300 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8301 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8302 } 8303 8304 // Handle 8 bit and 16 bit buffer loads 8305 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8306 EVT LoadVT, SDLoc DL, 8307 ArrayRef<SDValue> Ops, 8308 MemSDNode *M) const { 8309 EVT IntVT = LoadVT.changeTypeToInteger(); 8310 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8311 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8312 8313 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8314 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8315 Ops, IntVT, 8316 M->getMemOperand()); 8317 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8318 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8319 8320 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8321 } 8322 8323 // Handle 8 bit and 16 bit buffer stores 8324 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8325 EVT VDataType, SDLoc DL, 8326 SDValue Ops[], 8327 MemSDNode *M) const { 8328 if (VDataType == MVT::f16) 8329 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8330 8331 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8332 Ops[1] = BufferStoreExt; 8333 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8334 AMDGPUISD::BUFFER_STORE_SHORT; 8335 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8336 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8337 M->getMemOperand()); 8338 } 8339 8340 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8341 ISD::LoadExtType ExtType, SDValue Op, 8342 const SDLoc &SL, EVT VT) { 8343 if (VT.bitsLT(Op.getValueType())) 8344 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8345 8346 switch (ExtType) { 8347 case ISD::SEXTLOAD: 8348 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8349 case ISD::ZEXTLOAD: 8350 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8351 case ISD::EXTLOAD: 8352 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8353 case ISD::NON_EXTLOAD: 8354 return Op; 8355 } 8356 8357 llvm_unreachable("invalid ext type"); 8358 } 8359 8360 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8361 SelectionDAG &DAG = DCI.DAG; 8362 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8363 return SDValue(); 8364 8365 // FIXME: Constant loads should all be marked invariant. 8366 unsigned AS = Ld->getAddressSpace(); 8367 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8368 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8369 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8370 return SDValue(); 8371 8372 // Don't do this early, since it may interfere with adjacent load merging for 8373 // illegal types. We can avoid losing alignment information for exotic types 8374 // pre-legalize. 8375 EVT MemVT = Ld->getMemoryVT(); 8376 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8377 MemVT.getSizeInBits() >= 32) 8378 return SDValue(); 8379 8380 SDLoc SL(Ld); 8381 8382 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8383 "unexpected vector extload"); 8384 8385 // TODO: Drop only high part of range. 8386 SDValue Ptr = Ld->getBasePtr(); 8387 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8388 MVT::i32, SL, Ld->getChain(), Ptr, 8389 Ld->getOffset(), 8390 Ld->getPointerInfo(), MVT::i32, 8391 Ld->getAlignment(), 8392 Ld->getMemOperand()->getFlags(), 8393 Ld->getAAInfo(), 8394 nullptr); // Drop ranges 8395 8396 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8397 if (MemVT.isFloatingPoint()) { 8398 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8399 "unexpected fp extload"); 8400 TruncVT = MemVT.changeTypeToInteger(); 8401 } 8402 8403 SDValue Cvt = NewLoad; 8404 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8405 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8406 DAG.getValueType(TruncVT)); 8407 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8408 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8409 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8410 } else { 8411 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8412 } 8413 8414 EVT VT = Ld->getValueType(0); 8415 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8416 8417 DCI.AddToWorklist(Cvt.getNode()); 8418 8419 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8420 // the appropriate extension from the 32-bit load. 8421 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8422 DCI.AddToWorklist(Cvt.getNode()); 8423 8424 // Handle conversion back to floating point if necessary. 8425 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8426 8427 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8428 } 8429 8430 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8431 SDLoc DL(Op); 8432 LoadSDNode *Load = cast<LoadSDNode>(Op); 8433 ISD::LoadExtType ExtType = Load->getExtensionType(); 8434 EVT MemVT = Load->getMemoryVT(); 8435 8436 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8437 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8438 return SDValue(); 8439 8440 // FIXME: Copied from PPC 8441 // First, load into 32 bits, then truncate to 1 bit. 8442 8443 SDValue Chain = Load->getChain(); 8444 SDValue BasePtr = Load->getBasePtr(); 8445 MachineMemOperand *MMO = Load->getMemOperand(); 8446 8447 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8448 8449 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8450 BasePtr, RealMemVT, MMO); 8451 8452 if (!MemVT.isVector()) { 8453 SDValue Ops[] = { 8454 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8455 NewLD.getValue(1) 8456 }; 8457 8458 return DAG.getMergeValues(Ops, DL); 8459 } 8460 8461 SmallVector<SDValue, 3> Elts; 8462 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8463 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8464 DAG.getConstant(I, DL, MVT::i32)); 8465 8466 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8467 } 8468 8469 SDValue Ops[] = { 8470 DAG.getBuildVector(MemVT, DL, Elts), 8471 NewLD.getValue(1) 8472 }; 8473 8474 return DAG.getMergeValues(Ops, DL); 8475 } 8476 8477 if (!MemVT.isVector()) 8478 return SDValue(); 8479 8480 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8481 "Custom lowering for non-i32 vectors hasn't been implemented."); 8482 8483 unsigned Alignment = Load->getAlignment(); 8484 unsigned AS = Load->getAddressSpace(); 8485 if (Subtarget->hasLDSMisalignedBug() && 8486 AS == AMDGPUAS::FLAT_ADDRESS && 8487 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8488 return SplitVectorLoad(Op, DAG); 8489 } 8490 8491 MachineFunction &MF = DAG.getMachineFunction(); 8492 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8493 // If there is a possibility that flat instruction access scratch memory 8494 // then we need to use the same legalization rules we use for private. 8495 if (AS == AMDGPUAS::FLAT_ADDRESS && 8496 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8497 AS = MFI->hasFlatScratchInit() ? 8498 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8499 8500 unsigned NumElements = MemVT.getVectorNumElements(); 8501 8502 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8503 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8504 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8505 if (MemVT.isPow2VectorType()) 8506 return SDValue(); 8507 return WidenOrSplitVectorLoad(Op, DAG); 8508 } 8509 // Non-uniform loads will be selected to MUBUF instructions, so they 8510 // have the same legalization requirements as global and private 8511 // loads. 8512 // 8513 } 8514 8515 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8516 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8517 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8518 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8519 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8520 Alignment >= 4 && NumElements < 32) { 8521 if (MemVT.isPow2VectorType()) 8522 return SDValue(); 8523 return WidenOrSplitVectorLoad(Op, DAG); 8524 } 8525 // Non-uniform loads will be selected to MUBUF instructions, so they 8526 // have the same legalization requirements as global and private 8527 // loads. 8528 // 8529 } 8530 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8531 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8532 AS == AMDGPUAS::GLOBAL_ADDRESS || 8533 AS == AMDGPUAS::FLAT_ADDRESS) { 8534 if (NumElements > 4) 8535 return SplitVectorLoad(Op, DAG); 8536 // v3 loads not supported on SI. 8537 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8538 return WidenOrSplitVectorLoad(Op, DAG); 8539 8540 // v3 and v4 loads are supported for private and global memory. 8541 return SDValue(); 8542 } 8543 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8544 // Depending on the setting of the private_element_size field in the 8545 // resource descriptor, we can only make private accesses up to a certain 8546 // size. 8547 switch (Subtarget->getMaxPrivateElementSize()) { 8548 case 4: { 8549 SDValue Ops[2]; 8550 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8551 return DAG.getMergeValues(Ops, DL); 8552 } 8553 case 8: 8554 if (NumElements > 2) 8555 return SplitVectorLoad(Op, DAG); 8556 return SDValue(); 8557 case 16: 8558 // Same as global/flat 8559 if (NumElements > 4) 8560 return SplitVectorLoad(Op, DAG); 8561 // v3 loads not supported on SI. 8562 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8563 return WidenOrSplitVectorLoad(Op, DAG); 8564 8565 return SDValue(); 8566 default: 8567 llvm_unreachable("unsupported private_element_size"); 8568 } 8569 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8570 bool Fast = false; 8571 auto Flags = Load->getMemOperand()->getFlags(); 8572 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8573 Load->getAlign(), Flags, &Fast) && 8574 Fast) 8575 return SDValue(); 8576 8577 if (MemVT.isVector()) 8578 return SplitVectorLoad(Op, DAG); 8579 } 8580 8581 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8582 MemVT, *Load->getMemOperand())) { 8583 SDValue Ops[2]; 8584 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8585 return DAG.getMergeValues(Ops, DL); 8586 } 8587 8588 return SDValue(); 8589 } 8590 8591 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8592 EVT VT = Op.getValueType(); 8593 if (VT.getSizeInBits() == 128) 8594 return splitTernaryVectorOp(Op, DAG); 8595 8596 assert(VT.getSizeInBits() == 64); 8597 8598 SDLoc DL(Op); 8599 SDValue Cond = Op.getOperand(0); 8600 8601 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8602 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8603 8604 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8605 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8606 8607 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8608 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8609 8610 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8611 8612 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8613 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8614 8615 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8616 8617 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8618 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8619 } 8620 8621 // Catch division cases where we can use shortcuts with rcp and rsq 8622 // instructions. 8623 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8624 SelectionDAG &DAG) const { 8625 SDLoc SL(Op); 8626 SDValue LHS = Op.getOperand(0); 8627 SDValue RHS = Op.getOperand(1); 8628 EVT VT = Op.getValueType(); 8629 const SDNodeFlags Flags = Op->getFlags(); 8630 8631 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8632 8633 // Without !fpmath accuracy information, we can't do more because we don't 8634 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8635 if (!AllowInaccurateRcp) 8636 return SDValue(); 8637 8638 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8639 if (CLHS->isExactlyValue(1.0)) { 8640 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8641 // the CI documentation has a worst case error of 1 ulp. 8642 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8643 // use it as long as we aren't trying to use denormals. 8644 // 8645 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8646 8647 // 1.0 / sqrt(x) -> rsq(x) 8648 8649 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8650 // error seems really high at 2^29 ULP. 8651 if (RHS.getOpcode() == ISD::FSQRT) 8652 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8653 8654 // 1.0 / x -> rcp(x) 8655 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8656 } 8657 8658 // Same as for 1.0, but expand the sign out of the constant. 8659 if (CLHS->isExactlyValue(-1.0)) { 8660 // -1.0 / x -> rcp (fneg x) 8661 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8662 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8663 } 8664 } 8665 8666 // Turn into multiply by the reciprocal. 8667 // x / y -> x * (1.0 / y) 8668 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8669 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8670 } 8671 8672 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8673 SelectionDAG &DAG) const { 8674 SDLoc SL(Op); 8675 SDValue X = Op.getOperand(0); 8676 SDValue Y = Op.getOperand(1); 8677 EVT VT = Op.getValueType(); 8678 const SDNodeFlags Flags = Op->getFlags(); 8679 8680 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8681 DAG.getTarget().Options.UnsafeFPMath; 8682 if (!AllowInaccurateDiv) 8683 return SDValue(); 8684 8685 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8686 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8687 8688 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8689 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8690 8691 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8692 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8693 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8694 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8695 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8696 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8697 } 8698 8699 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8700 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8701 SDNodeFlags Flags) { 8702 if (GlueChain->getNumValues() <= 1) { 8703 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8704 } 8705 8706 assert(GlueChain->getNumValues() == 3); 8707 8708 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8709 switch (Opcode) { 8710 default: llvm_unreachable("no chain equivalent for opcode"); 8711 case ISD::FMUL: 8712 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8713 break; 8714 } 8715 8716 return DAG.getNode(Opcode, SL, VTList, 8717 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8718 Flags); 8719 } 8720 8721 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8722 EVT VT, SDValue A, SDValue B, SDValue C, 8723 SDValue GlueChain, SDNodeFlags Flags) { 8724 if (GlueChain->getNumValues() <= 1) { 8725 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8726 } 8727 8728 assert(GlueChain->getNumValues() == 3); 8729 8730 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8731 switch (Opcode) { 8732 default: llvm_unreachable("no chain equivalent for opcode"); 8733 case ISD::FMA: 8734 Opcode = AMDGPUISD::FMA_W_CHAIN; 8735 break; 8736 } 8737 8738 return DAG.getNode(Opcode, SL, VTList, 8739 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8740 Flags); 8741 } 8742 8743 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8744 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8745 return FastLowered; 8746 8747 SDLoc SL(Op); 8748 SDValue Src0 = Op.getOperand(0); 8749 SDValue Src1 = Op.getOperand(1); 8750 8751 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8752 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8753 8754 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8755 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8756 8757 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8758 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8759 8760 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8761 } 8762 8763 // Faster 2.5 ULP division that does not support denormals. 8764 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8765 SDLoc SL(Op); 8766 SDValue LHS = Op.getOperand(1); 8767 SDValue RHS = Op.getOperand(2); 8768 8769 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8770 8771 const APFloat K0Val(BitsToFloat(0x6f800000)); 8772 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8773 8774 const APFloat K1Val(BitsToFloat(0x2f800000)); 8775 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8776 8777 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8778 8779 EVT SetCCVT = 8780 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8781 8782 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8783 8784 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8785 8786 // TODO: Should this propagate fast-math-flags? 8787 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8788 8789 // rcp does not support denormals. 8790 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8791 8792 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8793 8794 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8795 } 8796 8797 // Returns immediate value for setting the F32 denorm mode when using the 8798 // S_DENORM_MODE instruction. 8799 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8800 const SDLoc &SL, const GCNSubtarget *ST) { 8801 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8802 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8803 ? FP_DENORM_FLUSH_NONE 8804 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8805 8806 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8807 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8808 } 8809 8810 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8811 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8812 return FastLowered; 8813 8814 // The selection matcher assumes anything with a chain selecting to a 8815 // mayRaiseFPException machine instruction. Since we're introducing a chain 8816 // here, we need to explicitly report nofpexcept for the regular fdiv 8817 // lowering. 8818 SDNodeFlags Flags = Op->getFlags(); 8819 Flags.setNoFPExcept(true); 8820 8821 SDLoc SL(Op); 8822 SDValue LHS = Op.getOperand(0); 8823 SDValue RHS = Op.getOperand(1); 8824 8825 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8826 8827 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8828 8829 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8830 {RHS, RHS, LHS}, Flags); 8831 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8832 {LHS, RHS, LHS}, Flags); 8833 8834 // Denominator is scaled to not be denormal, so using rcp is ok. 8835 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8836 DenominatorScaled, Flags); 8837 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8838 DenominatorScaled, Flags); 8839 8840 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8841 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8842 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8843 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8844 8845 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8846 8847 if (!HasFP32Denormals) { 8848 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8849 // lowering. The chain dependence is insufficient, and we need glue. We do 8850 // not need the glue variants in a strictfp function. 8851 8852 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8853 8854 SDNode *EnableDenorm; 8855 if (Subtarget->hasDenormModeInst()) { 8856 const SDValue EnableDenormValue = 8857 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8858 8859 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8860 DAG.getEntryNode(), EnableDenormValue).getNode(); 8861 } else { 8862 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8863 SL, MVT::i32); 8864 EnableDenorm = 8865 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8866 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8867 } 8868 8869 SDValue Ops[3] = { 8870 NegDivScale0, 8871 SDValue(EnableDenorm, 0), 8872 SDValue(EnableDenorm, 1) 8873 }; 8874 8875 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8876 } 8877 8878 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8879 ApproxRcp, One, NegDivScale0, Flags); 8880 8881 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8882 ApproxRcp, Fma0, Flags); 8883 8884 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8885 Fma1, Fma1, Flags); 8886 8887 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8888 NumeratorScaled, Mul, Flags); 8889 8890 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8891 Fma2, Fma1, Mul, Fma2, Flags); 8892 8893 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8894 NumeratorScaled, Fma3, Flags); 8895 8896 if (!HasFP32Denormals) { 8897 SDNode *DisableDenorm; 8898 if (Subtarget->hasDenormModeInst()) { 8899 const SDValue DisableDenormValue = 8900 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8901 8902 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8903 Fma4.getValue(1), DisableDenormValue, 8904 Fma4.getValue(2)).getNode(); 8905 } else { 8906 const SDValue DisableDenormValue = 8907 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8908 8909 DisableDenorm = DAG.getMachineNode( 8910 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8911 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8912 } 8913 8914 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8915 SDValue(DisableDenorm, 0), DAG.getRoot()); 8916 DAG.setRoot(OutputChain); 8917 } 8918 8919 SDValue Scale = NumeratorScaled.getValue(1); 8920 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8921 {Fma4, Fma1, Fma3, Scale}, Flags); 8922 8923 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8924 } 8925 8926 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8927 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8928 return FastLowered; 8929 8930 SDLoc SL(Op); 8931 SDValue X = Op.getOperand(0); 8932 SDValue Y = Op.getOperand(1); 8933 8934 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8935 8936 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8937 8938 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8939 8940 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8941 8942 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8943 8944 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8945 8946 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8947 8948 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8949 8950 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8951 8952 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8953 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8954 8955 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8956 NegDivScale0, Mul, DivScale1); 8957 8958 SDValue Scale; 8959 8960 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8961 // Workaround a hardware bug on SI where the condition output from div_scale 8962 // is not usable. 8963 8964 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8965 8966 // Figure out if the scale to use for div_fmas. 8967 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8968 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8969 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8970 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8971 8972 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8973 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8974 8975 SDValue Scale0Hi 8976 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8977 SDValue Scale1Hi 8978 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8979 8980 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8981 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8982 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8983 } else { 8984 Scale = DivScale1.getValue(1); 8985 } 8986 8987 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8988 Fma4, Fma3, Mul, Scale); 8989 8990 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8991 } 8992 8993 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8994 EVT VT = Op.getValueType(); 8995 8996 if (VT == MVT::f32) 8997 return LowerFDIV32(Op, DAG); 8998 8999 if (VT == MVT::f64) 9000 return LowerFDIV64(Op, DAG); 9001 9002 if (VT == MVT::f16) 9003 return LowerFDIV16(Op, DAG); 9004 9005 llvm_unreachable("Unexpected type for fdiv"); 9006 } 9007 9008 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9009 SDLoc DL(Op); 9010 StoreSDNode *Store = cast<StoreSDNode>(Op); 9011 EVT VT = Store->getMemoryVT(); 9012 9013 if (VT == MVT::i1) { 9014 return DAG.getTruncStore(Store->getChain(), DL, 9015 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9016 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9017 } 9018 9019 assert(VT.isVector() && 9020 Store->getValue().getValueType().getScalarType() == MVT::i32); 9021 9022 unsigned AS = Store->getAddressSpace(); 9023 if (Subtarget->hasLDSMisalignedBug() && 9024 AS == AMDGPUAS::FLAT_ADDRESS && 9025 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9026 return SplitVectorStore(Op, DAG); 9027 } 9028 9029 MachineFunction &MF = DAG.getMachineFunction(); 9030 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9031 // If there is a possibility that flat instruction access scratch memory 9032 // then we need to use the same legalization rules we use for private. 9033 if (AS == AMDGPUAS::FLAT_ADDRESS && 9034 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9035 AS = MFI->hasFlatScratchInit() ? 9036 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9037 9038 unsigned NumElements = VT.getVectorNumElements(); 9039 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9040 AS == AMDGPUAS::FLAT_ADDRESS) { 9041 if (NumElements > 4) 9042 return SplitVectorStore(Op, DAG); 9043 // v3 stores not supported on SI. 9044 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9045 return SplitVectorStore(Op, DAG); 9046 9047 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9048 VT, *Store->getMemOperand())) 9049 return expandUnalignedStore(Store, DAG); 9050 9051 return SDValue(); 9052 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9053 switch (Subtarget->getMaxPrivateElementSize()) { 9054 case 4: 9055 return scalarizeVectorStore(Store, DAG); 9056 case 8: 9057 if (NumElements > 2) 9058 return SplitVectorStore(Op, DAG); 9059 return SDValue(); 9060 case 16: 9061 if (NumElements > 4 || 9062 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9063 return SplitVectorStore(Op, DAG); 9064 return SDValue(); 9065 default: 9066 llvm_unreachable("unsupported private_element_size"); 9067 } 9068 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9069 bool Fast = false; 9070 auto Flags = Store->getMemOperand()->getFlags(); 9071 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9072 Store->getAlign(), Flags, &Fast) && 9073 Fast) 9074 return SDValue(); 9075 9076 if (VT.isVector()) 9077 return SplitVectorStore(Op, DAG); 9078 9079 return expandUnalignedStore(Store, DAG); 9080 } 9081 9082 // Probably an invalid store. If so we'll end up emitting a selection error. 9083 return SDValue(); 9084 } 9085 9086 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9087 SDLoc DL(Op); 9088 EVT VT = Op.getValueType(); 9089 SDValue Arg = Op.getOperand(0); 9090 SDValue TrigVal; 9091 9092 // Propagate fast-math flags so that the multiply we introduce can be folded 9093 // if Arg is already the result of a multiply by constant. 9094 auto Flags = Op->getFlags(); 9095 9096 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9097 9098 if (Subtarget->hasTrigReducedRange()) { 9099 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9100 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9101 } else { 9102 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9103 } 9104 9105 switch (Op.getOpcode()) { 9106 case ISD::FCOS: 9107 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9108 case ISD::FSIN: 9109 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9110 default: 9111 llvm_unreachable("Wrong trig opcode"); 9112 } 9113 } 9114 9115 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9116 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9117 assert(AtomicNode->isCompareAndSwap()); 9118 unsigned AS = AtomicNode->getAddressSpace(); 9119 9120 // No custom lowering required for local address space 9121 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9122 return Op; 9123 9124 // Non-local address space requires custom lowering for atomic compare 9125 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9126 SDLoc DL(Op); 9127 SDValue ChainIn = Op.getOperand(0); 9128 SDValue Addr = Op.getOperand(1); 9129 SDValue Old = Op.getOperand(2); 9130 SDValue New = Op.getOperand(3); 9131 EVT VT = Op.getValueType(); 9132 MVT SimpleVT = VT.getSimpleVT(); 9133 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9134 9135 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9136 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9137 9138 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9139 Ops, VT, AtomicNode->getMemOperand()); 9140 } 9141 9142 //===----------------------------------------------------------------------===// 9143 // Custom DAG optimizations 9144 //===----------------------------------------------------------------------===// 9145 9146 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9147 DAGCombinerInfo &DCI) const { 9148 EVT VT = N->getValueType(0); 9149 EVT ScalarVT = VT.getScalarType(); 9150 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9151 return SDValue(); 9152 9153 SelectionDAG &DAG = DCI.DAG; 9154 SDLoc DL(N); 9155 9156 SDValue Src = N->getOperand(0); 9157 EVT SrcVT = Src.getValueType(); 9158 9159 // TODO: We could try to match extracting the higher bytes, which would be 9160 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9161 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9162 // about in practice. 9163 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9164 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9165 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9166 DCI.AddToWorklist(Cvt.getNode()); 9167 9168 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9169 if (ScalarVT != MVT::f32) { 9170 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9171 DAG.getTargetConstant(0, DL, MVT::i32)); 9172 } 9173 return Cvt; 9174 } 9175 } 9176 9177 return SDValue(); 9178 } 9179 9180 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9181 9182 // This is a variant of 9183 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9184 // 9185 // The normal DAG combiner will do this, but only if the add has one use since 9186 // that would increase the number of instructions. 9187 // 9188 // This prevents us from seeing a constant offset that can be folded into a 9189 // memory instruction's addressing mode. If we know the resulting add offset of 9190 // a pointer can be folded into an addressing offset, we can replace the pointer 9191 // operand with the add of new constant offset. This eliminates one of the uses, 9192 // and may allow the remaining use to also be simplified. 9193 // 9194 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9195 unsigned AddrSpace, 9196 EVT MemVT, 9197 DAGCombinerInfo &DCI) const { 9198 SDValue N0 = N->getOperand(0); 9199 SDValue N1 = N->getOperand(1); 9200 9201 // We only do this to handle cases where it's profitable when there are 9202 // multiple uses of the add, so defer to the standard combine. 9203 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9204 N0->hasOneUse()) 9205 return SDValue(); 9206 9207 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9208 if (!CN1) 9209 return SDValue(); 9210 9211 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9212 if (!CAdd) 9213 return SDValue(); 9214 9215 // If the resulting offset is too large, we can't fold it into the addressing 9216 // mode offset. 9217 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9218 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9219 9220 AddrMode AM; 9221 AM.HasBaseReg = true; 9222 AM.BaseOffs = Offset.getSExtValue(); 9223 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9224 return SDValue(); 9225 9226 SelectionDAG &DAG = DCI.DAG; 9227 SDLoc SL(N); 9228 EVT VT = N->getValueType(0); 9229 9230 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9231 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9232 9233 SDNodeFlags Flags; 9234 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9235 (N0.getOpcode() == ISD::OR || 9236 N0->getFlags().hasNoUnsignedWrap())); 9237 9238 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9239 } 9240 9241 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9242 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9243 /// specific intrinsic, but they all place the pointer operand first. 9244 static unsigned getBasePtrIndex(const MemSDNode *N) { 9245 switch (N->getOpcode()) { 9246 case ISD::STORE: 9247 case ISD::INTRINSIC_W_CHAIN: 9248 case ISD::INTRINSIC_VOID: 9249 return 2; 9250 default: 9251 return 1; 9252 } 9253 } 9254 9255 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9256 DAGCombinerInfo &DCI) const { 9257 SelectionDAG &DAG = DCI.DAG; 9258 SDLoc SL(N); 9259 9260 unsigned PtrIdx = getBasePtrIndex(N); 9261 SDValue Ptr = N->getOperand(PtrIdx); 9262 9263 // TODO: We could also do this for multiplies. 9264 if (Ptr.getOpcode() == ISD::SHL) { 9265 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9266 N->getMemoryVT(), DCI); 9267 if (NewPtr) { 9268 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9269 9270 NewOps[PtrIdx] = NewPtr; 9271 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9272 } 9273 } 9274 9275 return SDValue(); 9276 } 9277 9278 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9279 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9280 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9281 (Opc == ISD::XOR && Val == 0); 9282 } 9283 9284 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9285 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9286 // integer combine opportunities since most 64-bit operations are decomposed 9287 // this way. TODO: We won't want this for SALU especially if it is an inline 9288 // immediate. 9289 SDValue SITargetLowering::splitBinaryBitConstantOp( 9290 DAGCombinerInfo &DCI, 9291 const SDLoc &SL, 9292 unsigned Opc, SDValue LHS, 9293 const ConstantSDNode *CRHS) const { 9294 uint64_t Val = CRHS->getZExtValue(); 9295 uint32_t ValLo = Lo_32(Val); 9296 uint32_t ValHi = Hi_32(Val); 9297 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9298 9299 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9300 bitOpWithConstantIsReducible(Opc, ValHi)) || 9301 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9302 // If we need to materialize a 64-bit immediate, it will be split up later 9303 // anyway. Avoid creating the harder to understand 64-bit immediate 9304 // materialization. 9305 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9306 } 9307 9308 return SDValue(); 9309 } 9310 9311 // Returns true if argument is a boolean value which is not serialized into 9312 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9313 static bool isBoolSGPR(SDValue V) { 9314 if (V.getValueType() != MVT::i1) 9315 return false; 9316 switch (V.getOpcode()) { 9317 default: 9318 break; 9319 case ISD::SETCC: 9320 case AMDGPUISD::FP_CLASS: 9321 return true; 9322 case ISD::AND: 9323 case ISD::OR: 9324 case ISD::XOR: 9325 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9326 } 9327 return false; 9328 } 9329 9330 // If a constant has all zeroes or all ones within each byte return it. 9331 // Otherwise return 0. 9332 static uint32_t getConstantPermuteMask(uint32_t C) { 9333 // 0xff for any zero byte in the mask 9334 uint32_t ZeroByteMask = 0; 9335 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9336 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9337 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9338 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9339 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9340 if ((NonZeroByteMask & C) != NonZeroByteMask) 9341 return 0; // Partial bytes selected. 9342 return C; 9343 } 9344 9345 // Check if a node selects whole bytes from its operand 0 starting at a byte 9346 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9347 // or -1 if not succeeded. 9348 // Note byte select encoding: 9349 // value 0-3 selects corresponding source byte; 9350 // value 0xc selects zero; 9351 // value 0xff selects 0xff. 9352 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9353 assert(V.getValueSizeInBits() == 32); 9354 9355 if (V.getNumOperands() != 2) 9356 return ~0; 9357 9358 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9359 if (!N1) 9360 return ~0; 9361 9362 uint32_t C = N1->getZExtValue(); 9363 9364 switch (V.getOpcode()) { 9365 default: 9366 break; 9367 case ISD::AND: 9368 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9369 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9370 } 9371 break; 9372 9373 case ISD::OR: 9374 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9375 return (0x03020100 & ~ConstMask) | ConstMask; 9376 } 9377 break; 9378 9379 case ISD::SHL: 9380 if (C % 8) 9381 return ~0; 9382 9383 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9384 9385 case ISD::SRL: 9386 if (C % 8) 9387 return ~0; 9388 9389 return uint32_t(0x0c0c0c0c03020100ull >> C); 9390 } 9391 9392 return ~0; 9393 } 9394 9395 SDValue SITargetLowering::performAndCombine(SDNode *N, 9396 DAGCombinerInfo &DCI) const { 9397 if (DCI.isBeforeLegalize()) 9398 return SDValue(); 9399 9400 SelectionDAG &DAG = DCI.DAG; 9401 EVT VT = N->getValueType(0); 9402 SDValue LHS = N->getOperand(0); 9403 SDValue RHS = N->getOperand(1); 9404 9405 9406 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9407 if (VT == MVT::i64 && CRHS) { 9408 if (SDValue Split 9409 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9410 return Split; 9411 } 9412 9413 if (CRHS && VT == MVT::i32) { 9414 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9415 // nb = number of trailing zeroes in mask 9416 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9417 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9418 uint64_t Mask = CRHS->getZExtValue(); 9419 unsigned Bits = countPopulation(Mask); 9420 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9421 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9422 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9423 unsigned Shift = CShift->getZExtValue(); 9424 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9425 unsigned Offset = NB + Shift; 9426 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9427 SDLoc SL(N); 9428 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9429 LHS->getOperand(0), 9430 DAG.getConstant(Offset, SL, MVT::i32), 9431 DAG.getConstant(Bits, SL, MVT::i32)); 9432 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9433 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9434 DAG.getValueType(NarrowVT)); 9435 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9436 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9437 return Shl; 9438 } 9439 } 9440 } 9441 9442 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9443 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9444 isa<ConstantSDNode>(LHS.getOperand(2))) { 9445 uint32_t Sel = getConstantPermuteMask(Mask); 9446 if (!Sel) 9447 return SDValue(); 9448 9449 // Select 0xc for all zero bytes 9450 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9451 SDLoc DL(N); 9452 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9453 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9454 } 9455 } 9456 9457 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9458 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9459 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9460 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9461 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9462 9463 SDValue X = LHS.getOperand(0); 9464 SDValue Y = RHS.getOperand(0); 9465 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9466 return SDValue(); 9467 9468 if (LCC == ISD::SETO) { 9469 if (X != LHS.getOperand(1)) 9470 return SDValue(); 9471 9472 if (RCC == ISD::SETUNE) { 9473 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9474 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9475 return SDValue(); 9476 9477 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9478 SIInstrFlags::N_SUBNORMAL | 9479 SIInstrFlags::N_ZERO | 9480 SIInstrFlags::P_ZERO | 9481 SIInstrFlags::P_SUBNORMAL | 9482 SIInstrFlags::P_NORMAL; 9483 9484 static_assert(((~(SIInstrFlags::S_NAN | 9485 SIInstrFlags::Q_NAN | 9486 SIInstrFlags::N_INFINITY | 9487 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9488 "mask not equal"); 9489 9490 SDLoc DL(N); 9491 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9492 X, DAG.getConstant(Mask, DL, MVT::i32)); 9493 } 9494 } 9495 } 9496 9497 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9498 std::swap(LHS, RHS); 9499 9500 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9501 RHS.hasOneUse()) { 9502 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9503 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9504 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9505 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9506 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9507 (RHS.getOperand(0) == LHS.getOperand(0) && 9508 LHS.getOperand(0) == LHS.getOperand(1))) { 9509 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9510 unsigned NewMask = LCC == ISD::SETO ? 9511 Mask->getZExtValue() & ~OrdMask : 9512 Mask->getZExtValue() & OrdMask; 9513 9514 SDLoc DL(N); 9515 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9516 DAG.getConstant(NewMask, DL, MVT::i32)); 9517 } 9518 } 9519 9520 if (VT == MVT::i32 && 9521 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9522 // and x, (sext cc from i1) => select cc, x, 0 9523 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9524 std::swap(LHS, RHS); 9525 if (isBoolSGPR(RHS.getOperand(0))) 9526 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9527 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9528 } 9529 9530 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9531 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9532 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9533 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9534 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9535 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9536 if (LHSMask != ~0u && RHSMask != ~0u) { 9537 // Canonicalize the expression in an attempt to have fewer unique masks 9538 // and therefore fewer registers used to hold the masks. 9539 if (LHSMask > RHSMask) { 9540 std::swap(LHSMask, RHSMask); 9541 std::swap(LHS, RHS); 9542 } 9543 9544 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9545 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9546 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9547 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9548 9549 // Check of we need to combine values from two sources within a byte. 9550 if (!(LHSUsedLanes & RHSUsedLanes) && 9551 // If we select high and lower word keep it for SDWA. 9552 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9553 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9554 // Each byte in each mask is either selector mask 0-3, or has higher 9555 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9556 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9557 // mask which is not 0xff wins. By anding both masks we have a correct 9558 // result except that 0x0c shall be corrected to give 0x0c only. 9559 uint32_t Mask = LHSMask & RHSMask; 9560 for (unsigned I = 0; I < 32; I += 8) { 9561 uint32_t ByteSel = 0xff << I; 9562 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9563 Mask &= (0x0c << I) & 0xffffffff; 9564 } 9565 9566 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9567 // or 0x0c. 9568 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9569 SDLoc DL(N); 9570 9571 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9572 LHS.getOperand(0), RHS.getOperand(0), 9573 DAG.getConstant(Sel, DL, MVT::i32)); 9574 } 9575 } 9576 } 9577 9578 return SDValue(); 9579 } 9580 9581 SDValue SITargetLowering::performOrCombine(SDNode *N, 9582 DAGCombinerInfo &DCI) const { 9583 SelectionDAG &DAG = DCI.DAG; 9584 SDValue LHS = N->getOperand(0); 9585 SDValue RHS = N->getOperand(1); 9586 9587 EVT VT = N->getValueType(0); 9588 if (VT == MVT::i1) { 9589 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9590 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9591 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9592 SDValue Src = LHS.getOperand(0); 9593 if (Src != RHS.getOperand(0)) 9594 return SDValue(); 9595 9596 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9597 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9598 if (!CLHS || !CRHS) 9599 return SDValue(); 9600 9601 // Only 10 bits are used. 9602 static const uint32_t MaxMask = 0x3ff; 9603 9604 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9605 SDLoc DL(N); 9606 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9607 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9608 } 9609 9610 return SDValue(); 9611 } 9612 9613 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9614 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9615 LHS.getOpcode() == AMDGPUISD::PERM && 9616 isa<ConstantSDNode>(LHS.getOperand(2))) { 9617 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9618 if (!Sel) 9619 return SDValue(); 9620 9621 Sel |= LHS.getConstantOperandVal(2); 9622 SDLoc DL(N); 9623 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9624 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9625 } 9626 9627 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9628 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9629 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9630 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9631 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9632 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9633 if (LHSMask != ~0u && RHSMask != ~0u) { 9634 // Canonicalize the expression in an attempt to have fewer unique masks 9635 // and therefore fewer registers used to hold the masks. 9636 if (LHSMask > RHSMask) { 9637 std::swap(LHSMask, RHSMask); 9638 std::swap(LHS, RHS); 9639 } 9640 9641 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9642 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9643 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9644 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9645 9646 // Check of we need to combine values from two sources within a byte. 9647 if (!(LHSUsedLanes & RHSUsedLanes) && 9648 // If we select high and lower word keep it for SDWA. 9649 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9650 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9651 // Kill zero bytes selected by other mask. Zero value is 0xc. 9652 LHSMask &= ~RHSUsedLanes; 9653 RHSMask &= ~LHSUsedLanes; 9654 // Add 4 to each active LHS lane 9655 LHSMask |= LHSUsedLanes & 0x04040404; 9656 // Combine masks 9657 uint32_t Sel = LHSMask | RHSMask; 9658 SDLoc DL(N); 9659 9660 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9661 LHS.getOperand(0), RHS.getOperand(0), 9662 DAG.getConstant(Sel, DL, MVT::i32)); 9663 } 9664 } 9665 } 9666 9667 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9668 return SDValue(); 9669 9670 // TODO: This could be a generic combine with a predicate for extracting the 9671 // high half of an integer being free. 9672 9673 // (or i64:x, (zero_extend i32:y)) -> 9674 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9675 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9676 RHS.getOpcode() != ISD::ZERO_EXTEND) 9677 std::swap(LHS, RHS); 9678 9679 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9680 SDValue ExtSrc = RHS.getOperand(0); 9681 EVT SrcVT = ExtSrc.getValueType(); 9682 if (SrcVT == MVT::i32) { 9683 SDLoc SL(N); 9684 SDValue LowLHS, HiBits; 9685 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9686 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9687 9688 DCI.AddToWorklist(LowOr.getNode()); 9689 DCI.AddToWorklist(HiBits.getNode()); 9690 9691 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9692 LowOr, HiBits); 9693 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9694 } 9695 } 9696 9697 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9698 if (CRHS) { 9699 if (SDValue Split 9700 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9701 N->getOperand(0), CRHS)) 9702 return Split; 9703 } 9704 9705 return SDValue(); 9706 } 9707 9708 SDValue SITargetLowering::performXorCombine(SDNode *N, 9709 DAGCombinerInfo &DCI) const { 9710 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9711 return RV; 9712 9713 EVT VT = N->getValueType(0); 9714 if (VT != MVT::i64) 9715 return SDValue(); 9716 9717 SDValue LHS = N->getOperand(0); 9718 SDValue RHS = N->getOperand(1); 9719 9720 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9721 if (CRHS) { 9722 if (SDValue Split 9723 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9724 return Split; 9725 } 9726 9727 return SDValue(); 9728 } 9729 9730 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9731 DAGCombinerInfo &DCI) const { 9732 if (!Subtarget->has16BitInsts() || 9733 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9734 return SDValue(); 9735 9736 EVT VT = N->getValueType(0); 9737 if (VT != MVT::i32) 9738 return SDValue(); 9739 9740 SDValue Src = N->getOperand(0); 9741 if (Src.getValueType() != MVT::i16) 9742 return SDValue(); 9743 9744 return SDValue(); 9745 } 9746 9747 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9748 DAGCombinerInfo &DCI) 9749 const { 9750 SDValue Src = N->getOperand(0); 9751 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9752 9753 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9754 VTSign->getVT() == MVT::i8) || 9755 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9756 VTSign->getVT() == MVT::i16)) && 9757 Src.hasOneUse()) { 9758 auto *M = cast<MemSDNode>(Src); 9759 SDValue Ops[] = { 9760 Src.getOperand(0), // Chain 9761 Src.getOperand(1), // rsrc 9762 Src.getOperand(2), // vindex 9763 Src.getOperand(3), // voffset 9764 Src.getOperand(4), // soffset 9765 Src.getOperand(5), // offset 9766 Src.getOperand(6), 9767 Src.getOperand(7) 9768 }; 9769 // replace with BUFFER_LOAD_BYTE/SHORT 9770 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9771 Src.getOperand(0).getValueType()); 9772 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9773 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9774 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9775 ResList, 9776 Ops, M->getMemoryVT(), 9777 M->getMemOperand()); 9778 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9779 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9780 } 9781 return SDValue(); 9782 } 9783 9784 SDValue SITargetLowering::performClassCombine(SDNode *N, 9785 DAGCombinerInfo &DCI) const { 9786 SelectionDAG &DAG = DCI.DAG; 9787 SDValue Mask = N->getOperand(1); 9788 9789 // fp_class x, 0 -> false 9790 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9791 if (CMask->isZero()) 9792 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9793 } 9794 9795 if (N->getOperand(0).isUndef()) 9796 return DAG.getUNDEF(MVT::i1); 9797 9798 return SDValue(); 9799 } 9800 9801 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9802 DAGCombinerInfo &DCI) const { 9803 EVT VT = N->getValueType(0); 9804 SDValue N0 = N->getOperand(0); 9805 9806 if (N0.isUndef()) 9807 return N0; 9808 9809 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9810 N0.getOpcode() == ISD::SINT_TO_FP)) { 9811 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9812 N->getFlags()); 9813 } 9814 9815 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9816 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9817 N0.getOperand(0), N->getFlags()); 9818 } 9819 9820 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9821 } 9822 9823 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9824 unsigned MaxDepth) const { 9825 unsigned Opcode = Op.getOpcode(); 9826 if (Opcode == ISD::FCANONICALIZE) 9827 return true; 9828 9829 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9830 auto F = CFP->getValueAPF(); 9831 if (F.isNaN() && F.isSignaling()) 9832 return false; 9833 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9834 } 9835 9836 // If source is a result of another standard FP operation it is already in 9837 // canonical form. 9838 if (MaxDepth == 0) 9839 return false; 9840 9841 switch (Opcode) { 9842 // These will flush denorms if required. 9843 case ISD::FADD: 9844 case ISD::FSUB: 9845 case ISD::FMUL: 9846 case ISD::FCEIL: 9847 case ISD::FFLOOR: 9848 case ISD::FMA: 9849 case ISD::FMAD: 9850 case ISD::FSQRT: 9851 case ISD::FDIV: 9852 case ISD::FREM: 9853 case ISD::FP_ROUND: 9854 case ISD::FP_EXTEND: 9855 case AMDGPUISD::FMUL_LEGACY: 9856 case AMDGPUISD::FMAD_FTZ: 9857 case AMDGPUISD::RCP: 9858 case AMDGPUISD::RSQ: 9859 case AMDGPUISD::RSQ_CLAMP: 9860 case AMDGPUISD::RCP_LEGACY: 9861 case AMDGPUISD::RCP_IFLAG: 9862 case AMDGPUISD::DIV_SCALE: 9863 case AMDGPUISD::DIV_FMAS: 9864 case AMDGPUISD::DIV_FIXUP: 9865 case AMDGPUISD::FRACT: 9866 case AMDGPUISD::LDEXP: 9867 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9868 case AMDGPUISD::CVT_F32_UBYTE0: 9869 case AMDGPUISD::CVT_F32_UBYTE1: 9870 case AMDGPUISD::CVT_F32_UBYTE2: 9871 case AMDGPUISD::CVT_F32_UBYTE3: 9872 return true; 9873 9874 // It can/will be lowered or combined as a bit operation. 9875 // Need to check their input recursively to handle. 9876 case ISD::FNEG: 9877 case ISD::FABS: 9878 case ISD::FCOPYSIGN: 9879 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9880 9881 case ISD::FSIN: 9882 case ISD::FCOS: 9883 case ISD::FSINCOS: 9884 return Op.getValueType().getScalarType() != MVT::f16; 9885 9886 case ISD::FMINNUM: 9887 case ISD::FMAXNUM: 9888 case ISD::FMINNUM_IEEE: 9889 case ISD::FMAXNUM_IEEE: 9890 case AMDGPUISD::CLAMP: 9891 case AMDGPUISD::FMED3: 9892 case AMDGPUISD::FMAX3: 9893 case AMDGPUISD::FMIN3: { 9894 // FIXME: Shouldn't treat the generic operations different based these. 9895 // However, we aren't really required to flush the result from 9896 // minnum/maxnum.. 9897 9898 // snans will be quieted, so we only need to worry about denormals. 9899 if (Subtarget->supportsMinMaxDenormModes() || 9900 denormalsEnabledForType(DAG, Op.getValueType())) 9901 return true; 9902 9903 // Flushing may be required. 9904 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9905 // targets need to check their input recursively. 9906 9907 // FIXME: Does this apply with clamp? It's implemented with max. 9908 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9909 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9910 return false; 9911 } 9912 9913 return true; 9914 } 9915 case ISD::SELECT: { 9916 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9917 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9918 } 9919 case ISD::BUILD_VECTOR: { 9920 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9921 SDValue SrcOp = Op.getOperand(i); 9922 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9923 return false; 9924 } 9925 9926 return true; 9927 } 9928 case ISD::EXTRACT_VECTOR_ELT: 9929 case ISD::EXTRACT_SUBVECTOR: { 9930 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9931 } 9932 case ISD::INSERT_VECTOR_ELT: { 9933 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9934 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9935 } 9936 case ISD::UNDEF: 9937 // Could be anything. 9938 return false; 9939 9940 case ISD::BITCAST: 9941 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9942 case ISD::TRUNCATE: { 9943 // Hack round the mess we make when legalizing extract_vector_elt 9944 if (Op.getValueType() == MVT::i16) { 9945 SDValue TruncSrc = Op.getOperand(0); 9946 if (TruncSrc.getValueType() == MVT::i32 && 9947 TruncSrc.getOpcode() == ISD::BITCAST && 9948 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9949 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9950 } 9951 } 9952 return false; 9953 } 9954 case ISD::INTRINSIC_WO_CHAIN: { 9955 unsigned IntrinsicID 9956 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9957 // TODO: Handle more intrinsics 9958 switch (IntrinsicID) { 9959 case Intrinsic::amdgcn_cvt_pkrtz: 9960 case Intrinsic::amdgcn_cubeid: 9961 case Intrinsic::amdgcn_frexp_mant: 9962 case Intrinsic::amdgcn_fdot2: 9963 case Intrinsic::amdgcn_rcp: 9964 case Intrinsic::amdgcn_rsq: 9965 case Intrinsic::amdgcn_rsq_clamp: 9966 case Intrinsic::amdgcn_rcp_legacy: 9967 case Intrinsic::amdgcn_rsq_legacy: 9968 case Intrinsic::amdgcn_trig_preop: 9969 return true; 9970 default: 9971 break; 9972 } 9973 9974 LLVM_FALLTHROUGH; 9975 } 9976 default: 9977 return denormalsEnabledForType(DAG, Op.getValueType()) && 9978 DAG.isKnownNeverSNaN(Op); 9979 } 9980 9981 llvm_unreachable("invalid operation"); 9982 } 9983 9984 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9985 unsigned MaxDepth) const { 9986 MachineRegisterInfo &MRI = MF.getRegInfo(); 9987 MachineInstr *MI = MRI.getVRegDef(Reg); 9988 unsigned Opcode = MI->getOpcode(); 9989 9990 if (Opcode == AMDGPU::G_FCANONICALIZE) 9991 return true; 9992 9993 Optional<FPValueAndVReg> FCR; 9994 // Constant splat (can be padded with undef) or scalar constant. 9995 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9996 if (FCR->Value.isSignaling()) 9997 return false; 9998 return !FCR->Value.isDenormal() || 9999 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10000 } 10001 10002 if (MaxDepth == 0) 10003 return false; 10004 10005 switch (Opcode) { 10006 case AMDGPU::G_FMINNUM_IEEE: 10007 case AMDGPU::G_FMAXNUM_IEEE: { 10008 if (Subtarget->supportsMinMaxDenormModes() || 10009 denormalsEnabledForType(MRI.getType(Reg), MF)) 10010 return true; 10011 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10012 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10013 return false; 10014 return true; 10015 } 10016 default: 10017 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10018 isKnownNeverSNaN(Reg, MRI); 10019 } 10020 10021 llvm_unreachable("invalid operation"); 10022 } 10023 10024 // Constant fold canonicalize. 10025 SDValue SITargetLowering::getCanonicalConstantFP( 10026 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10027 // Flush denormals to 0 if not enabled. 10028 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10029 return DAG.getConstantFP(0.0, SL, VT); 10030 10031 if (C.isNaN()) { 10032 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10033 if (C.isSignaling()) { 10034 // Quiet a signaling NaN. 10035 // FIXME: Is this supposed to preserve payload bits? 10036 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10037 } 10038 10039 // Make sure it is the canonical NaN bitpattern. 10040 // 10041 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10042 // immediate? 10043 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10044 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10045 } 10046 10047 // Already canonical. 10048 return DAG.getConstantFP(C, SL, VT); 10049 } 10050 10051 static bool vectorEltWillFoldAway(SDValue Op) { 10052 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10053 } 10054 10055 SDValue SITargetLowering::performFCanonicalizeCombine( 10056 SDNode *N, 10057 DAGCombinerInfo &DCI) const { 10058 SelectionDAG &DAG = DCI.DAG; 10059 SDValue N0 = N->getOperand(0); 10060 EVT VT = N->getValueType(0); 10061 10062 // fcanonicalize undef -> qnan 10063 if (N0.isUndef()) { 10064 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10065 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10066 } 10067 10068 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10069 EVT VT = N->getValueType(0); 10070 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10071 } 10072 10073 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10074 // (fcanonicalize k) 10075 // 10076 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10077 10078 // TODO: This could be better with wider vectors that will be split to v2f16, 10079 // and to consider uses since there aren't that many packed operations. 10080 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10081 isTypeLegal(MVT::v2f16)) { 10082 SDLoc SL(N); 10083 SDValue NewElts[2]; 10084 SDValue Lo = N0.getOperand(0); 10085 SDValue Hi = N0.getOperand(1); 10086 EVT EltVT = Lo.getValueType(); 10087 10088 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10089 for (unsigned I = 0; I != 2; ++I) { 10090 SDValue Op = N0.getOperand(I); 10091 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10092 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10093 CFP->getValueAPF()); 10094 } else if (Op.isUndef()) { 10095 // Handled below based on what the other operand is. 10096 NewElts[I] = Op; 10097 } else { 10098 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10099 } 10100 } 10101 10102 // If one half is undef, and one is constant, prefer a splat vector rather 10103 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10104 // cheaper to use and may be free with a packed operation. 10105 if (NewElts[0].isUndef()) { 10106 if (isa<ConstantFPSDNode>(NewElts[1])) 10107 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10108 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10109 } 10110 10111 if (NewElts[1].isUndef()) { 10112 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10113 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10114 } 10115 10116 return DAG.getBuildVector(VT, SL, NewElts); 10117 } 10118 } 10119 10120 unsigned SrcOpc = N0.getOpcode(); 10121 10122 // If it's free to do so, push canonicalizes further up the source, which may 10123 // find a canonical source. 10124 // 10125 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10126 // sNaNs. 10127 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10128 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10129 if (CRHS && N0.hasOneUse()) { 10130 SDLoc SL(N); 10131 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10132 N0.getOperand(0)); 10133 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10134 DCI.AddToWorklist(Canon0.getNode()); 10135 10136 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10137 } 10138 } 10139 10140 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10141 } 10142 10143 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10144 switch (Opc) { 10145 case ISD::FMAXNUM: 10146 case ISD::FMAXNUM_IEEE: 10147 return AMDGPUISD::FMAX3; 10148 case ISD::SMAX: 10149 return AMDGPUISD::SMAX3; 10150 case ISD::UMAX: 10151 return AMDGPUISD::UMAX3; 10152 case ISD::FMINNUM: 10153 case ISD::FMINNUM_IEEE: 10154 return AMDGPUISD::FMIN3; 10155 case ISD::SMIN: 10156 return AMDGPUISD::SMIN3; 10157 case ISD::UMIN: 10158 return AMDGPUISD::UMIN3; 10159 default: 10160 llvm_unreachable("Not a min/max opcode"); 10161 } 10162 } 10163 10164 SDValue SITargetLowering::performIntMed3ImmCombine( 10165 SelectionDAG &DAG, const SDLoc &SL, 10166 SDValue Op0, SDValue Op1, bool Signed) const { 10167 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10168 if (!K1) 10169 return SDValue(); 10170 10171 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10172 if (!K0) 10173 return SDValue(); 10174 10175 if (Signed) { 10176 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10177 return SDValue(); 10178 } else { 10179 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10180 return SDValue(); 10181 } 10182 10183 EVT VT = K0->getValueType(0); 10184 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10185 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10186 return DAG.getNode(Med3Opc, SL, VT, 10187 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10188 } 10189 10190 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10191 if (VT == MVT::i16) { 10192 MVT NVT = MVT::i32; 10193 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10194 10195 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10196 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10197 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10198 10199 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10200 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10201 } 10202 10203 return SDValue(); 10204 } 10205 10206 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10207 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10208 return C; 10209 10210 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10211 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10212 return C; 10213 } 10214 10215 return nullptr; 10216 } 10217 10218 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10219 const SDLoc &SL, 10220 SDValue Op0, 10221 SDValue Op1) const { 10222 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10223 if (!K1) 10224 return SDValue(); 10225 10226 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10227 if (!K0) 10228 return SDValue(); 10229 10230 // Ordered >= (although NaN inputs should have folded away by now). 10231 if (K0->getValueAPF() > K1->getValueAPF()) 10232 return SDValue(); 10233 10234 const MachineFunction &MF = DAG.getMachineFunction(); 10235 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10236 10237 // TODO: Check IEEE bit enabled? 10238 EVT VT = Op0.getValueType(); 10239 if (Info->getMode().DX10Clamp) { 10240 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10241 // hardware fmed3 behavior converting to a min. 10242 // FIXME: Should this be allowing -0.0? 10243 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10244 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10245 } 10246 10247 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10248 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10249 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10250 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10251 // then give the other result, which is different from med3 with a NaN 10252 // input. 10253 SDValue Var = Op0.getOperand(0); 10254 if (!DAG.isKnownNeverSNaN(Var)) 10255 return SDValue(); 10256 10257 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10258 10259 if ((!K0->hasOneUse() || 10260 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10261 (!K1->hasOneUse() || 10262 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10263 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10264 Var, SDValue(K0, 0), SDValue(K1, 0)); 10265 } 10266 } 10267 10268 return SDValue(); 10269 } 10270 10271 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10272 DAGCombinerInfo &DCI) const { 10273 SelectionDAG &DAG = DCI.DAG; 10274 10275 EVT VT = N->getValueType(0); 10276 unsigned Opc = N->getOpcode(); 10277 SDValue Op0 = N->getOperand(0); 10278 SDValue Op1 = N->getOperand(1); 10279 10280 // Only do this if the inner op has one use since this will just increases 10281 // register pressure for no benefit. 10282 10283 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10284 !VT.isVector() && 10285 (VT == MVT::i32 || VT == MVT::f32 || 10286 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10287 // max(max(a, b), c) -> max3(a, b, c) 10288 // min(min(a, b), c) -> min3(a, b, c) 10289 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10290 SDLoc DL(N); 10291 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10292 DL, 10293 N->getValueType(0), 10294 Op0.getOperand(0), 10295 Op0.getOperand(1), 10296 Op1); 10297 } 10298 10299 // Try commuted. 10300 // max(a, max(b, c)) -> max3(a, b, c) 10301 // min(a, min(b, c)) -> min3(a, b, c) 10302 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10303 SDLoc DL(N); 10304 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10305 DL, 10306 N->getValueType(0), 10307 Op0, 10308 Op1.getOperand(0), 10309 Op1.getOperand(1)); 10310 } 10311 } 10312 10313 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10314 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10315 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10316 return Med3; 10317 } 10318 10319 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10320 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10321 return Med3; 10322 } 10323 10324 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10325 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10326 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10327 (Opc == AMDGPUISD::FMIN_LEGACY && 10328 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10329 (VT == MVT::f32 || VT == MVT::f64 || 10330 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10331 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10332 Op0.hasOneUse()) { 10333 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10334 return Res; 10335 } 10336 10337 return SDValue(); 10338 } 10339 10340 static bool isClampZeroToOne(SDValue A, SDValue B) { 10341 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10342 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10343 // FIXME: Should this be allowing -0.0? 10344 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10345 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10346 } 10347 } 10348 10349 return false; 10350 } 10351 10352 // FIXME: Should only worry about snans for version with chain. 10353 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10354 DAGCombinerInfo &DCI) const { 10355 EVT VT = N->getValueType(0); 10356 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10357 // NaNs. With a NaN input, the order of the operands may change the result. 10358 10359 SelectionDAG &DAG = DCI.DAG; 10360 SDLoc SL(N); 10361 10362 SDValue Src0 = N->getOperand(0); 10363 SDValue Src1 = N->getOperand(1); 10364 SDValue Src2 = N->getOperand(2); 10365 10366 if (isClampZeroToOne(Src0, Src1)) { 10367 // const_a, const_b, x -> clamp is safe in all cases including signaling 10368 // nans. 10369 // FIXME: Should this be allowing -0.0? 10370 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10371 } 10372 10373 const MachineFunction &MF = DAG.getMachineFunction(); 10374 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10375 10376 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10377 // handling no dx10-clamp? 10378 if (Info->getMode().DX10Clamp) { 10379 // If NaNs is clamped to 0, we are free to reorder the inputs. 10380 10381 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10382 std::swap(Src0, Src1); 10383 10384 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10385 std::swap(Src1, Src2); 10386 10387 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10388 std::swap(Src0, Src1); 10389 10390 if (isClampZeroToOne(Src1, Src2)) 10391 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10392 } 10393 10394 return SDValue(); 10395 } 10396 10397 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10398 DAGCombinerInfo &DCI) const { 10399 SDValue Src0 = N->getOperand(0); 10400 SDValue Src1 = N->getOperand(1); 10401 if (Src0.isUndef() && Src1.isUndef()) 10402 return DCI.DAG.getUNDEF(N->getValueType(0)); 10403 return SDValue(); 10404 } 10405 10406 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10407 // expanded into a set of cmp/select instructions. 10408 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10409 unsigned NumElem, 10410 bool IsDivergentIdx) { 10411 if (UseDivergentRegisterIndexing) 10412 return false; 10413 10414 unsigned VecSize = EltSize * NumElem; 10415 10416 // Sub-dword vectors of size 2 dword or less have better implementation. 10417 if (VecSize <= 64 && EltSize < 32) 10418 return false; 10419 10420 // Always expand the rest of sub-dword instructions, otherwise it will be 10421 // lowered via memory. 10422 if (EltSize < 32) 10423 return true; 10424 10425 // Always do this if var-idx is divergent, otherwise it will become a loop. 10426 if (IsDivergentIdx) 10427 return true; 10428 10429 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10430 unsigned NumInsts = NumElem /* Number of compares */ + 10431 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10432 return NumInsts <= 16; 10433 } 10434 10435 static bool shouldExpandVectorDynExt(SDNode *N) { 10436 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10437 if (isa<ConstantSDNode>(Idx)) 10438 return false; 10439 10440 SDValue Vec = N->getOperand(0); 10441 EVT VecVT = Vec.getValueType(); 10442 EVT EltVT = VecVT.getVectorElementType(); 10443 unsigned EltSize = EltVT.getSizeInBits(); 10444 unsigned NumElem = VecVT.getVectorNumElements(); 10445 10446 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10447 Idx->isDivergent()); 10448 } 10449 10450 SDValue SITargetLowering::performExtractVectorEltCombine( 10451 SDNode *N, DAGCombinerInfo &DCI) const { 10452 SDValue Vec = N->getOperand(0); 10453 SelectionDAG &DAG = DCI.DAG; 10454 10455 EVT VecVT = Vec.getValueType(); 10456 EVT EltVT = VecVT.getVectorElementType(); 10457 10458 if ((Vec.getOpcode() == ISD::FNEG || 10459 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10460 SDLoc SL(N); 10461 EVT EltVT = N->getValueType(0); 10462 SDValue Idx = N->getOperand(1); 10463 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10464 Vec.getOperand(0), Idx); 10465 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10466 } 10467 10468 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10469 // => 10470 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10471 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10472 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10473 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10474 SDLoc SL(N); 10475 EVT EltVT = N->getValueType(0); 10476 SDValue Idx = N->getOperand(1); 10477 unsigned Opc = Vec.getOpcode(); 10478 10479 switch(Opc) { 10480 default: 10481 break; 10482 // TODO: Support other binary operations. 10483 case ISD::FADD: 10484 case ISD::FSUB: 10485 case ISD::FMUL: 10486 case ISD::ADD: 10487 case ISD::UMIN: 10488 case ISD::UMAX: 10489 case ISD::SMIN: 10490 case ISD::SMAX: 10491 case ISD::FMAXNUM: 10492 case ISD::FMINNUM: 10493 case ISD::FMAXNUM_IEEE: 10494 case ISD::FMINNUM_IEEE: { 10495 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10496 Vec.getOperand(0), Idx); 10497 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10498 Vec.getOperand(1), Idx); 10499 10500 DCI.AddToWorklist(Elt0.getNode()); 10501 DCI.AddToWorklist(Elt1.getNode()); 10502 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10503 } 10504 } 10505 } 10506 10507 unsigned VecSize = VecVT.getSizeInBits(); 10508 unsigned EltSize = EltVT.getSizeInBits(); 10509 10510 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10511 if (::shouldExpandVectorDynExt(N)) { 10512 SDLoc SL(N); 10513 SDValue Idx = N->getOperand(1); 10514 SDValue V; 10515 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10516 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10517 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10518 if (I == 0) 10519 V = Elt; 10520 else 10521 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10522 } 10523 return V; 10524 } 10525 10526 if (!DCI.isBeforeLegalize()) 10527 return SDValue(); 10528 10529 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10530 // elements. This exposes more load reduction opportunities by replacing 10531 // multiple small extract_vector_elements with a single 32-bit extract. 10532 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10533 if (isa<MemSDNode>(Vec) && 10534 EltSize <= 16 && 10535 EltVT.isByteSized() && 10536 VecSize > 32 && 10537 VecSize % 32 == 0 && 10538 Idx) { 10539 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10540 10541 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10542 unsigned EltIdx = BitIndex / 32; 10543 unsigned LeftoverBitIdx = BitIndex % 32; 10544 SDLoc SL(N); 10545 10546 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10547 DCI.AddToWorklist(Cast.getNode()); 10548 10549 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10550 DAG.getConstant(EltIdx, SL, MVT::i32)); 10551 DCI.AddToWorklist(Elt.getNode()); 10552 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10553 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10554 DCI.AddToWorklist(Srl.getNode()); 10555 10556 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10557 DCI.AddToWorklist(Trunc.getNode()); 10558 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10559 } 10560 10561 return SDValue(); 10562 } 10563 10564 SDValue 10565 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10566 DAGCombinerInfo &DCI) const { 10567 SDValue Vec = N->getOperand(0); 10568 SDValue Idx = N->getOperand(2); 10569 EVT VecVT = Vec.getValueType(); 10570 EVT EltVT = VecVT.getVectorElementType(); 10571 10572 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10573 // => BUILD_VECTOR n x select (e, const-idx) 10574 if (!::shouldExpandVectorDynExt(N)) 10575 return SDValue(); 10576 10577 SelectionDAG &DAG = DCI.DAG; 10578 SDLoc SL(N); 10579 SDValue Ins = N->getOperand(1); 10580 EVT IdxVT = Idx.getValueType(); 10581 10582 SmallVector<SDValue, 16> Ops; 10583 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10584 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10585 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10586 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10587 Ops.push_back(V); 10588 } 10589 10590 return DAG.getBuildVector(VecVT, SL, Ops); 10591 } 10592 10593 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10594 const SDNode *N0, 10595 const SDNode *N1) const { 10596 EVT VT = N0->getValueType(0); 10597 10598 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10599 // support denormals ever. 10600 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10601 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10602 getSubtarget()->hasMadF16())) && 10603 isOperationLegal(ISD::FMAD, VT)) 10604 return ISD::FMAD; 10605 10606 const TargetOptions &Options = DAG.getTarget().Options; 10607 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10608 (N0->getFlags().hasAllowContract() && 10609 N1->getFlags().hasAllowContract())) && 10610 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10611 return ISD::FMA; 10612 } 10613 10614 return 0; 10615 } 10616 10617 // For a reassociatable opcode perform: 10618 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10619 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10620 SelectionDAG &DAG) const { 10621 EVT VT = N->getValueType(0); 10622 if (VT != MVT::i32 && VT != MVT::i64) 10623 return SDValue(); 10624 10625 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10626 return SDValue(); 10627 10628 unsigned Opc = N->getOpcode(); 10629 SDValue Op0 = N->getOperand(0); 10630 SDValue Op1 = N->getOperand(1); 10631 10632 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10633 return SDValue(); 10634 10635 if (Op0->isDivergent()) 10636 std::swap(Op0, Op1); 10637 10638 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10639 return SDValue(); 10640 10641 SDValue Op2 = Op1.getOperand(1); 10642 Op1 = Op1.getOperand(0); 10643 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10644 return SDValue(); 10645 10646 if (Op1->isDivergent()) 10647 std::swap(Op1, Op2); 10648 10649 SDLoc SL(N); 10650 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10651 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10652 } 10653 10654 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10655 EVT VT, 10656 SDValue N0, SDValue N1, SDValue N2, 10657 bool Signed) { 10658 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10659 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10660 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10661 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10662 } 10663 10664 SDValue SITargetLowering::performAddCombine(SDNode *N, 10665 DAGCombinerInfo &DCI) const { 10666 SelectionDAG &DAG = DCI.DAG; 10667 EVT VT = N->getValueType(0); 10668 SDLoc SL(N); 10669 SDValue LHS = N->getOperand(0); 10670 SDValue RHS = N->getOperand(1); 10671 10672 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10673 && Subtarget->hasMad64_32() && 10674 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10675 VT.getScalarSizeInBits() <= 64) { 10676 if (LHS.getOpcode() != ISD::MUL) 10677 std::swap(LHS, RHS); 10678 10679 SDValue MulLHS = LHS.getOperand(0); 10680 SDValue MulRHS = LHS.getOperand(1); 10681 SDValue AddRHS = RHS; 10682 10683 // TODO: Maybe restrict if SGPR inputs. 10684 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10685 numBitsUnsigned(MulRHS, DAG) <= 32) { 10686 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10687 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10688 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10689 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10690 } 10691 10692 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10693 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10694 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10695 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10696 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10697 } 10698 10699 return SDValue(); 10700 } 10701 10702 if (SDValue V = reassociateScalarOps(N, DAG)) { 10703 return V; 10704 } 10705 10706 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10707 return SDValue(); 10708 10709 // add x, zext (setcc) => addcarry x, 0, setcc 10710 // add x, sext (setcc) => subcarry x, 0, setcc 10711 unsigned Opc = LHS.getOpcode(); 10712 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10713 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10714 std::swap(RHS, LHS); 10715 10716 Opc = RHS.getOpcode(); 10717 switch (Opc) { 10718 default: break; 10719 case ISD::ZERO_EXTEND: 10720 case ISD::SIGN_EXTEND: 10721 case ISD::ANY_EXTEND: { 10722 auto Cond = RHS.getOperand(0); 10723 // If this won't be a real VOPC output, we would still need to insert an 10724 // extra instruction anyway. 10725 if (!isBoolSGPR(Cond)) 10726 break; 10727 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10728 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10729 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10730 return DAG.getNode(Opc, SL, VTList, Args); 10731 } 10732 case ISD::ADDCARRY: { 10733 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10734 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10735 if (!C || C->getZExtValue() != 0) break; 10736 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10737 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10738 } 10739 } 10740 return SDValue(); 10741 } 10742 10743 SDValue SITargetLowering::performSubCombine(SDNode *N, 10744 DAGCombinerInfo &DCI) const { 10745 SelectionDAG &DAG = DCI.DAG; 10746 EVT VT = N->getValueType(0); 10747 10748 if (VT != MVT::i32) 10749 return SDValue(); 10750 10751 SDLoc SL(N); 10752 SDValue LHS = N->getOperand(0); 10753 SDValue RHS = N->getOperand(1); 10754 10755 // sub x, zext (setcc) => subcarry x, 0, setcc 10756 // sub x, sext (setcc) => addcarry x, 0, setcc 10757 unsigned Opc = RHS.getOpcode(); 10758 switch (Opc) { 10759 default: break; 10760 case ISD::ZERO_EXTEND: 10761 case ISD::SIGN_EXTEND: 10762 case ISD::ANY_EXTEND: { 10763 auto Cond = RHS.getOperand(0); 10764 // If this won't be a real VOPC output, we would still need to insert an 10765 // extra instruction anyway. 10766 if (!isBoolSGPR(Cond)) 10767 break; 10768 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10769 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10770 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10771 return DAG.getNode(Opc, SL, VTList, Args); 10772 } 10773 } 10774 10775 if (LHS.getOpcode() == ISD::SUBCARRY) { 10776 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10777 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10778 if (!C || !C->isZero()) 10779 return SDValue(); 10780 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10781 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10782 } 10783 return SDValue(); 10784 } 10785 10786 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10787 DAGCombinerInfo &DCI) const { 10788 10789 if (N->getValueType(0) != MVT::i32) 10790 return SDValue(); 10791 10792 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10793 if (!C || C->getZExtValue() != 0) 10794 return SDValue(); 10795 10796 SelectionDAG &DAG = DCI.DAG; 10797 SDValue LHS = N->getOperand(0); 10798 10799 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10800 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10801 unsigned LHSOpc = LHS.getOpcode(); 10802 unsigned Opc = N->getOpcode(); 10803 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10804 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10805 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10806 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10807 } 10808 return SDValue(); 10809 } 10810 10811 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10812 DAGCombinerInfo &DCI) const { 10813 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10814 return SDValue(); 10815 10816 SelectionDAG &DAG = DCI.DAG; 10817 EVT VT = N->getValueType(0); 10818 10819 SDLoc SL(N); 10820 SDValue LHS = N->getOperand(0); 10821 SDValue RHS = N->getOperand(1); 10822 10823 // These should really be instruction patterns, but writing patterns with 10824 // source modifiers is a pain. 10825 10826 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10827 if (LHS.getOpcode() == ISD::FADD) { 10828 SDValue A = LHS.getOperand(0); 10829 if (A == LHS.getOperand(1)) { 10830 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10831 if (FusedOp != 0) { 10832 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10833 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10834 } 10835 } 10836 } 10837 10838 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10839 if (RHS.getOpcode() == ISD::FADD) { 10840 SDValue A = RHS.getOperand(0); 10841 if (A == RHS.getOperand(1)) { 10842 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10843 if (FusedOp != 0) { 10844 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10845 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10846 } 10847 } 10848 } 10849 10850 return SDValue(); 10851 } 10852 10853 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10854 DAGCombinerInfo &DCI) const { 10855 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10856 return SDValue(); 10857 10858 SelectionDAG &DAG = DCI.DAG; 10859 SDLoc SL(N); 10860 EVT VT = N->getValueType(0); 10861 assert(!VT.isVector()); 10862 10863 // Try to get the fneg to fold into the source modifier. This undoes generic 10864 // DAG combines and folds them into the mad. 10865 // 10866 // Only do this if we are not trying to support denormals. v_mad_f32 does 10867 // not support denormals ever. 10868 SDValue LHS = N->getOperand(0); 10869 SDValue RHS = N->getOperand(1); 10870 if (LHS.getOpcode() == ISD::FADD) { 10871 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10872 SDValue A = LHS.getOperand(0); 10873 if (A == LHS.getOperand(1)) { 10874 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10875 if (FusedOp != 0){ 10876 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10877 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10878 10879 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10880 } 10881 } 10882 } 10883 10884 if (RHS.getOpcode() == ISD::FADD) { 10885 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10886 10887 SDValue A = RHS.getOperand(0); 10888 if (A == RHS.getOperand(1)) { 10889 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10890 if (FusedOp != 0){ 10891 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10892 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10893 } 10894 } 10895 } 10896 10897 return SDValue(); 10898 } 10899 10900 SDValue SITargetLowering::performFMACombine(SDNode *N, 10901 DAGCombinerInfo &DCI) const { 10902 SelectionDAG &DAG = DCI.DAG; 10903 EVT VT = N->getValueType(0); 10904 SDLoc SL(N); 10905 10906 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10907 return SDValue(); 10908 10909 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10910 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10911 SDValue Op1 = N->getOperand(0); 10912 SDValue Op2 = N->getOperand(1); 10913 SDValue FMA = N->getOperand(2); 10914 10915 if (FMA.getOpcode() != ISD::FMA || 10916 Op1.getOpcode() != ISD::FP_EXTEND || 10917 Op2.getOpcode() != ISD::FP_EXTEND) 10918 return SDValue(); 10919 10920 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10921 // regardless of the denorm mode setting. Therefore, 10922 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 10923 const TargetOptions &Options = DAG.getTarget().Options; 10924 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10925 (N->getFlags().hasAllowContract() && 10926 FMA->getFlags().hasAllowContract())) { 10927 Op1 = Op1.getOperand(0); 10928 Op2 = Op2.getOperand(0); 10929 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10930 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10931 return SDValue(); 10932 10933 SDValue Vec1 = Op1.getOperand(0); 10934 SDValue Idx1 = Op1.getOperand(1); 10935 SDValue Vec2 = Op2.getOperand(0); 10936 10937 SDValue FMAOp1 = FMA.getOperand(0); 10938 SDValue FMAOp2 = FMA.getOperand(1); 10939 SDValue FMAAcc = FMA.getOperand(2); 10940 10941 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10942 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10943 return SDValue(); 10944 10945 FMAOp1 = FMAOp1.getOperand(0); 10946 FMAOp2 = FMAOp2.getOperand(0); 10947 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10948 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10949 return SDValue(); 10950 10951 SDValue Vec3 = FMAOp1.getOperand(0); 10952 SDValue Vec4 = FMAOp2.getOperand(0); 10953 SDValue Idx2 = FMAOp1.getOperand(1); 10954 10955 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10956 // Idx1 and Idx2 cannot be the same. 10957 Idx1 == Idx2) 10958 return SDValue(); 10959 10960 if (Vec1 == Vec2 || Vec3 == Vec4) 10961 return SDValue(); 10962 10963 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10964 return SDValue(); 10965 10966 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10967 (Vec1 == Vec4 && Vec2 == Vec3)) { 10968 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10969 DAG.getTargetConstant(0, SL, MVT::i1)); 10970 } 10971 } 10972 return SDValue(); 10973 } 10974 10975 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10976 DAGCombinerInfo &DCI) const { 10977 SelectionDAG &DAG = DCI.DAG; 10978 SDLoc SL(N); 10979 10980 SDValue LHS = N->getOperand(0); 10981 SDValue RHS = N->getOperand(1); 10982 EVT VT = LHS.getValueType(); 10983 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10984 10985 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10986 if (!CRHS) { 10987 CRHS = dyn_cast<ConstantSDNode>(LHS); 10988 if (CRHS) { 10989 std::swap(LHS, RHS); 10990 CC = getSetCCSwappedOperands(CC); 10991 } 10992 } 10993 10994 if (CRHS) { 10995 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10996 isBoolSGPR(LHS.getOperand(0))) { 10997 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10998 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10999 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11000 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11001 if ((CRHS->isAllOnes() && 11002 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11003 (CRHS->isZero() && 11004 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11005 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11006 DAG.getConstant(-1, SL, MVT::i1)); 11007 if ((CRHS->isAllOnes() && 11008 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11009 (CRHS->isZero() && 11010 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11011 return LHS.getOperand(0); 11012 } 11013 11014 const APInt &CRHSVal = CRHS->getAPIntValue(); 11015 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11016 LHS.getOpcode() == ISD::SELECT && 11017 isa<ConstantSDNode>(LHS.getOperand(1)) && 11018 isa<ConstantSDNode>(LHS.getOperand(2)) && 11019 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11020 isBoolSGPR(LHS.getOperand(0))) { 11021 // Given CT != FT: 11022 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11023 // setcc (select cc, CT, CF), CF, ne => cc 11024 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11025 // setcc (select cc, CT, CF), CT, eq => cc 11026 const APInt &CT = LHS.getConstantOperandAPInt(1); 11027 const APInt &CF = LHS.getConstantOperandAPInt(2); 11028 11029 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11030 (CT == CRHSVal && CC == ISD::SETNE)) 11031 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11032 DAG.getConstant(-1, SL, MVT::i1)); 11033 if ((CF == CRHSVal && CC == ISD::SETNE) || 11034 (CT == CRHSVal && CC == ISD::SETEQ)) 11035 return LHS.getOperand(0); 11036 } 11037 } 11038 11039 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11040 VT != MVT::f16)) 11041 return SDValue(); 11042 11043 // Match isinf/isfinite pattern 11044 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11045 // (fcmp one (fabs x), inf) -> (fp_class x, 11046 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11047 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11048 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11049 if (!CRHS) 11050 return SDValue(); 11051 11052 const APFloat &APF = CRHS->getValueAPF(); 11053 if (APF.isInfinity() && !APF.isNegative()) { 11054 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11055 SIInstrFlags::N_INFINITY; 11056 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11057 SIInstrFlags::P_ZERO | 11058 SIInstrFlags::N_NORMAL | 11059 SIInstrFlags::P_NORMAL | 11060 SIInstrFlags::N_SUBNORMAL | 11061 SIInstrFlags::P_SUBNORMAL; 11062 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11063 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11064 DAG.getConstant(Mask, SL, MVT::i32)); 11065 } 11066 } 11067 11068 return SDValue(); 11069 } 11070 11071 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11072 DAGCombinerInfo &DCI) const { 11073 SelectionDAG &DAG = DCI.DAG; 11074 SDLoc SL(N); 11075 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11076 11077 SDValue Src = N->getOperand(0); 11078 SDValue Shift = N->getOperand(0); 11079 11080 // TODO: Extend type shouldn't matter (assuming legal types). 11081 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11082 Shift = Shift.getOperand(0); 11083 11084 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11085 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11086 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11087 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11088 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11089 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11090 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11091 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11092 SDLoc(Shift.getOperand(0)), MVT::i32); 11093 11094 unsigned ShiftOffset = 8 * Offset; 11095 if (Shift.getOpcode() == ISD::SHL) 11096 ShiftOffset -= C->getZExtValue(); 11097 else 11098 ShiftOffset += C->getZExtValue(); 11099 11100 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11101 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11102 MVT::f32, Shifted); 11103 } 11104 } 11105 } 11106 11107 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11108 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11109 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11110 // We simplified Src. If this node is not dead, visit it again so it is 11111 // folded properly. 11112 if (N->getOpcode() != ISD::DELETED_NODE) 11113 DCI.AddToWorklist(N); 11114 return SDValue(N, 0); 11115 } 11116 11117 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11118 if (SDValue DemandedSrc = 11119 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11120 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11121 11122 return SDValue(); 11123 } 11124 11125 SDValue SITargetLowering::performClampCombine(SDNode *N, 11126 DAGCombinerInfo &DCI) const { 11127 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11128 if (!CSrc) 11129 return SDValue(); 11130 11131 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11132 const APFloat &F = CSrc->getValueAPF(); 11133 APFloat Zero = APFloat::getZero(F.getSemantics()); 11134 if (F < Zero || 11135 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11136 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11137 } 11138 11139 APFloat One(F.getSemantics(), "1.0"); 11140 if (F > One) 11141 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11142 11143 return SDValue(CSrc, 0); 11144 } 11145 11146 11147 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11148 DAGCombinerInfo &DCI) const { 11149 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11150 return SDValue(); 11151 switch (N->getOpcode()) { 11152 case ISD::ADD: 11153 return performAddCombine(N, DCI); 11154 case ISD::SUB: 11155 return performSubCombine(N, DCI); 11156 case ISD::ADDCARRY: 11157 case ISD::SUBCARRY: 11158 return performAddCarrySubCarryCombine(N, DCI); 11159 case ISD::FADD: 11160 return performFAddCombine(N, DCI); 11161 case ISD::FSUB: 11162 return performFSubCombine(N, DCI); 11163 case ISD::SETCC: 11164 return performSetCCCombine(N, DCI); 11165 case ISD::FMAXNUM: 11166 case ISD::FMINNUM: 11167 case ISD::FMAXNUM_IEEE: 11168 case ISD::FMINNUM_IEEE: 11169 case ISD::SMAX: 11170 case ISD::SMIN: 11171 case ISD::UMAX: 11172 case ISD::UMIN: 11173 case AMDGPUISD::FMIN_LEGACY: 11174 case AMDGPUISD::FMAX_LEGACY: 11175 return performMinMaxCombine(N, DCI); 11176 case ISD::FMA: 11177 return performFMACombine(N, DCI); 11178 case ISD::AND: 11179 return performAndCombine(N, DCI); 11180 case ISD::OR: 11181 return performOrCombine(N, DCI); 11182 case ISD::XOR: 11183 return performXorCombine(N, DCI); 11184 case ISD::ZERO_EXTEND: 11185 return performZeroExtendCombine(N, DCI); 11186 case ISD::SIGN_EXTEND_INREG: 11187 return performSignExtendInRegCombine(N , DCI); 11188 case AMDGPUISD::FP_CLASS: 11189 return performClassCombine(N, DCI); 11190 case ISD::FCANONICALIZE: 11191 return performFCanonicalizeCombine(N, DCI); 11192 case AMDGPUISD::RCP: 11193 return performRcpCombine(N, DCI); 11194 case AMDGPUISD::FRACT: 11195 case AMDGPUISD::RSQ: 11196 case AMDGPUISD::RCP_LEGACY: 11197 case AMDGPUISD::RCP_IFLAG: 11198 case AMDGPUISD::RSQ_CLAMP: 11199 case AMDGPUISD::LDEXP: { 11200 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11201 SDValue Src = N->getOperand(0); 11202 if (Src.isUndef()) 11203 return Src; 11204 break; 11205 } 11206 case ISD::SINT_TO_FP: 11207 case ISD::UINT_TO_FP: 11208 return performUCharToFloatCombine(N, DCI); 11209 case AMDGPUISD::CVT_F32_UBYTE0: 11210 case AMDGPUISD::CVT_F32_UBYTE1: 11211 case AMDGPUISD::CVT_F32_UBYTE2: 11212 case AMDGPUISD::CVT_F32_UBYTE3: 11213 return performCvtF32UByteNCombine(N, DCI); 11214 case AMDGPUISD::FMED3: 11215 return performFMed3Combine(N, DCI); 11216 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11217 return performCvtPkRTZCombine(N, DCI); 11218 case AMDGPUISD::CLAMP: 11219 return performClampCombine(N, DCI); 11220 case ISD::SCALAR_TO_VECTOR: { 11221 SelectionDAG &DAG = DCI.DAG; 11222 EVT VT = N->getValueType(0); 11223 11224 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11225 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11226 SDLoc SL(N); 11227 SDValue Src = N->getOperand(0); 11228 EVT EltVT = Src.getValueType(); 11229 if (EltVT == MVT::f16) 11230 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11231 11232 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11233 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11234 } 11235 11236 break; 11237 } 11238 case ISD::EXTRACT_VECTOR_ELT: 11239 return performExtractVectorEltCombine(N, DCI); 11240 case ISD::INSERT_VECTOR_ELT: 11241 return performInsertVectorEltCombine(N, DCI); 11242 case ISD::LOAD: { 11243 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11244 return Widended; 11245 LLVM_FALLTHROUGH; 11246 } 11247 default: { 11248 if (!DCI.isBeforeLegalize()) { 11249 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11250 return performMemSDNodeCombine(MemNode, DCI); 11251 } 11252 11253 break; 11254 } 11255 } 11256 11257 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11258 } 11259 11260 /// Helper function for adjustWritemask 11261 static unsigned SubIdx2Lane(unsigned Idx) { 11262 switch (Idx) { 11263 default: return ~0u; 11264 case AMDGPU::sub0: return 0; 11265 case AMDGPU::sub1: return 1; 11266 case AMDGPU::sub2: return 2; 11267 case AMDGPU::sub3: return 3; 11268 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11269 } 11270 } 11271 11272 /// Adjust the writemask of MIMG instructions 11273 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11274 SelectionDAG &DAG) const { 11275 unsigned Opcode = Node->getMachineOpcode(); 11276 11277 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11278 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11279 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11280 return Node; // not implemented for D16 11281 11282 SDNode *Users[5] = { nullptr }; 11283 unsigned Lane = 0; 11284 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11285 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11286 unsigned NewDmask = 0; 11287 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11288 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11289 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11290 Node->getConstantOperandVal(LWEIdx)) 11291 ? true 11292 : false; 11293 unsigned TFCLane = 0; 11294 bool HasChain = Node->getNumValues() > 1; 11295 11296 if (OldDmask == 0) { 11297 // These are folded out, but on the chance it happens don't assert. 11298 return Node; 11299 } 11300 11301 unsigned OldBitsSet = countPopulation(OldDmask); 11302 // Work out which is the TFE/LWE lane if that is enabled. 11303 if (UsesTFC) { 11304 TFCLane = OldBitsSet; 11305 } 11306 11307 // Try to figure out the used register components 11308 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11309 I != E; ++I) { 11310 11311 // Don't look at users of the chain. 11312 if (I.getUse().getResNo() != 0) 11313 continue; 11314 11315 // Abort if we can't understand the usage 11316 if (!I->isMachineOpcode() || 11317 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11318 return Node; 11319 11320 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11321 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11322 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11323 // set, etc. 11324 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11325 if (Lane == ~0u) 11326 return Node; 11327 11328 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11329 if (UsesTFC && Lane == TFCLane) { 11330 Users[Lane] = *I; 11331 } else { 11332 // Set which texture component corresponds to the lane. 11333 unsigned Comp; 11334 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11335 Comp = countTrailingZeros(Dmask); 11336 Dmask &= ~(1 << Comp); 11337 } 11338 11339 // Abort if we have more than one user per component. 11340 if (Users[Lane]) 11341 return Node; 11342 11343 Users[Lane] = *I; 11344 NewDmask |= 1 << Comp; 11345 } 11346 } 11347 11348 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11349 bool NoChannels = !NewDmask; 11350 if (NoChannels) { 11351 if (!UsesTFC) { 11352 // No uses of the result and not using TFC. Then do nothing. 11353 return Node; 11354 } 11355 // If the original dmask has one channel - then nothing to do 11356 if (OldBitsSet == 1) 11357 return Node; 11358 // Use an arbitrary dmask - required for the instruction to work 11359 NewDmask = 1; 11360 } 11361 // Abort if there's no change 11362 if (NewDmask == OldDmask) 11363 return Node; 11364 11365 unsigned BitsSet = countPopulation(NewDmask); 11366 11367 // Check for TFE or LWE - increase the number of channels by one to account 11368 // for the extra return value 11369 // This will need adjustment for D16 if this is also included in 11370 // adjustWriteMask (this function) but at present D16 are excluded. 11371 unsigned NewChannels = BitsSet + UsesTFC; 11372 11373 int NewOpcode = 11374 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11375 assert(NewOpcode != -1 && 11376 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11377 "failed to find equivalent MIMG op"); 11378 11379 // Adjust the writemask in the node 11380 SmallVector<SDValue, 12> Ops; 11381 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11382 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11383 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11384 11385 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11386 11387 MVT ResultVT = NewChannels == 1 ? 11388 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11389 NewChannels == 5 ? 8 : NewChannels); 11390 SDVTList NewVTList = HasChain ? 11391 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11392 11393 11394 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11395 NewVTList, Ops); 11396 11397 if (HasChain) { 11398 // Update chain. 11399 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11400 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11401 } 11402 11403 if (NewChannels == 1) { 11404 assert(Node->hasNUsesOfValue(1, 0)); 11405 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11406 SDLoc(Node), Users[Lane]->getValueType(0), 11407 SDValue(NewNode, 0)); 11408 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11409 return nullptr; 11410 } 11411 11412 // Update the users of the node with the new indices 11413 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11414 SDNode *User = Users[i]; 11415 if (!User) { 11416 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11417 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11418 if (i || !NoChannels) 11419 continue; 11420 } else { 11421 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11422 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11423 } 11424 11425 switch (Idx) { 11426 default: break; 11427 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11428 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11429 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11430 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11431 } 11432 } 11433 11434 DAG.RemoveDeadNode(Node); 11435 return nullptr; 11436 } 11437 11438 static bool isFrameIndexOp(SDValue Op) { 11439 if (Op.getOpcode() == ISD::AssertZext) 11440 Op = Op.getOperand(0); 11441 11442 return isa<FrameIndexSDNode>(Op); 11443 } 11444 11445 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11446 /// with frame index operands. 11447 /// LLVM assumes that inputs are to these instructions are registers. 11448 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11449 SelectionDAG &DAG) const { 11450 if (Node->getOpcode() == ISD::CopyToReg) { 11451 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11452 SDValue SrcVal = Node->getOperand(2); 11453 11454 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11455 // to try understanding copies to physical registers. 11456 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11457 SDLoc SL(Node); 11458 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11459 SDValue VReg = DAG.getRegister( 11460 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11461 11462 SDNode *Glued = Node->getGluedNode(); 11463 SDValue ToVReg 11464 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11465 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11466 SDValue ToResultReg 11467 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11468 VReg, ToVReg.getValue(1)); 11469 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11470 DAG.RemoveDeadNode(Node); 11471 return ToResultReg.getNode(); 11472 } 11473 } 11474 11475 SmallVector<SDValue, 8> Ops; 11476 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11477 if (!isFrameIndexOp(Node->getOperand(i))) { 11478 Ops.push_back(Node->getOperand(i)); 11479 continue; 11480 } 11481 11482 SDLoc DL(Node); 11483 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11484 Node->getOperand(i).getValueType(), 11485 Node->getOperand(i)), 0)); 11486 } 11487 11488 return DAG.UpdateNodeOperands(Node, Ops); 11489 } 11490 11491 /// Fold the instructions after selecting them. 11492 /// Returns null if users were already updated. 11493 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11494 SelectionDAG &DAG) const { 11495 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11496 unsigned Opcode = Node->getMachineOpcode(); 11497 11498 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11499 !TII->isGather4(Opcode) && 11500 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11501 return adjustWritemask(Node, DAG); 11502 } 11503 11504 if (Opcode == AMDGPU::INSERT_SUBREG || 11505 Opcode == AMDGPU::REG_SEQUENCE) { 11506 legalizeTargetIndependentNode(Node, DAG); 11507 return Node; 11508 } 11509 11510 switch (Opcode) { 11511 case AMDGPU::V_DIV_SCALE_F32_e64: 11512 case AMDGPU::V_DIV_SCALE_F64_e64: { 11513 // Satisfy the operand register constraint when one of the inputs is 11514 // undefined. Ordinarily each undef value will have its own implicit_def of 11515 // a vreg, so force these to use a single register. 11516 SDValue Src0 = Node->getOperand(1); 11517 SDValue Src1 = Node->getOperand(3); 11518 SDValue Src2 = Node->getOperand(5); 11519 11520 if ((Src0.isMachineOpcode() && 11521 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11522 (Src0 == Src1 || Src0 == Src2)) 11523 break; 11524 11525 MVT VT = Src0.getValueType().getSimpleVT(); 11526 const TargetRegisterClass *RC = 11527 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11528 11529 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11530 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11531 11532 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11533 UndefReg, Src0, SDValue()); 11534 11535 // src0 must be the same register as src1 or src2, even if the value is 11536 // undefined, so make sure we don't violate this constraint. 11537 if (Src0.isMachineOpcode() && 11538 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11539 if (Src1.isMachineOpcode() && 11540 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11541 Src0 = Src1; 11542 else if (Src2.isMachineOpcode() && 11543 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11544 Src0 = Src2; 11545 else { 11546 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11547 Src0 = UndefReg; 11548 Src1 = UndefReg; 11549 } 11550 } else 11551 break; 11552 11553 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11554 Ops[1] = Src0; 11555 Ops[3] = Src1; 11556 Ops[5] = Src2; 11557 Ops.push_back(ImpDef.getValue(1)); 11558 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11559 } 11560 default: 11561 break; 11562 } 11563 11564 return Node; 11565 } 11566 11567 // Any MIMG instructions that use tfe or lwe require an initialization of the 11568 // result register that will be written in the case of a memory access failure. 11569 // The required code is also added to tie this init code to the result of the 11570 // img instruction. 11571 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11572 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11573 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11574 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11575 MachineBasicBlock &MBB = *MI.getParent(); 11576 11577 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11578 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11579 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11580 11581 if (!TFE && !LWE) // intersect_ray 11582 return; 11583 11584 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11585 unsigned LWEVal = LWE->getImm(); 11586 unsigned D16Val = D16 ? D16->getImm() : 0; 11587 11588 if (!TFEVal && !LWEVal) 11589 return; 11590 11591 // At least one of TFE or LWE are non-zero 11592 // We have to insert a suitable initialization of the result value and 11593 // tie this to the dest of the image instruction. 11594 11595 const DebugLoc &DL = MI.getDebugLoc(); 11596 11597 int DstIdx = 11598 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11599 11600 // Calculate which dword we have to initialize to 0. 11601 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11602 11603 // check that dmask operand is found. 11604 assert(MO_Dmask && "Expected dmask operand in instruction"); 11605 11606 unsigned dmask = MO_Dmask->getImm(); 11607 // Determine the number of active lanes taking into account the 11608 // Gather4 special case 11609 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11610 11611 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11612 11613 unsigned InitIdx = 11614 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11615 11616 // Abandon attempt if the dst size isn't large enough 11617 // - this is in fact an error but this is picked up elsewhere and 11618 // reported correctly. 11619 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11620 if (DstSize < InitIdx) 11621 return; 11622 11623 // Create a register for the initialization value. 11624 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11625 unsigned NewDst = 0; // Final initialized value will be in here 11626 11627 // If PRTStrictNull feature is enabled (the default) then initialize 11628 // all the result registers to 0, otherwise just the error indication 11629 // register (VGPRn+1) 11630 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11631 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11632 11633 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11634 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11635 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11636 // Initialize dword 11637 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11638 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11639 .addImm(0); 11640 // Insert into the super-reg 11641 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11642 .addReg(PrevDst) 11643 .addReg(SubReg) 11644 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11645 11646 PrevDst = NewDst; 11647 } 11648 11649 // Add as an implicit operand 11650 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11651 11652 // Tie the just added implicit operand to the dst 11653 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11654 } 11655 11656 /// Assign the register class depending on the number of 11657 /// bits set in the writemask 11658 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11659 SDNode *Node) const { 11660 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11661 11662 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11663 11664 if (TII->isVOP3(MI.getOpcode())) { 11665 // Make sure constant bus requirements are respected. 11666 TII->legalizeOperandsVOP3(MRI, MI); 11667 11668 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11669 // This saves a chain-copy of registers and better balance register 11670 // use between vgpr and agpr as agpr tuples tend to be big. 11671 if (MI.getDesc().OpInfo) { 11672 unsigned Opc = MI.getOpcode(); 11673 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11674 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11675 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11676 if (I == -1) 11677 break; 11678 MachineOperand &Op = MI.getOperand(I); 11679 if (!Op.isReg() || !Op.getReg().isVirtual()) 11680 continue; 11681 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11682 if (!TRI->hasAGPRs(RC)) 11683 continue; 11684 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11685 if (!Src || !Src->isCopy() || 11686 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11687 continue; 11688 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11689 // All uses of agpr64 and agpr32 can also accept vgpr except for 11690 // v_accvgpr_read, but we do not produce agpr reads during selection, 11691 // so no use checks are needed. 11692 MRI.setRegClass(Op.getReg(), NewRC); 11693 } 11694 11695 // Resolve the rest of AV operands to AGPRs. 11696 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11697 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11698 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11699 if (TRI->isVectorSuperClass(RC)) { 11700 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11701 MRI.setRegClass(Src2->getReg(), NewRC); 11702 if (Src2->isTied()) 11703 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11704 } 11705 } 11706 } 11707 } 11708 11709 return; 11710 } 11711 11712 if (TII->isMIMG(MI) && !MI.mayStore()) 11713 AddIMGInit(MI); 11714 } 11715 11716 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11717 uint64_t Val) { 11718 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11719 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11720 } 11721 11722 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11723 const SDLoc &DL, 11724 SDValue Ptr) const { 11725 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11726 11727 // Build the half of the subregister with the constants before building the 11728 // full 128-bit register. If we are building multiple resource descriptors, 11729 // this will allow CSEing of the 2-component register. 11730 const SDValue Ops0[] = { 11731 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11732 buildSMovImm32(DAG, DL, 0), 11733 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11734 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11735 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11736 }; 11737 11738 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11739 MVT::v2i32, Ops0), 0); 11740 11741 // Combine the constants and the pointer. 11742 const SDValue Ops1[] = { 11743 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11744 Ptr, 11745 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11746 SubRegHi, 11747 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11748 }; 11749 11750 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11751 } 11752 11753 /// Return a resource descriptor with the 'Add TID' bit enabled 11754 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11755 /// of the resource descriptor) to create an offset, which is added to 11756 /// the resource pointer. 11757 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11758 SDValue Ptr, uint32_t RsrcDword1, 11759 uint64_t RsrcDword2And3) const { 11760 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11761 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11762 if (RsrcDword1) { 11763 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11764 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11765 0); 11766 } 11767 11768 SDValue DataLo = buildSMovImm32(DAG, DL, 11769 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11770 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11771 11772 const SDValue Ops[] = { 11773 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11774 PtrLo, 11775 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11776 PtrHi, 11777 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11778 DataLo, 11779 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11780 DataHi, 11781 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11782 }; 11783 11784 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11785 } 11786 11787 //===----------------------------------------------------------------------===// 11788 // SI Inline Assembly Support 11789 //===----------------------------------------------------------------------===// 11790 11791 std::pair<unsigned, const TargetRegisterClass *> 11792 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11793 StringRef Constraint, 11794 MVT VT) const { 11795 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11796 11797 const TargetRegisterClass *RC = nullptr; 11798 if (Constraint.size() == 1) { 11799 const unsigned BitWidth = VT.getSizeInBits(); 11800 switch (Constraint[0]) { 11801 default: 11802 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11803 case 's': 11804 case 'r': 11805 switch (BitWidth) { 11806 case 16: 11807 RC = &AMDGPU::SReg_32RegClass; 11808 break; 11809 case 64: 11810 RC = &AMDGPU::SGPR_64RegClass; 11811 break; 11812 default: 11813 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11814 if (!RC) 11815 return std::make_pair(0U, nullptr); 11816 break; 11817 } 11818 break; 11819 case 'v': 11820 switch (BitWidth) { 11821 case 16: 11822 RC = &AMDGPU::VGPR_32RegClass; 11823 break; 11824 default: 11825 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11826 if (!RC) 11827 return std::make_pair(0U, nullptr); 11828 break; 11829 } 11830 break; 11831 case 'a': 11832 if (!Subtarget->hasMAIInsts()) 11833 break; 11834 switch (BitWidth) { 11835 case 16: 11836 RC = &AMDGPU::AGPR_32RegClass; 11837 break; 11838 default: 11839 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11840 if (!RC) 11841 return std::make_pair(0U, nullptr); 11842 break; 11843 } 11844 break; 11845 } 11846 // We actually support i128, i16 and f16 as inline parameters 11847 // even if they are not reported as legal 11848 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11849 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11850 return std::make_pair(0U, RC); 11851 } 11852 11853 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11854 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11855 if (RegName.consume_front("v")) { 11856 RC = &AMDGPU::VGPR_32RegClass; 11857 } else if (RegName.consume_front("s")) { 11858 RC = &AMDGPU::SGPR_32RegClass; 11859 } else if (RegName.consume_front("a")) { 11860 RC = &AMDGPU::AGPR_32RegClass; 11861 } 11862 11863 if (RC) { 11864 uint32_t Idx; 11865 if (RegName.consume_front("[")) { 11866 uint32_t End; 11867 bool Failed = RegName.consumeInteger(10, Idx); 11868 Failed |= !RegName.consume_front(":"); 11869 Failed |= RegName.consumeInteger(10, End); 11870 Failed |= !RegName.consume_back("]"); 11871 if (!Failed) { 11872 uint32_t Width = (End - Idx + 1) * 32; 11873 MCRegister Reg = RC->getRegister(Idx); 11874 if (SIRegisterInfo::isVGPRClass(RC)) 11875 RC = TRI->getVGPRClassForBitWidth(Width); 11876 else if (SIRegisterInfo::isSGPRClass(RC)) 11877 RC = TRI->getSGPRClassForBitWidth(Width); 11878 else if (SIRegisterInfo::isAGPRClass(RC)) 11879 RC = TRI->getAGPRClassForBitWidth(Width); 11880 if (RC) { 11881 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11882 return std::make_pair(Reg, RC); 11883 } 11884 } 11885 } else { 11886 bool Failed = RegName.getAsInteger(10, Idx); 11887 if (!Failed && Idx < RC->getNumRegs()) 11888 return std::make_pair(RC->getRegister(Idx), RC); 11889 } 11890 } 11891 } 11892 11893 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11894 if (Ret.first) 11895 Ret.second = TRI->getPhysRegClass(Ret.first); 11896 11897 return Ret; 11898 } 11899 11900 static bool isImmConstraint(StringRef Constraint) { 11901 if (Constraint.size() == 1) { 11902 switch (Constraint[0]) { 11903 default: break; 11904 case 'I': 11905 case 'J': 11906 case 'A': 11907 case 'B': 11908 case 'C': 11909 return true; 11910 } 11911 } else if (Constraint == "DA" || 11912 Constraint == "DB") { 11913 return true; 11914 } 11915 return false; 11916 } 11917 11918 SITargetLowering::ConstraintType 11919 SITargetLowering::getConstraintType(StringRef Constraint) const { 11920 if (Constraint.size() == 1) { 11921 switch (Constraint[0]) { 11922 default: break; 11923 case 's': 11924 case 'v': 11925 case 'a': 11926 return C_RegisterClass; 11927 } 11928 } 11929 if (isImmConstraint(Constraint)) { 11930 return C_Other; 11931 } 11932 return TargetLowering::getConstraintType(Constraint); 11933 } 11934 11935 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11936 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11937 Val = Val & maskTrailingOnes<uint64_t>(Size); 11938 } 11939 return Val; 11940 } 11941 11942 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11943 std::string &Constraint, 11944 std::vector<SDValue> &Ops, 11945 SelectionDAG &DAG) const { 11946 if (isImmConstraint(Constraint)) { 11947 uint64_t Val; 11948 if (getAsmOperandConstVal(Op, Val) && 11949 checkAsmConstraintVal(Op, Constraint, Val)) { 11950 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11951 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11952 } 11953 } else { 11954 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11955 } 11956 } 11957 11958 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11959 unsigned Size = Op.getScalarValueSizeInBits(); 11960 if (Size > 64) 11961 return false; 11962 11963 if (Size == 16 && !Subtarget->has16BitInsts()) 11964 return false; 11965 11966 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11967 Val = C->getSExtValue(); 11968 return true; 11969 } 11970 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11971 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11972 return true; 11973 } 11974 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11975 if (Size != 16 || Op.getNumOperands() != 2) 11976 return false; 11977 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11978 return false; 11979 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11980 Val = C->getSExtValue(); 11981 return true; 11982 } 11983 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11984 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11985 return true; 11986 } 11987 } 11988 11989 return false; 11990 } 11991 11992 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11993 const std::string &Constraint, 11994 uint64_t Val) const { 11995 if (Constraint.size() == 1) { 11996 switch (Constraint[0]) { 11997 case 'I': 11998 return AMDGPU::isInlinableIntLiteral(Val); 11999 case 'J': 12000 return isInt<16>(Val); 12001 case 'A': 12002 return checkAsmConstraintValA(Op, Val); 12003 case 'B': 12004 return isInt<32>(Val); 12005 case 'C': 12006 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12007 AMDGPU::isInlinableIntLiteral(Val); 12008 default: 12009 break; 12010 } 12011 } else if (Constraint.size() == 2) { 12012 if (Constraint == "DA") { 12013 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12014 int64_t LoBits = static_cast<int32_t>(Val); 12015 return checkAsmConstraintValA(Op, HiBits, 32) && 12016 checkAsmConstraintValA(Op, LoBits, 32); 12017 } 12018 if (Constraint == "DB") { 12019 return true; 12020 } 12021 } 12022 llvm_unreachable("Invalid asm constraint"); 12023 } 12024 12025 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12026 uint64_t Val, 12027 unsigned MaxSize) const { 12028 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12029 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12030 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12031 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12032 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12033 return true; 12034 } 12035 return false; 12036 } 12037 12038 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12039 switch (UnalignedClassID) { 12040 case AMDGPU::VReg_64RegClassID: 12041 return AMDGPU::VReg_64_Align2RegClassID; 12042 case AMDGPU::VReg_96RegClassID: 12043 return AMDGPU::VReg_96_Align2RegClassID; 12044 case AMDGPU::VReg_128RegClassID: 12045 return AMDGPU::VReg_128_Align2RegClassID; 12046 case AMDGPU::VReg_160RegClassID: 12047 return AMDGPU::VReg_160_Align2RegClassID; 12048 case AMDGPU::VReg_192RegClassID: 12049 return AMDGPU::VReg_192_Align2RegClassID; 12050 case AMDGPU::VReg_224RegClassID: 12051 return AMDGPU::VReg_224_Align2RegClassID; 12052 case AMDGPU::VReg_256RegClassID: 12053 return AMDGPU::VReg_256_Align2RegClassID; 12054 case AMDGPU::VReg_512RegClassID: 12055 return AMDGPU::VReg_512_Align2RegClassID; 12056 case AMDGPU::VReg_1024RegClassID: 12057 return AMDGPU::VReg_1024_Align2RegClassID; 12058 case AMDGPU::AReg_64RegClassID: 12059 return AMDGPU::AReg_64_Align2RegClassID; 12060 case AMDGPU::AReg_96RegClassID: 12061 return AMDGPU::AReg_96_Align2RegClassID; 12062 case AMDGPU::AReg_128RegClassID: 12063 return AMDGPU::AReg_128_Align2RegClassID; 12064 case AMDGPU::AReg_160RegClassID: 12065 return AMDGPU::AReg_160_Align2RegClassID; 12066 case AMDGPU::AReg_192RegClassID: 12067 return AMDGPU::AReg_192_Align2RegClassID; 12068 case AMDGPU::AReg_256RegClassID: 12069 return AMDGPU::AReg_256_Align2RegClassID; 12070 case AMDGPU::AReg_512RegClassID: 12071 return AMDGPU::AReg_512_Align2RegClassID; 12072 case AMDGPU::AReg_1024RegClassID: 12073 return AMDGPU::AReg_1024_Align2RegClassID; 12074 default: 12075 return -1; 12076 } 12077 } 12078 12079 // Figure out which registers should be reserved for stack access. Only after 12080 // the function is legalized do we know all of the non-spill stack objects or if 12081 // calls are present. 12082 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12083 MachineRegisterInfo &MRI = MF.getRegInfo(); 12084 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12085 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12086 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12087 const SIInstrInfo *TII = ST.getInstrInfo(); 12088 12089 if (Info->isEntryFunction()) { 12090 // Callable functions have fixed registers used for stack access. 12091 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12092 } 12093 12094 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12095 Info->getStackPtrOffsetReg())); 12096 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12097 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12098 12099 // We need to worry about replacing the default register with itself in case 12100 // of MIR testcases missing the MFI. 12101 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12102 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12103 12104 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12105 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12106 12107 Info->limitOccupancy(MF); 12108 12109 if (ST.isWave32() && !MF.empty()) { 12110 for (auto &MBB : MF) { 12111 for (auto &MI : MBB) { 12112 TII->fixImplicitOperands(MI); 12113 } 12114 } 12115 } 12116 12117 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12118 // classes if required. Ideally the register class constraints would differ 12119 // per-subtarget, but there's no easy way to achieve that right now. This is 12120 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12121 // from using them as the register class for legal types. 12122 if (ST.needsAlignedVGPRs()) { 12123 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12124 const Register Reg = Register::index2VirtReg(I); 12125 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12126 if (!RC) 12127 continue; 12128 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12129 if (NewClassID != -1) 12130 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12131 } 12132 } 12133 12134 TargetLoweringBase::finalizeLowering(MF); 12135 } 12136 12137 void SITargetLowering::computeKnownBitsForFrameIndex( 12138 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12139 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12140 12141 // Set the high bits to zero based on the maximum allowed scratch size per 12142 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12143 // calculation won't overflow, so assume the sign bit is never set. 12144 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12145 } 12146 12147 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12148 KnownBits &Known, unsigned Dim) { 12149 unsigned MaxValue = 12150 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12151 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12152 } 12153 12154 void SITargetLowering::computeKnownBitsForTargetInstr( 12155 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12156 const MachineRegisterInfo &MRI, unsigned Depth) const { 12157 const MachineInstr *MI = MRI.getVRegDef(R); 12158 switch (MI->getOpcode()) { 12159 case AMDGPU::G_INTRINSIC: { 12160 switch (MI->getIntrinsicID()) { 12161 case Intrinsic::amdgcn_workitem_id_x: 12162 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12163 break; 12164 case Intrinsic::amdgcn_workitem_id_y: 12165 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12166 break; 12167 case Intrinsic::amdgcn_workitem_id_z: 12168 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12169 break; 12170 case Intrinsic::amdgcn_mbcnt_lo: 12171 case Intrinsic::amdgcn_mbcnt_hi: { 12172 // These return at most the wavefront size - 1. 12173 unsigned Size = MRI.getType(R).getSizeInBits(); 12174 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12175 break; 12176 } 12177 case Intrinsic::amdgcn_groupstaticsize: { 12178 // We can report everything over the maximum size as 0. We can't report 12179 // based on the actual size because we don't know if it's accurate or not 12180 // at any given point. 12181 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12182 break; 12183 } 12184 } 12185 break; 12186 } 12187 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12188 Known.Zero.setHighBits(24); 12189 break; 12190 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12191 Known.Zero.setHighBits(16); 12192 break; 12193 } 12194 } 12195 12196 Align SITargetLowering::computeKnownAlignForTargetInstr( 12197 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12198 unsigned Depth) const { 12199 const MachineInstr *MI = MRI.getVRegDef(R); 12200 switch (MI->getOpcode()) { 12201 case AMDGPU::G_INTRINSIC: 12202 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12203 // FIXME: Can this move to generic code? What about the case where the call 12204 // site specifies a lower alignment? 12205 Intrinsic::ID IID = MI->getIntrinsicID(); 12206 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12207 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12208 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12209 return *RetAlign; 12210 return Align(1); 12211 } 12212 default: 12213 return Align(1); 12214 } 12215 } 12216 12217 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12218 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12219 const Align CacheLineAlign = Align(64); 12220 12221 // Pre-GFX10 target did not benefit from loop alignment 12222 if (!ML || DisableLoopAlignment || 12223 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12224 getSubtarget()->hasInstFwdPrefetchBug()) 12225 return PrefAlign; 12226 12227 // On GFX10 I$ is 4 x 64 bytes cache lines. 12228 // By default prefetcher keeps one cache line behind and reads two ahead. 12229 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12230 // behind and one ahead. 12231 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12232 // If loop fits 64 bytes it always spans no more than two cache lines and 12233 // does not need an alignment. 12234 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12235 // Else if loop is less or equal 192 bytes we need two lines behind. 12236 12237 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12238 const MachineBasicBlock *Header = ML->getHeader(); 12239 if (Header->getAlignment() != PrefAlign) 12240 return Header->getAlignment(); // Already processed. 12241 12242 unsigned LoopSize = 0; 12243 for (const MachineBasicBlock *MBB : ML->blocks()) { 12244 // If inner loop block is aligned assume in average half of the alignment 12245 // size to be added as nops. 12246 if (MBB != Header) 12247 LoopSize += MBB->getAlignment().value() / 2; 12248 12249 for (const MachineInstr &MI : *MBB) { 12250 LoopSize += TII->getInstSizeInBytes(MI); 12251 if (LoopSize > 192) 12252 return PrefAlign; 12253 } 12254 } 12255 12256 if (LoopSize <= 64) 12257 return PrefAlign; 12258 12259 if (LoopSize <= 128) 12260 return CacheLineAlign; 12261 12262 // If any of parent loops is surrounded by prefetch instructions do not 12263 // insert new for inner loop, which would reset parent's settings. 12264 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12265 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12266 auto I = Exit->getFirstNonDebugInstr(); 12267 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12268 return CacheLineAlign; 12269 } 12270 } 12271 12272 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12273 MachineBasicBlock *Exit = ML->getExitBlock(); 12274 12275 if (Pre && Exit) { 12276 auto PreTerm = Pre->getFirstTerminator(); 12277 if (PreTerm == Pre->begin() || 12278 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12279 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12280 .addImm(1); // prefetch 2 lines behind PC 12281 12282 auto ExitHead = Exit->getFirstNonDebugInstr(); 12283 if (ExitHead == Exit->end() || 12284 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12285 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12286 .addImm(2); // prefetch 1 line behind PC 12287 } 12288 12289 return CacheLineAlign; 12290 } 12291 12292 LLVM_ATTRIBUTE_UNUSED 12293 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12294 assert(N->getOpcode() == ISD::CopyFromReg); 12295 do { 12296 // Follow the chain until we find an INLINEASM node. 12297 N = N->getOperand(0).getNode(); 12298 if (N->getOpcode() == ISD::INLINEASM || 12299 N->getOpcode() == ISD::INLINEASM_BR) 12300 return true; 12301 } while (N->getOpcode() == ISD::CopyFromReg); 12302 return false; 12303 } 12304 12305 bool SITargetLowering::isSDNodeSourceOfDivergence( 12306 const SDNode *N, FunctionLoweringInfo *FLI, 12307 LegacyDivergenceAnalysis *KDA) const { 12308 switch (N->getOpcode()) { 12309 case ISD::CopyFromReg: { 12310 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12311 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12312 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12313 Register Reg = R->getReg(); 12314 12315 // FIXME: Why does this need to consider isLiveIn? 12316 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12317 return !TRI->isSGPRReg(MRI, Reg); 12318 12319 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12320 return KDA->isDivergent(V); 12321 12322 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12323 return !TRI->isSGPRReg(MRI, Reg); 12324 } 12325 case ISD::LOAD: { 12326 const LoadSDNode *L = cast<LoadSDNode>(N); 12327 unsigned AS = L->getAddressSpace(); 12328 // A flat load may access private memory. 12329 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12330 } 12331 case ISD::CALLSEQ_END: 12332 return true; 12333 case ISD::INTRINSIC_WO_CHAIN: 12334 return AMDGPU::isIntrinsicSourceOfDivergence( 12335 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12336 case ISD::INTRINSIC_W_CHAIN: 12337 return AMDGPU::isIntrinsicSourceOfDivergence( 12338 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12339 case AMDGPUISD::ATOMIC_CMP_SWAP: 12340 case AMDGPUISD::ATOMIC_INC: 12341 case AMDGPUISD::ATOMIC_DEC: 12342 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12343 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12344 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12345 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12346 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12347 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12348 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12349 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12350 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12351 case AMDGPUISD::BUFFER_ATOMIC_AND: 12352 case AMDGPUISD::BUFFER_ATOMIC_OR: 12353 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12354 case AMDGPUISD::BUFFER_ATOMIC_INC: 12355 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12356 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12357 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12358 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12359 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12360 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12361 // Target-specific read-modify-write atomics are sources of divergence. 12362 return true; 12363 default: 12364 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12365 // Generic read-modify-write atomics are sources of divergence. 12366 return A->readMem() && A->writeMem(); 12367 } 12368 return false; 12369 } 12370 } 12371 12372 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12373 EVT VT) const { 12374 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12375 case MVT::f32: 12376 return hasFP32Denormals(DAG.getMachineFunction()); 12377 case MVT::f64: 12378 case MVT::f16: 12379 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12380 default: 12381 return false; 12382 } 12383 } 12384 12385 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12386 MachineFunction &MF) const { 12387 switch (Ty.getScalarSizeInBits()) { 12388 case 32: 12389 return hasFP32Denormals(MF); 12390 case 64: 12391 case 16: 12392 return hasFP64FP16Denormals(MF); 12393 default: 12394 return false; 12395 } 12396 } 12397 12398 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12399 const SelectionDAG &DAG, 12400 bool SNaN, 12401 unsigned Depth) const { 12402 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12403 const MachineFunction &MF = DAG.getMachineFunction(); 12404 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12405 12406 if (Info->getMode().DX10Clamp) 12407 return true; // Clamped to 0. 12408 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12409 } 12410 12411 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12412 SNaN, Depth); 12413 } 12414 12415 // Global FP atomic instructions have a hardcoded FP mode and do not support 12416 // FP32 denormals, and only support v2f16 denormals. 12417 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12418 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12419 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12420 if (&Flt == &APFloat::IEEEsingle()) 12421 return DenormMode == DenormalMode::getPreserveSign(); 12422 return DenormMode == DenormalMode::getIEEE(); 12423 } 12424 12425 TargetLowering::AtomicExpansionKind 12426 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12427 unsigned AS = RMW->getPointerAddressSpace(); 12428 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12429 return AtomicExpansionKind::NotAtomic; 12430 12431 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12432 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12433 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12434 SmallVector<StringRef> SSNs; 12435 Ctx.getSyncScopeNames(SSNs); 12436 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12437 ? "system" 12438 : SSNs[RMW->getSyncScopeID()]; 12439 ORE.emit([&]() { 12440 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12441 << "Hardware instruction generated for atomic " 12442 << RMW->getOperationName(RMW->getOperation()) 12443 << " operation at memory scope " << MemScope 12444 << " due to an unsafe request."; 12445 }); 12446 return Kind; 12447 }; 12448 12449 switch (RMW->getOperation()) { 12450 case AtomicRMWInst::FAdd: { 12451 Type *Ty = RMW->getType(); 12452 12453 // We don't have a way to support 16-bit atomics now, so just leave them 12454 // as-is. 12455 if (Ty->isHalfTy()) 12456 return AtomicExpansionKind::None; 12457 12458 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12459 return AtomicExpansionKind::CmpXChg; 12460 12461 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12462 Subtarget->hasAtomicFaddInsts()) { 12463 if (Subtarget->hasGFX940Insts()) 12464 return AtomicExpansionKind::None; 12465 12466 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12467 // floating point atomic instructions. May generate more efficient code, 12468 // but may not respect rounding and denormal modes, and may give incorrect 12469 // results for certain memory destinations. 12470 if (RMW->getFunction() 12471 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12472 .getValueAsString() != "true") 12473 return AtomicExpansionKind::CmpXChg; 12474 12475 if (Subtarget->hasGFX90AInsts()) { 12476 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12477 return AtomicExpansionKind::CmpXChg; 12478 12479 auto SSID = RMW->getSyncScopeID(); 12480 if (SSID == SyncScope::System || 12481 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12482 return AtomicExpansionKind::CmpXChg; 12483 12484 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12485 } 12486 12487 if (AS == AMDGPUAS::FLAT_ADDRESS) 12488 return AtomicExpansionKind::CmpXChg; 12489 12490 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12491 : AtomicExpansionKind::CmpXChg; 12492 } 12493 12494 // DS FP atomics do respect the denormal mode, but the rounding mode is 12495 // fixed to round-to-nearest-even. 12496 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12497 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12498 if (!Ty->isDoubleTy()) 12499 return AtomicExpansionKind::None; 12500 12501 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12502 return AtomicExpansionKind::None; 12503 12504 return RMW->getFunction() 12505 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12506 .getValueAsString() == "true" 12507 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12508 : AtomicExpansionKind::CmpXChg; 12509 } 12510 12511 return AtomicExpansionKind::CmpXChg; 12512 } 12513 default: 12514 break; 12515 } 12516 12517 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12518 } 12519 12520 TargetLowering::AtomicExpansionKind 12521 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12522 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12523 ? AtomicExpansionKind::NotAtomic 12524 : AtomicExpansionKind::None; 12525 } 12526 12527 TargetLowering::AtomicExpansionKind 12528 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12529 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12530 ? AtomicExpansionKind::NotAtomic 12531 : AtomicExpansionKind::None; 12532 } 12533 12534 TargetLowering::AtomicExpansionKind 12535 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12536 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12537 ? AtomicExpansionKind::NotAtomic 12538 : AtomicExpansionKind::None; 12539 } 12540 12541 const TargetRegisterClass * 12542 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12543 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12544 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12545 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12546 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12547 : &AMDGPU::SReg_32RegClass; 12548 if (!TRI->isSGPRClass(RC) && !isDivergent) 12549 return TRI->getEquivalentSGPRClass(RC); 12550 else if (TRI->isSGPRClass(RC) && isDivergent) 12551 return TRI->getEquivalentVGPRClass(RC); 12552 12553 return RC; 12554 } 12555 12556 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12557 // uniform values (as produced by the mask results of control flow intrinsics) 12558 // used outside of divergent blocks. The phi users need to also be treated as 12559 // always uniform. 12560 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12561 unsigned WaveSize) { 12562 // FIXME: We assume we never cast the mask results of a control flow 12563 // intrinsic. 12564 // Early exit if the type won't be consistent as a compile time hack. 12565 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12566 if (!IT || IT->getBitWidth() != WaveSize) 12567 return false; 12568 12569 if (!isa<Instruction>(V)) 12570 return false; 12571 if (!Visited.insert(V).second) 12572 return false; 12573 bool Result = false; 12574 for (auto U : V->users()) { 12575 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12576 if (V == U->getOperand(1)) { 12577 switch (Intrinsic->getIntrinsicID()) { 12578 default: 12579 Result = false; 12580 break; 12581 case Intrinsic::amdgcn_if_break: 12582 case Intrinsic::amdgcn_if: 12583 case Intrinsic::amdgcn_else: 12584 Result = true; 12585 break; 12586 } 12587 } 12588 if (V == U->getOperand(0)) { 12589 switch (Intrinsic->getIntrinsicID()) { 12590 default: 12591 Result = false; 12592 break; 12593 case Intrinsic::amdgcn_end_cf: 12594 case Intrinsic::amdgcn_loop: 12595 Result = true; 12596 break; 12597 } 12598 } 12599 } else { 12600 Result = hasCFUser(U, Visited, WaveSize); 12601 } 12602 if (Result) 12603 break; 12604 } 12605 return Result; 12606 } 12607 12608 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12609 const Value *V) const { 12610 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12611 if (CI->isInlineAsm()) { 12612 // FIXME: This cannot give a correct answer. This should only trigger in 12613 // the case where inline asm returns mixed SGPR and VGPR results, used 12614 // outside the defining block. We don't have a specific result to 12615 // consider, so this assumes if any value is SGPR, the overall register 12616 // also needs to be SGPR. 12617 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12618 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12619 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12620 for (auto &TC : TargetConstraints) { 12621 if (TC.Type == InlineAsm::isOutput) { 12622 ComputeConstraintToUse(TC, SDValue()); 12623 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12624 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12625 if (RC && SIRI->isSGPRClass(RC)) 12626 return true; 12627 } 12628 } 12629 } 12630 } 12631 SmallPtrSet<const Value *, 16> Visited; 12632 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12633 } 12634 12635 std::pair<InstructionCost, MVT> 12636 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12637 Type *Ty) const { 12638 std::pair<InstructionCost, MVT> Cost = 12639 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12640 auto Size = DL.getTypeSizeInBits(Ty); 12641 // Maximum load or store can handle 8 dwords for scalar and 4 for 12642 // vector ALU. Let's assume anything above 8 dwords is expensive 12643 // even if legal. 12644 if (Size <= 256) 12645 return Cost; 12646 12647 Cost.first += (Size + 255) / 256; 12648 return Cost; 12649 } 12650 12651 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12652 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12653 for (; I != E; ++I) { 12654 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12655 if (getBasePtrIndex(M) == I.getOperandNo()) 12656 return true; 12657 } 12658 } 12659 return false; 12660 } 12661 12662 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12663 SDValue N1) const { 12664 if (!N0.hasOneUse()) 12665 return false; 12666 // Take care of the opportunity to keep N0 uniform 12667 if (N0->isDivergent() || !N1->isDivergent()) 12668 return true; 12669 // Check if we have a good chance to form the memory access pattern with the 12670 // base and offset 12671 return (DAG.isBaseWithConstantOffset(N0) && 12672 hasMemSDNodeUser(*N0->use_begin())); 12673 } 12674 12675 MachineMemOperand::Flags 12676 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12677 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12678 if (I.getMetadata("amdgpu.noclobber")) 12679 return MONoClobber; 12680 return MachineMemOperand::MONone; 12681 } 12682