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() && 1522 !Subtarget->hasLDSMisalignedBug()) { 1523 if (IsFast) 1524 *IsFast = Alignment != Align(2); 1525 return true; 1526 } 1527 1528 // Either, the alignment requirements are "enabled", or there is an 1529 // unaligned LDS access related hardware bug though alignment requirements 1530 // are "disabled". In either case, we need to check for proper alignment 1531 // requirements. 1532 // 1533 if (Size == 64) { 1534 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1535 // address is negative, then the instruction is incorrectly treated as 1536 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1537 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1538 // load later in the SILoadStoreOptimizer. 1539 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1540 return false; 1541 1542 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1543 // can do a 4 byte aligned, 8 byte access in a single operation using 1544 // ds_read2/write2_b32 with adjacent offsets. 1545 bool AlignedBy4 = Alignment >= Align(4); 1546 if (IsFast) 1547 *IsFast = AlignedBy4; 1548 1549 return AlignedBy4; 1550 } 1551 if (Size == 96) { 1552 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1553 // gfx8 and older. 1554 bool AlignedBy16 = Alignment >= Align(16); 1555 if (IsFast) 1556 *IsFast = AlignedBy16; 1557 1558 return AlignedBy16; 1559 } 1560 if (Size == 128) { 1561 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1562 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1563 // single operation using ds_read2/write2_b64. 1564 bool AlignedBy8 = Alignment >= Align(8); 1565 if (IsFast) 1566 *IsFast = AlignedBy8; 1567 1568 return AlignedBy8; 1569 } 1570 } 1571 1572 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1573 bool AlignedBy4 = Alignment >= Align(4); 1574 if (IsFast) 1575 *IsFast = AlignedBy4; 1576 1577 return AlignedBy4 || 1578 Subtarget->enableFlatScratch() || 1579 Subtarget->hasUnalignedScratchAccess(); 1580 } 1581 1582 // FIXME: We have to be conservative here and assume that flat operations 1583 // will access scratch. If we had access to the IR function, then we 1584 // could determine if any private memory was used in the function. 1585 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1586 !Subtarget->hasUnalignedScratchAccess()) { 1587 bool AlignedBy4 = Alignment >= Align(4); 1588 if (IsFast) 1589 *IsFast = AlignedBy4; 1590 1591 return AlignedBy4; 1592 } 1593 1594 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1595 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1596 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1597 // If we have a uniform constant load, it still requires using a slow 1598 // buffer instruction if unaligned. 1599 if (IsFast) { 1600 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1601 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1602 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1603 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1604 Alignment >= Align(4) : Alignment != Align(2); 1605 } 1606 1607 return true; 1608 } 1609 1610 // Smaller than dword value must be aligned. 1611 if (Size < 32) 1612 return false; 1613 1614 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1615 // byte-address are ignored, thus forcing Dword alignment. 1616 // This applies to private, global, and constant memory. 1617 if (IsFast) 1618 *IsFast = true; 1619 1620 return Size >= 32 && Alignment >= Align(4); 1621 } 1622 1623 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1624 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1625 bool *IsFast) const { 1626 if (IsFast) 1627 *IsFast = false; 1628 1629 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1630 // which isn't a simple VT. 1631 // Until MVT is extended to handle this, simply check for the size and 1632 // rely on the condition below: allow accesses if the size is a multiple of 4. 1633 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1634 VT.getStoreSize() > 16)) { 1635 return false; 1636 } 1637 1638 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1639 Alignment, Flags, IsFast); 1640 } 1641 1642 EVT SITargetLowering::getOptimalMemOpType( 1643 const MemOp &Op, const AttributeList &FuncAttributes) const { 1644 // FIXME: Should account for address space here. 1645 1646 // The default fallback uses the private pointer size as a guess for a type to 1647 // use. Make sure we switch these to 64-bit accesses. 1648 1649 if (Op.size() >= 16 && 1650 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1651 return MVT::v4i32; 1652 1653 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1654 return MVT::v2i32; 1655 1656 // Use the default. 1657 return MVT::Other; 1658 } 1659 1660 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1661 const MemSDNode *MemNode = cast<MemSDNode>(N); 1662 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1663 } 1664 1665 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1666 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1667 AS == AMDGPUAS::PRIVATE_ADDRESS; 1668 } 1669 1670 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1671 unsigned DestAS) const { 1672 // Flat -> private/local is a simple truncate. 1673 // Flat -> global is no-op 1674 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1675 return true; 1676 1677 const GCNTargetMachine &TM = 1678 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1679 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1680 } 1681 1682 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1683 const MemSDNode *MemNode = cast<MemSDNode>(N); 1684 1685 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1686 } 1687 1688 TargetLoweringBase::LegalizeTypeAction 1689 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1690 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1691 VT.getScalarType().bitsLE(MVT::i16)) 1692 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1693 return TargetLoweringBase::getPreferredVectorAction(VT); 1694 } 1695 1696 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1697 Type *Ty) const { 1698 // FIXME: Could be smarter if called for vector constants. 1699 return true; 1700 } 1701 1702 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1703 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1704 switch (Op) { 1705 case ISD::LOAD: 1706 case ISD::STORE: 1707 1708 // These operations are done with 32-bit instructions anyway. 1709 case ISD::AND: 1710 case ISD::OR: 1711 case ISD::XOR: 1712 case ISD::SELECT: 1713 // TODO: Extensions? 1714 return true; 1715 default: 1716 return false; 1717 } 1718 } 1719 1720 // SimplifySetCC uses this function to determine whether or not it should 1721 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1722 if (VT == MVT::i1 && Op == ISD::SETCC) 1723 return false; 1724 1725 return TargetLowering::isTypeDesirableForOp(Op, VT); 1726 } 1727 1728 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1729 const SDLoc &SL, 1730 SDValue Chain, 1731 uint64_t Offset) const { 1732 const DataLayout &DL = DAG.getDataLayout(); 1733 MachineFunction &MF = DAG.getMachineFunction(); 1734 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1735 1736 const ArgDescriptor *InputPtrReg; 1737 const TargetRegisterClass *RC; 1738 LLT ArgTy; 1739 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1740 1741 std::tie(InputPtrReg, RC, ArgTy) = 1742 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1743 1744 // We may not have the kernarg segment argument if we have no kernel 1745 // arguments. 1746 if (!InputPtrReg) 1747 return DAG.getConstant(0, SL, PtrVT); 1748 1749 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1750 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1751 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1752 1753 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1754 } 1755 1756 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1757 const SDLoc &SL) const { 1758 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1759 FIRST_IMPLICIT); 1760 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1761 } 1762 1763 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1764 const SDLoc &SL, SDValue Val, 1765 bool Signed, 1766 const ISD::InputArg *Arg) const { 1767 // First, if it is a widened vector, narrow it. 1768 if (VT.isVector() && 1769 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1770 EVT NarrowedVT = 1771 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1772 VT.getVectorNumElements()); 1773 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1774 DAG.getConstant(0, SL, MVT::i32)); 1775 } 1776 1777 // Then convert the vector elements or scalar value. 1778 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1779 VT.bitsLT(MemVT)) { 1780 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1781 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1782 } 1783 1784 if (MemVT.isFloatingPoint()) 1785 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1786 else if (Signed) 1787 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1788 else 1789 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1790 1791 return Val; 1792 } 1793 1794 SDValue SITargetLowering::lowerKernargMemParameter( 1795 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1796 uint64_t Offset, Align Alignment, bool Signed, 1797 const ISD::InputArg *Arg) const { 1798 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1799 1800 // Try to avoid using an extload by loading earlier than the argument address, 1801 // and extracting the relevant bits. The load should hopefully be merged with 1802 // the previous argument. 1803 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1804 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1805 int64_t AlignDownOffset = alignDown(Offset, 4); 1806 int64_t OffsetDiff = Offset - AlignDownOffset; 1807 1808 EVT IntVT = MemVT.changeTypeToInteger(); 1809 1810 // TODO: If we passed in the base kernel offset we could have a better 1811 // alignment than 4, but we don't really need it. 1812 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1813 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1814 MachineMemOperand::MODereferenceable | 1815 MachineMemOperand::MOInvariant); 1816 1817 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1818 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1819 1820 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1821 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1822 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1823 1824 1825 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1826 } 1827 1828 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1829 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1830 MachineMemOperand::MODereferenceable | 1831 MachineMemOperand::MOInvariant); 1832 1833 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1834 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1835 } 1836 1837 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1838 const SDLoc &SL, SDValue Chain, 1839 const ISD::InputArg &Arg) const { 1840 MachineFunction &MF = DAG.getMachineFunction(); 1841 MachineFrameInfo &MFI = MF.getFrameInfo(); 1842 1843 if (Arg.Flags.isByVal()) { 1844 unsigned Size = Arg.Flags.getByValSize(); 1845 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1846 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1847 } 1848 1849 unsigned ArgOffset = VA.getLocMemOffset(); 1850 unsigned ArgSize = VA.getValVT().getStoreSize(); 1851 1852 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1853 1854 // Create load nodes to retrieve arguments from the stack. 1855 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1856 SDValue ArgValue; 1857 1858 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1859 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1860 MVT MemVT = VA.getValVT(); 1861 1862 switch (VA.getLocInfo()) { 1863 default: 1864 break; 1865 case CCValAssign::BCvt: 1866 MemVT = VA.getLocVT(); 1867 break; 1868 case CCValAssign::SExt: 1869 ExtType = ISD::SEXTLOAD; 1870 break; 1871 case CCValAssign::ZExt: 1872 ExtType = ISD::ZEXTLOAD; 1873 break; 1874 case CCValAssign::AExt: 1875 ExtType = ISD::EXTLOAD; 1876 break; 1877 } 1878 1879 ArgValue = DAG.getExtLoad( 1880 ExtType, SL, VA.getLocVT(), Chain, FIN, 1881 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1882 MemVT); 1883 return ArgValue; 1884 } 1885 1886 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1887 const SIMachineFunctionInfo &MFI, 1888 EVT VT, 1889 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1890 const ArgDescriptor *Reg; 1891 const TargetRegisterClass *RC; 1892 LLT Ty; 1893 1894 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1895 if (!Reg) { 1896 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1897 // It's possible for a kernarg intrinsic call to appear in a kernel with 1898 // no allocated segment, in which case we do not add the user sgpr 1899 // argument, so just return null. 1900 return DAG.getConstant(0, SDLoc(), VT); 1901 } 1902 1903 // It's undefined behavior if a function marked with the amdgpu-no-* 1904 // attributes uses the corresponding intrinsic. 1905 return DAG.getUNDEF(VT); 1906 } 1907 1908 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1909 } 1910 1911 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1912 CallingConv::ID CallConv, 1913 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1914 FunctionType *FType, 1915 SIMachineFunctionInfo *Info) { 1916 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1917 const ISD::InputArg *Arg = &Ins[I]; 1918 1919 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1920 "vector type argument should have been split"); 1921 1922 // First check if it's a PS input addr. 1923 if (CallConv == CallingConv::AMDGPU_PS && 1924 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1925 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1926 1927 // Inconveniently only the first part of the split is marked as isSplit, 1928 // so skip to the end. We only want to increment PSInputNum once for the 1929 // entire split argument. 1930 if (Arg->Flags.isSplit()) { 1931 while (!Arg->Flags.isSplitEnd()) { 1932 assert((!Arg->VT.isVector() || 1933 Arg->VT.getScalarSizeInBits() == 16) && 1934 "unexpected vector split in ps argument type"); 1935 if (!SkipArg) 1936 Splits.push_back(*Arg); 1937 Arg = &Ins[++I]; 1938 } 1939 } 1940 1941 if (SkipArg) { 1942 // We can safely skip PS inputs. 1943 Skipped.set(Arg->getOrigArgIndex()); 1944 ++PSInputNum; 1945 continue; 1946 } 1947 1948 Info->markPSInputAllocated(PSInputNum); 1949 if (Arg->Used) 1950 Info->markPSInputEnabled(PSInputNum); 1951 1952 ++PSInputNum; 1953 } 1954 1955 Splits.push_back(*Arg); 1956 } 1957 } 1958 1959 // Allocate special inputs passed in VGPRs. 1960 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1961 MachineFunction &MF, 1962 const SIRegisterInfo &TRI, 1963 SIMachineFunctionInfo &Info) const { 1964 const LLT S32 = LLT::scalar(32); 1965 MachineRegisterInfo &MRI = MF.getRegInfo(); 1966 1967 if (Info.hasWorkItemIDX()) { 1968 Register Reg = AMDGPU::VGPR0; 1969 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1970 1971 CCInfo.AllocateReg(Reg); 1972 unsigned Mask = (Subtarget->hasPackedTID() && 1973 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1974 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1975 } 1976 1977 if (Info.hasWorkItemIDY()) { 1978 assert(Info.hasWorkItemIDX()); 1979 if (Subtarget->hasPackedTID()) { 1980 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1981 0x3ff << 10)); 1982 } else { 1983 unsigned Reg = AMDGPU::VGPR1; 1984 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1985 1986 CCInfo.AllocateReg(Reg); 1987 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1988 } 1989 } 1990 1991 if (Info.hasWorkItemIDZ()) { 1992 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1993 if (Subtarget->hasPackedTID()) { 1994 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1995 0x3ff << 20)); 1996 } else { 1997 unsigned Reg = AMDGPU::VGPR2; 1998 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1999 2000 CCInfo.AllocateReg(Reg); 2001 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 2002 } 2003 } 2004 } 2005 2006 // Try to allocate a VGPR at the end of the argument list, or if no argument 2007 // VGPRs are left allocating a stack slot. 2008 // If \p Mask is is given it indicates bitfield position in the register. 2009 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2010 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2011 ArgDescriptor Arg = ArgDescriptor()) { 2012 if (Arg.isSet()) 2013 return ArgDescriptor::createArg(Arg, Mask); 2014 2015 ArrayRef<MCPhysReg> ArgVGPRs 2016 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2017 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2018 if (RegIdx == ArgVGPRs.size()) { 2019 // Spill to stack required. 2020 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2021 2022 return ArgDescriptor::createStack(Offset, Mask); 2023 } 2024 2025 unsigned Reg = ArgVGPRs[RegIdx]; 2026 Reg = CCInfo.AllocateReg(Reg); 2027 assert(Reg != AMDGPU::NoRegister); 2028 2029 MachineFunction &MF = CCInfo.getMachineFunction(); 2030 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2031 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2032 return ArgDescriptor::createRegister(Reg, Mask); 2033 } 2034 2035 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2036 const TargetRegisterClass *RC, 2037 unsigned NumArgRegs) { 2038 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2039 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2040 if (RegIdx == ArgSGPRs.size()) 2041 report_fatal_error("ran out of SGPRs for arguments"); 2042 2043 unsigned Reg = ArgSGPRs[RegIdx]; 2044 Reg = CCInfo.AllocateReg(Reg); 2045 assert(Reg != AMDGPU::NoRegister); 2046 2047 MachineFunction &MF = CCInfo.getMachineFunction(); 2048 MF.addLiveIn(Reg, RC); 2049 return ArgDescriptor::createRegister(Reg); 2050 } 2051 2052 // If this has a fixed position, we still should allocate the register in the 2053 // CCInfo state. Technically we could get away with this for values passed 2054 // outside of the normal argument range. 2055 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2056 const TargetRegisterClass *RC, 2057 MCRegister Reg) { 2058 Reg = CCInfo.AllocateReg(Reg); 2059 assert(Reg != AMDGPU::NoRegister); 2060 MachineFunction &MF = CCInfo.getMachineFunction(); 2061 MF.addLiveIn(Reg, RC); 2062 } 2063 2064 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2065 if (Arg) { 2066 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2067 Arg.getRegister()); 2068 } else 2069 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2070 } 2071 2072 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2073 if (Arg) { 2074 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2075 Arg.getRegister()); 2076 } else 2077 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2078 } 2079 2080 /// Allocate implicit function VGPR arguments at the end of allocated user 2081 /// arguments. 2082 void SITargetLowering::allocateSpecialInputVGPRs( 2083 CCState &CCInfo, MachineFunction &MF, 2084 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2085 const unsigned Mask = 0x3ff; 2086 ArgDescriptor Arg; 2087 2088 if (Info.hasWorkItemIDX()) { 2089 Arg = allocateVGPR32Input(CCInfo, Mask); 2090 Info.setWorkItemIDX(Arg); 2091 } 2092 2093 if (Info.hasWorkItemIDY()) { 2094 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2095 Info.setWorkItemIDY(Arg); 2096 } 2097 2098 if (Info.hasWorkItemIDZ()) 2099 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2100 } 2101 2102 /// Allocate implicit function VGPR arguments in fixed registers. 2103 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2104 CCState &CCInfo, MachineFunction &MF, 2105 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2106 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2107 if (!Reg) 2108 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2109 2110 const unsigned Mask = 0x3ff; 2111 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2112 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2113 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2114 } 2115 2116 void SITargetLowering::allocateSpecialInputSGPRs( 2117 CCState &CCInfo, 2118 MachineFunction &MF, 2119 const SIRegisterInfo &TRI, 2120 SIMachineFunctionInfo &Info) const { 2121 auto &ArgInfo = Info.getArgInfo(); 2122 2123 // TODO: Unify handling with private memory pointers. 2124 if (Info.hasDispatchPtr()) 2125 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2126 2127 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2128 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2129 2130 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2131 // constant offset from the kernarg segment. 2132 if (Info.hasImplicitArgPtr()) 2133 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2134 2135 if (Info.hasDispatchID()) 2136 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2137 2138 // flat_scratch_init is not applicable for non-kernel functions. 2139 2140 if (Info.hasWorkGroupIDX()) 2141 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2142 2143 if (Info.hasWorkGroupIDY()) 2144 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2145 2146 if (Info.hasWorkGroupIDZ()) 2147 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2148 } 2149 2150 // Allocate special inputs passed in user SGPRs. 2151 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2152 MachineFunction &MF, 2153 const SIRegisterInfo &TRI, 2154 SIMachineFunctionInfo &Info) const { 2155 if (Info.hasImplicitBufferPtr()) { 2156 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2157 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2158 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2159 } 2160 2161 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2162 if (Info.hasPrivateSegmentBuffer()) { 2163 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2164 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2165 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2166 } 2167 2168 if (Info.hasDispatchPtr()) { 2169 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2170 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2171 CCInfo.AllocateReg(DispatchPtrReg); 2172 } 2173 2174 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2175 Register QueuePtrReg = Info.addQueuePtr(TRI); 2176 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2177 CCInfo.AllocateReg(QueuePtrReg); 2178 } 2179 2180 if (Info.hasKernargSegmentPtr()) { 2181 MachineRegisterInfo &MRI = MF.getRegInfo(); 2182 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2183 CCInfo.AllocateReg(InputPtrReg); 2184 2185 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2186 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2187 } 2188 2189 if (Info.hasDispatchID()) { 2190 Register DispatchIDReg = Info.addDispatchID(TRI); 2191 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2192 CCInfo.AllocateReg(DispatchIDReg); 2193 } 2194 2195 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2196 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2197 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2198 CCInfo.AllocateReg(FlatScratchInitReg); 2199 } 2200 2201 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2202 // these from the dispatch pointer. 2203 } 2204 2205 // Allocate special input registers that are initialized per-wave. 2206 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2207 MachineFunction &MF, 2208 SIMachineFunctionInfo &Info, 2209 CallingConv::ID CallConv, 2210 bool IsShader) const { 2211 if (Info.hasWorkGroupIDX()) { 2212 Register Reg = Info.addWorkGroupIDX(); 2213 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2214 CCInfo.AllocateReg(Reg); 2215 } 2216 2217 if (Info.hasWorkGroupIDY()) { 2218 Register Reg = Info.addWorkGroupIDY(); 2219 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2220 CCInfo.AllocateReg(Reg); 2221 } 2222 2223 if (Info.hasWorkGroupIDZ()) { 2224 Register Reg = Info.addWorkGroupIDZ(); 2225 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2226 CCInfo.AllocateReg(Reg); 2227 } 2228 2229 if (Info.hasWorkGroupInfo()) { 2230 Register Reg = Info.addWorkGroupInfo(); 2231 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2232 CCInfo.AllocateReg(Reg); 2233 } 2234 2235 if (Info.hasPrivateSegmentWaveByteOffset()) { 2236 // Scratch wave offset passed in system SGPR. 2237 unsigned PrivateSegmentWaveByteOffsetReg; 2238 2239 if (IsShader) { 2240 PrivateSegmentWaveByteOffsetReg = 2241 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2242 2243 // This is true if the scratch wave byte offset doesn't have a fixed 2244 // location. 2245 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2246 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2247 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2248 } 2249 } else 2250 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2251 2252 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2253 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2254 } 2255 } 2256 2257 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2258 MachineFunction &MF, 2259 const SIRegisterInfo &TRI, 2260 SIMachineFunctionInfo &Info) { 2261 // Now that we've figured out where the scratch register inputs are, see if 2262 // should reserve the arguments and use them directly. 2263 MachineFrameInfo &MFI = MF.getFrameInfo(); 2264 bool HasStackObjects = MFI.hasStackObjects(); 2265 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2266 2267 // Record that we know we have non-spill stack objects so we don't need to 2268 // check all stack objects later. 2269 if (HasStackObjects) 2270 Info.setHasNonSpillStackObjects(true); 2271 2272 // Everything live out of a block is spilled with fast regalloc, so it's 2273 // almost certain that spilling will be required. 2274 if (TM.getOptLevel() == CodeGenOpt::None) 2275 HasStackObjects = true; 2276 2277 // For now assume stack access is needed in any callee functions, so we need 2278 // the scratch registers to pass in. 2279 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2280 2281 if (!ST.enableFlatScratch()) { 2282 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2283 // If we have stack objects, we unquestionably need the private buffer 2284 // resource. For the Code Object V2 ABI, this will be the first 4 user 2285 // SGPR inputs. We can reserve those and use them directly. 2286 2287 Register PrivateSegmentBufferReg = 2288 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2289 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2290 } else { 2291 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2292 // We tentatively reserve the last registers (skipping the last registers 2293 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2294 // we'll replace these with the ones immediately after those which were 2295 // really allocated. In the prologue copies will be inserted from the 2296 // argument to these reserved registers. 2297 2298 // Without HSA, relocations are used for the scratch pointer and the 2299 // buffer resource setup is always inserted in the prologue. Scratch wave 2300 // offset is still in an input SGPR. 2301 Info.setScratchRSrcReg(ReservedBufferReg); 2302 } 2303 } 2304 2305 MachineRegisterInfo &MRI = MF.getRegInfo(); 2306 2307 // For entry functions we have to set up the stack pointer if we use it, 2308 // whereas non-entry functions get this "for free". This means there is no 2309 // intrinsic advantage to using S32 over S34 in cases where we do not have 2310 // calls but do need a frame pointer (i.e. if we are requested to have one 2311 // because frame pointer elimination is disabled). To keep things simple we 2312 // only ever use S32 as the call ABI stack pointer, and so using it does not 2313 // imply we need a separate frame pointer. 2314 // 2315 // Try to use s32 as the SP, but move it if it would interfere with input 2316 // arguments. This won't work with calls though. 2317 // 2318 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2319 // registers. 2320 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2321 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2322 } else { 2323 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2324 2325 if (MFI.hasCalls()) 2326 report_fatal_error("call in graphics shader with too many input SGPRs"); 2327 2328 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2329 if (!MRI.isLiveIn(Reg)) { 2330 Info.setStackPtrOffsetReg(Reg); 2331 break; 2332 } 2333 } 2334 2335 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2336 report_fatal_error("failed to find register for SP"); 2337 } 2338 2339 // hasFP should be accurate for entry functions even before the frame is 2340 // finalized, because it does not rely on the known stack size, only 2341 // properties like whether variable sized objects are present. 2342 if (ST.getFrameLowering()->hasFP(MF)) { 2343 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2344 } 2345 } 2346 2347 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2348 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2349 return !Info->isEntryFunction(); 2350 } 2351 2352 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2353 2354 } 2355 2356 void SITargetLowering::insertCopiesSplitCSR( 2357 MachineBasicBlock *Entry, 2358 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2359 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2360 2361 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2362 if (!IStart) 2363 return; 2364 2365 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2366 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2367 MachineBasicBlock::iterator MBBI = Entry->begin(); 2368 for (const MCPhysReg *I = IStart; *I; ++I) { 2369 const TargetRegisterClass *RC = nullptr; 2370 if (AMDGPU::SReg_64RegClass.contains(*I)) 2371 RC = &AMDGPU::SGPR_64RegClass; 2372 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2373 RC = &AMDGPU::SGPR_32RegClass; 2374 else 2375 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2376 2377 Register NewVR = MRI->createVirtualRegister(RC); 2378 // Create copy from CSR to a virtual register. 2379 Entry->addLiveIn(*I); 2380 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2381 .addReg(*I); 2382 2383 // Insert the copy-back instructions right before the terminator. 2384 for (auto *Exit : Exits) 2385 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2386 TII->get(TargetOpcode::COPY), *I) 2387 .addReg(NewVR); 2388 } 2389 } 2390 2391 SDValue SITargetLowering::LowerFormalArguments( 2392 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2393 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2394 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2395 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2396 2397 MachineFunction &MF = DAG.getMachineFunction(); 2398 const Function &Fn = MF.getFunction(); 2399 FunctionType *FType = MF.getFunction().getFunctionType(); 2400 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2401 2402 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2403 DiagnosticInfoUnsupported NoGraphicsHSA( 2404 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2405 DAG.getContext()->diagnose(NoGraphicsHSA); 2406 return DAG.getEntryNode(); 2407 } 2408 2409 Info->allocateModuleLDSGlobal(Fn.getParent()); 2410 2411 SmallVector<ISD::InputArg, 16> Splits; 2412 SmallVector<CCValAssign, 16> ArgLocs; 2413 BitVector Skipped(Ins.size()); 2414 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2415 *DAG.getContext()); 2416 2417 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2418 bool IsKernel = AMDGPU::isKernel(CallConv); 2419 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2420 2421 if (IsGraphics) { 2422 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2423 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2424 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2425 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2426 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2427 !Info->hasWorkItemIDZ()); 2428 } 2429 2430 if (CallConv == CallingConv::AMDGPU_PS) { 2431 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2432 2433 // At least one interpolation mode must be enabled or else the GPU will 2434 // hang. 2435 // 2436 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2437 // set PSInputAddr, the user wants to enable some bits after the compilation 2438 // based on run-time states. Since we can't know what the final PSInputEna 2439 // will look like, so we shouldn't do anything here and the user should take 2440 // responsibility for the correct programming. 2441 // 2442 // Otherwise, the following restrictions apply: 2443 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2444 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2445 // enabled too. 2446 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2447 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2448 CCInfo.AllocateReg(AMDGPU::VGPR0); 2449 CCInfo.AllocateReg(AMDGPU::VGPR1); 2450 Info->markPSInputAllocated(0); 2451 Info->markPSInputEnabled(0); 2452 } 2453 if (Subtarget->isAmdPalOS()) { 2454 // For isAmdPalOS, the user does not enable some bits after compilation 2455 // based on run-time states; the register values being generated here are 2456 // the final ones set in hardware. Therefore we need to apply the 2457 // workaround to PSInputAddr and PSInputEnable together. (The case where 2458 // a bit is set in PSInputAddr but not PSInputEnable is where the 2459 // frontend set up an input arg for a particular interpolation mode, but 2460 // nothing uses that input arg. Really we should have an earlier pass 2461 // that removes such an arg.) 2462 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2463 if ((PsInputBits & 0x7F) == 0 || 2464 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2465 Info->markPSInputEnabled( 2466 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2467 } 2468 } else if (IsKernel) { 2469 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2470 } else { 2471 Splits.append(Ins.begin(), Ins.end()); 2472 } 2473 2474 if (IsEntryFunc) { 2475 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2476 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2477 } else if (!IsGraphics) { 2478 // For the fixed ABI, pass workitem IDs in the last argument register. 2479 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2480 } 2481 2482 if (IsKernel) { 2483 analyzeFormalArgumentsCompute(CCInfo, Ins); 2484 } else { 2485 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2486 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2487 } 2488 2489 SmallVector<SDValue, 16> Chains; 2490 2491 // FIXME: This is the minimum kernel argument alignment. We should improve 2492 // this to the maximum alignment of the arguments. 2493 // 2494 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2495 // kern arg offset. 2496 const Align KernelArgBaseAlign = Align(16); 2497 2498 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2499 const ISD::InputArg &Arg = Ins[i]; 2500 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2501 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2502 continue; 2503 } 2504 2505 CCValAssign &VA = ArgLocs[ArgIdx++]; 2506 MVT VT = VA.getLocVT(); 2507 2508 if (IsEntryFunc && VA.isMemLoc()) { 2509 VT = Ins[i].VT; 2510 EVT MemVT = VA.getLocVT(); 2511 2512 const uint64_t Offset = VA.getLocMemOffset(); 2513 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2514 2515 if (Arg.Flags.isByRef()) { 2516 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2517 2518 const GCNTargetMachine &TM = 2519 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2520 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2521 Arg.Flags.getPointerAddrSpace())) { 2522 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2523 Arg.Flags.getPointerAddrSpace()); 2524 } 2525 2526 InVals.push_back(Ptr); 2527 continue; 2528 } 2529 2530 SDValue Arg = lowerKernargMemParameter( 2531 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2532 Chains.push_back(Arg.getValue(1)); 2533 2534 auto *ParamTy = 2535 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2536 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2537 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2538 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2539 // On SI local pointers are just offsets into LDS, so they are always 2540 // less than 16-bits. On CI and newer they could potentially be 2541 // real pointers, so we can't guarantee their size. 2542 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2543 DAG.getValueType(MVT::i16)); 2544 } 2545 2546 InVals.push_back(Arg); 2547 continue; 2548 } else if (!IsEntryFunc && VA.isMemLoc()) { 2549 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2550 InVals.push_back(Val); 2551 if (!Arg.Flags.isByVal()) 2552 Chains.push_back(Val.getValue(1)); 2553 continue; 2554 } 2555 2556 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2557 2558 Register Reg = VA.getLocReg(); 2559 const TargetRegisterClass *RC = nullptr; 2560 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2561 RC = &AMDGPU::VGPR_32RegClass; 2562 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2563 RC = &AMDGPU::SGPR_32RegClass; 2564 else 2565 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2566 EVT ValVT = VA.getValVT(); 2567 2568 Reg = MF.addLiveIn(Reg, RC); 2569 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2570 2571 if (Arg.Flags.isSRet()) { 2572 // The return object should be reasonably addressable. 2573 2574 // FIXME: This helps when the return is a real sret. If it is a 2575 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2576 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2577 unsigned NumBits 2578 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2579 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2580 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2581 } 2582 2583 // If this is an 8 or 16-bit value, it is really passed promoted 2584 // to 32 bits. Insert an assert[sz]ext to capture this, then 2585 // truncate to the right size. 2586 switch (VA.getLocInfo()) { 2587 case CCValAssign::Full: 2588 break; 2589 case CCValAssign::BCvt: 2590 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2591 break; 2592 case CCValAssign::SExt: 2593 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2594 DAG.getValueType(ValVT)); 2595 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2596 break; 2597 case CCValAssign::ZExt: 2598 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2599 DAG.getValueType(ValVT)); 2600 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2601 break; 2602 case CCValAssign::AExt: 2603 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2604 break; 2605 default: 2606 llvm_unreachable("Unknown loc info!"); 2607 } 2608 2609 InVals.push_back(Val); 2610 } 2611 2612 // Start adding system SGPRs. 2613 if (IsEntryFunc) { 2614 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2615 } else { 2616 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2617 if (!IsGraphics) 2618 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2619 } 2620 2621 auto &ArgUsageInfo = 2622 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2623 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2624 2625 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2626 Info->setBytesInStackArgArea(StackArgSize); 2627 2628 return Chains.empty() ? Chain : 2629 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2630 } 2631 2632 // TODO: If return values can't fit in registers, we should return as many as 2633 // possible in registers before passing on stack. 2634 bool SITargetLowering::CanLowerReturn( 2635 CallingConv::ID CallConv, 2636 MachineFunction &MF, bool IsVarArg, 2637 const SmallVectorImpl<ISD::OutputArg> &Outs, 2638 LLVMContext &Context) const { 2639 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2640 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2641 // for shaders. Vector types should be explicitly handled by CC. 2642 if (AMDGPU::isEntryFunctionCC(CallConv)) 2643 return true; 2644 2645 SmallVector<CCValAssign, 16> RVLocs; 2646 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2647 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2648 } 2649 2650 SDValue 2651 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2652 bool isVarArg, 2653 const SmallVectorImpl<ISD::OutputArg> &Outs, 2654 const SmallVectorImpl<SDValue> &OutVals, 2655 const SDLoc &DL, SelectionDAG &DAG) const { 2656 MachineFunction &MF = DAG.getMachineFunction(); 2657 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2658 2659 if (AMDGPU::isKernel(CallConv)) { 2660 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2661 OutVals, DL, DAG); 2662 } 2663 2664 bool IsShader = AMDGPU::isShader(CallConv); 2665 2666 Info->setIfReturnsVoid(Outs.empty()); 2667 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2668 2669 // CCValAssign - represent the assignment of the return value to a location. 2670 SmallVector<CCValAssign, 48> RVLocs; 2671 SmallVector<ISD::OutputArg, 48> Splits; 2672 2673 // CCState - Info about the registers and stack slots. 2674 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2675 *DAG.getContext()); 2676 2677 // Analyze outgoing return values. 2678 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2679 2680 SDValue Flag; 2681 SmallVector<SDValue, 48> RetOps; 2682 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2683 2684 // Copy the result values into the output registers. 2685 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2686 ++I, ++RealRVLocIdx) { 2687 CCValAssign &VA = RVLocs[I]; 2688 assert(VA.isRegLoc() && "Can only return in registers!"); 2689 // TODO: Partially return in registers if return values don't fit. 2690 SDValue Arg = OutVals[RealRVLocIdx]; 2691 2692 // Copied from other backends. 2693 switch (VA.getLocInfo()) { 2694 case CCValAssign::Full: 2695 break; 2696 case CCValAssign::BCvt: 2697 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2698 break; 2699 case CCValAssign::SExt: 2700 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2701 break; 2702 case CCValAssign::ZExt: 2703 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2704 break; 2705 case CCValAssign::AExt: 2706 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2707 break; 2708 default: 2709 llvm_unreachable("Unknown loc info!"); 2710 } 2711 2712 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2713 Flag = Chain.getValue(1); 2714 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2715 } 2716 2717 // FIXME: Does sret work properly? 2718 if (!Info->isEntryFunction()) { 2719 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2720 const MCPhysReg *I = 2721 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2722 if (I) { 2723 for (; *I; ++I) { 2724 if (AMDGPU::SReg_64RegClass.contains(*I)) 2725 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2726 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2727 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2728 else 2729 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2730 } 2731 } 2732 } 2733 2734 // Update chain and glue. 2735 RetOps[0] = Chain; 2736 if (Flag.getNode()) 2737 RetOps.push_back(Flag); 2738 2739 unsigned Opc = AMDGPUISD::ENDPGM; 2740 if (!IsWaveEnd) 2741 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2742 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2743 } 2744 2745 SDValue SITargetLowering::LowerCallResult( 2746 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2747 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2748 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2749 SDValue ThisVal) const { 2750 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2751 2752 // Assign locations to each value returned by this call. 2753 SmallVector<CCValAssign, 16> RVLocs; 2754 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2755 *DAG.getContext()); 2756 CCInfo.AnalyzeCallResult(Ins, RetCC); 2757 2758 // Copy all of the result registers out of their specified physreg. 2759 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2760 CCValAssign VA = RVLocs[i]; 2761 SDValue Val; 2762 2763 if (VA.isRegLoc()) { 2764 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2765 Chain = Val.getValue(1); 2766 InFlag = Val.getValue(2); 2767 } else if (VA.isMemLoc()) { 2768 report_fatal_error("TODO: return values in memory"); 2769 } else 2770 llvm_unreachable("unknown argument location type"); 2771 2772 switch (VA.getLocInfo()) { 2773 case CCValAssign::Full: 2774 break; 2775 case CCValAssign::BCvt: 2776 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2777 break; 2778 case CCValAssign::ZExt: 2779 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2780 DAG.getValueType(VA.getValVT())); 2781 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2782 break; 2783 case CCValAssign::SExt: 2784 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2785 DAG.getValueType(VA.getValVT())); 2786 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2787 break; 2788 case CCValAssign::AExt: 2789 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2790 break; 2791 default: 2792 llvm_unreachable("Unknown loc info!"); 2793 } 2794 2795 InVals.push_back(Val); 2796 } 2797 2798 return Chain; 2799 } 2800 2801 // Add code to pass special inputs required depending on used features separate 2802 // from the explicit user arguments present in the IR. 2803 void SITargetLowering::passSpecialInputs( 2804 CallLoweringInfo &CLI, 2805 CCState &CCInfo, 2806 const SIMachineFunctionInfo &Info, 2807 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2808 SmallVectorImpl<SDValue> &MemOpChains, 2809 SDValue Chain) const { 2810 // If we don't have a call site, this was a call inserted by 2811 // legalization. These can never use special inputs. 2812 if (!CLI.CB) 2813 return; 2814 2815 SelectionDAG &DAG = CLI.DAG; 2816 const SDLoc &DL = CLI.DL; 2817 const Function &F = DAG.getMachineFunction().getFunction(); 2818 2819 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2820 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2821 2822 const AMDGPUFunctionArgInfo *CalleeArgInfo 2823 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2824 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2825 auto &ArgUsageInfo = 2826 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2827 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2828 } 2829 2830 // TODO: Unify with private memory register handling. This is complicated by 2831 // the fact that at least in kernels, the input argument is not necessarily 2832 // in the same location as the input. 2833 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2834 StringLiteral> ImplicitAttrs[] = { 2835 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2836 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2837 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2838 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2839 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2840 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2841 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2842 }; 2843 2844 for (auto Attr : ImplicitAttrs) { 2845 const ArgDescriptor *OutgoingArg; 2846 const TargetRegisterClass *ArgRC; 2847 LLT ArgTy; 2848 2849 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2850 2851 // If the callee does not use the attribute value, skip copying the value. 2852 if (CLI.CB->hasFnAttr(Attr.second)) 2853 continue; 2854 2855 std::tie(OutgoingArg, ArgRC, ArgTy) = 2856 CalleeArgInfo->getPreloadedValue(InputID); 2857 if (!OutgoingArg) 2858 continue; 2859 2860 const ArgDescriptor *IncomingArg; 2861 const TargetRegisterClass *IncomingArgRC; 2862 LLT Ty; 2863 std::tie(IncomingArg, IncomingArgRC, Ty) = 2864 CallerArgInfo.getPreloadedValue(InputID); 2865 assert(IncomingArgRC == ArgRC); 2866 2867 // All special arguments are ints for now. 2868 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2869 SDValue InputReg; 2870 2871 if (IncomingArg) { 2872 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2873 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2874 // The implicit arg ptr is special because it doesn't have a corresponding 2875 // input for kernels, and is computed from the kernarg segment pointer. 2876 InputReg = getImplicitArgPtr(DAG, DL); 2877 } else { 2878 // We may have proven the input wasn't needed, although the ABI is 2879 // requiring it. We just need to allocate the register appropriately. 2880 InputReg = DAG.getUNDEF(ArgVT); 2881 } 2882 2883 if (OutgoingArg->isRegister()) { 2884 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2885 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2886 report_fatal_error("failed to allocate implicit input argument"); 2887 } else { 2888 unsigned SpecialArgOffset = 2889 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2890 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2891 SpecialArgOffset); 2892 MemOpChains.push_back(ArgStore); 2893 } 2894 } 2895 2896 // Pack workitem IDs into a single register or pass it as is if already 2897 // packed. 2898 const ArgDescriptor *OutgoingArg; 2899 const TargetRegisterClass *ArgRC; 2900 LLT Ty; 2901 2902 std::tie(OutgoingArg, ArgRC, Ty) = 2903 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2904 if (!OutgoingArg) 2905 std::tie(OutgoingArg, ArgRC, Ty) = 2906 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2907 if (!OutgoingArg) 2908 std::tie(OutgoingArg, ArgRC, Ty) = 2909 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2910 if (!OutgoingArg) 2911 return; 2912 2913 const ArgDescriptor *IncomingArgX = std::get<0>( 2914 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2915 const ArgDescriptor *IncomingArgY = std::get<0>( 2916 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2917 const ArgDescriptor *IncomingArgZ = std::get<0>( 2918 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2919 2920 SDValue InputReg; 2921 SDLoc SL; 2922 2923 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2924 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2925 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2926 2927 // If incoming ids are not packed we need to pack them. 2928 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2929 NeedWorkItemIDX) { 2930 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2931 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2932 } else { 2933 InputReg = DAG.getConstant(0, DL, MVT::i32); 2934 } 2935 } 2936 2937 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2938 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2939 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2940 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2941 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2942 InputReg = InputReg.getNode() ? 2943 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2944 } 2945 2946 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2947 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2948 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2949 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2950 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2951 InputReg = InputReg.getNode() ? 2952 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2953 } 2954 2955 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2956 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2957 // We're in a situation where the outgoing function requires the workitem 2958 // ID, but the calling function does not have it (e.g a graphics function 2959 // calling a C calling convention function). This is illegal, but we need 2960 // to produce something. 2961 InputReg = DAG.getUNDEF(MVT::i32); 2962 } else { 2963 // Workitem ids are already packed, any of present incoming arguments 2964 // will carry all required fields. 2965 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2966 IncomingArgX ? *IncomingArgX : 2967 IncomingArgY ? *IncomingArgY : 2968 *IncomingArgZ, ~0u); 2969 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2970 } 2971 } 2972 2973 if (OutgoingArg->isRegister()) { 2974 if (InputReg) 2975 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2976 2977 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2978 } else { 2979 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2980 if (InputReg) { 2981 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2982 SpecialArgOffset); 2983 MemOpChains.push_back(ArgStore); 2984 } 2985 } 2986 } 2987 2988 static bool canGuaranteeTCO(CallingConv::ID CC) { 2989 return CC == CallingConv::Fast; 2990 } 2991 2992 /// Return true if we might ever do TCO for calls with this calling convention. 2993 static bool mayTailCallThisCC(CallingConv::ID CC) { 2994 switch (CC) { 2995 case CallingConv::C: 2996 case CallingConv::AMDGPU_Gfx: 2997 return true; 2998 default: 2999 return canGuaranteeTCO(CC); 3000 } 3001 } 3002 3003 bool SITargetLowering::isEligibleForTailCallOptimization( 3004 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 3005 const SmallVectorImpl<ISD::OutputArg> &Outs, 3006 const SmallVectorImpl<SDValue> &OutVals, 3007 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3008 if (!mayTailCallThisCC(CalleeCC)) 3009 return false; 3010 3011 // For a divergent call target, we need to do a waterfall loop over the 3012 // possible callees which precludes us from using a simple jump. 3013 if (Callee->isDivergent()) 3014 return false; 3015 3016 MachineFunction &MF = DAG.getMachineFunction(); 3017 const Function &CallerF = MF.getFunction(); 3018 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3019 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3020 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3021 3022 // Kernels aren't callable, and don't have a live in return address so it 3023 // doesn't make sense to do a tail call with entry functions. 3024 if (!CallerPreserved) 3025 return false; 3026 3027 bool CCMatch = CallerCC == CalleeCC; 3028 3029 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3030 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3031 return true; 3032 return false; 3033 } 3034 3035 // TODO: Can we handle var args? 3036 if (IsVarArg) 3037 return false; 3038 3039 for (const Argument &Arg : CallerF.args()) { 3040 if (Arg.hasByValAttr()) 3041 return false; 3042 } 3043 3044 LLVMContext &Ctx = *DAG.getContext(); 3045 3046 // Check that the call results are passed in the same way. 3047 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3048 CCAssignFnForCall(CalleeCC, IsVarArg), 3049 CCAssignFnForCall(CallerCC, IsVarArg))) 3050 return false; 3051 3052 // The callee has to preserve all registers the caller needs to preserve. 3053 if (!CCMatch) { 3054 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3055 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3056 return false; 3057 } 3058 3059 // Nothing more to check if the callee is taking no arguments. 3060 if (Outs.empty()) 3061 return true; 3062 3063 SmallVector<CCValAssign, 16> ArgLocs; 3064 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3065 3066 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3067 3068 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3069 // If the stack arguments for this call do not fit into our own save area then 3070 // the call cannot be made tail. 3071 // TODO: Is this really necessary? 3072 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3073 return false; 3074 3075 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3076 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3077 } 3078 3079 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3080 if (!CI->isTailCall()) 3081 return false; 3082 3083 const Function *ParentFn = CI->getParent()->getParent(); 3084 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3085 return false; 3086 return true; 3087 } 3088 3089 // The wave scratch offset register is used as the global base pointer. 3090 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3091 SmallVectorImpl<SDValue> &InVals) const { 3092 SelectionDAG &DAG = CLI.DAG; 3093 const SDLoc &DL = CLI.DL; 3094 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3095 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3096 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3097 SDValue Chain = CLI.Chain; 3098 SDValue Callee = CLI.Callee; 3099 bool &IsTailCall = CLI.IsTailCall; 3100 CallingConv::ID CallConv = CLI.CallConv; 3101 bool IsVarArg = CLI.IsVarArg; 3102 bool IsSibCall = false; 3103 bool IsThisReturn = false; 3104 MachineFunction &MF = DAG.getMachineFunction(); 3105 3106 if (Callee.isUndef() || isNullConstant(Callee)) { 3107 if (!CLI.IsTailCall) { 3108 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3109 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3110 } 3111 3112 return Chain; 3113 } 3114 3115 if (IsVarArg) { 3116 return lowerUnhandledCall(CLI, InVals, 3117 "unsupported call to variadic function "); 3118 } 3119 3120 if (!CLI.CB) 3121 report_fatal_error("unsupported libcall legalization"); 3122 3123 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3124 return lowerUnhandledCall(CLI, InVals, 3125 "unsupported required tail call to function "); 3126 } 3127 3128 if (AMDGPU::isShader(CallConv)) { 3129 // Note the issue is with the CC of the called function, not of the call 3130 // itself. 3131 return lowerUnhandledCall(CLI, InVals, 3132 "unsupported call to a shader function "); 3133 } 3134 3135 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3136 CallConv != CallingConv::AMDGPU_Gfx) { 3137 // Only allow calls with specific calling conventions. 3138 return lowerUnhandledCall(CLI, InVals, 3139 "unsupported calling convention for call from " 3140 "graphics shader of function "); 3141 } 3142 3143 if (IsTailCall) { 3144 IsTailCall = isEligibleForTailCallOptimization( 3145 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3146 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3147 report_fatal_error("failed to perform tail call elimination on a call " 3148 "site marked musttail"); 3149 } 3150 3151 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3152 3153 // A sibling call is one where we're under the usual C ABI and not planning 3154 // to change that but can still do a tail call: 3155 if (!TailCallOpt && IsTailCall) 3156 IsSibCall = true; 3157 3158 if (IsTailCall) 3159 ++NumTailCalls; 3160 } 3161 3162 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3163 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3164 SmallVector<SDValue, 8> MemOpChains; 3165 3166 // Analyze operands of the call, assigning locations to each operand. 3167 SmallVector<CCValAssign, 16> ArgLocs; 3168 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3169 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3170 3171 if (CallConv != CallingConv::AMDGPU_Gfx) { 3172 // With a fixed ABI, allocate fixed registers before user arguments. 3173 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3174 } 3175 3176 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3177 3178 // Get a count of how many bytes are to be pushed on the stack. 3179 unsigned NumBytes = CCInfo.getNextStackOffset(); 3180 3181 if (IsSibCall) { 3182 // Since we're not changing the ABI to make this a tail call, the memory 3183 // operands are already available in the caller's incoming argument space. 3184 NumBytes = 0; 3185 } 3186 3187 // FPDiff is the byte offset of the call's argument area from the callee's. 3188 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3189 // by this amount for a tail call. In a sibling call it must be 0 because the 3190 // caller will deallocate the entire stack and the callee still expects its 3191 // arguments to begin at SP+0. Completely unused for non-tail calls. 3192 int32_t FPDiff = 0; 3193 MachineFrameInfo &MFI = MF.getFrameInfo(); 3194 3195 // Adjust the stack pointer for the new arguments... 3196 // These operations are automatically eliminated by the prolog/epilog pass 3197 if (!IsSibCall) { 3198 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3199 3200 if (!Subtarget->enableFlatScratch()) { 3201 SmallVector<SDValue, 4> CopyFromChains; 3202 3203 // In the HSA case, this should be an identity copy. 3204 SDValue ScratchRSrcReg 3205 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3206 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3207 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3208 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3209 } 3210 } 3211 3212 MVT PtrVT = MVT::i32; 3213 3214 // Walk the register/memloc assignments, inserting copies/loads. 3215 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3216 CCValAssign &VA = ArgLocs[i]; 3217 SDValue Arg = OutVals[i]; 3218 3219 // Promote the value if needed. 3220 switch (VA.getLocInfo()) { 3221 case CCValAssign::Full: 3222 break; 3223 case CCValAssign::BCvt: 3224 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3225 break; 3226 case CCValAssign::ZExt: 3227 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3228 break; 3229 case CCValAssign::SExt: 3230 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3231 break; 3232 case CCValAssign::AExt: 3233 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3234 break; 3235 case CCValAssign::FPExt: 3236 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3237 break; 3238 default: 3239 llvm_unreachable("Unknown loc info!"); 3240 } 3241 3242 if (VA.isRegLoc()) { 3243 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3244 } else { 3245 assert(VA.isMemLoc()); 3246 3247 SDValue DstAddr; 3248 MachinePointerInfo DstInfo; 3249 3250 unsigned LocMemOffset = VA.getLocMemOffset(); 3251 int32_t Offset = LocMemOffset; 3252 3253 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3254 MaybeAlign Alignment; 3255 3256 if (IsTailCall) { 3257 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3258 unsigned OpSize = Flags.isByVal() ? 3259 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3260 3261 // FIXME: We can have better than the minimum byval required alignment. 3262 Alignment = 3263 Flags.isByVal() 3264 ? Flags.getNonZeroByValAlign() 3265 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3266 3267 Offset = Offset + FPDiff; 3268 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3269 3270 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3271 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3272 3273 // Make sure any stack arguments overlapping with where we're storing 3274 // are loaded before this eventual operation. Otherwise they'll be 3275 // clobbered. 3276 3277 // FIXME: Why is this really necessary? This seems to just result in a 3278 // lot of code to copy the stack and write them back to the same 3279 // locations, which are supposed to be immutable? 3280 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3281 } else { 3282 // Stores to the argument stack area are relative to the stack pointer. 3283 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3284 MVT::i32); 3285 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3286 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3287 Alignment = 3288 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3289 } 3290 3291 if (Outs[i].Flags.isByVal()) { 3292 SDValue SizeNode = 3293 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3294 SDValue Cpy = 3295 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3296 Outs[i].Flags.getNonZeroByValAlign(), 3297 /*isVol = */ false, /*AlwaysInline = */ true, 3298 /*isTailCall = */ false, DstInfo, 3299 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3300 3301 MemOpChains.push_back(Cpy); 3302 } else { 3303 SDValue Store = 3304 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3305 MemOpChains.push_back(Store); 3306 } 3307 } 3308 } 3309 3310 if (!MemOpChains.empty()) 3311 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3312 3313 // Build a sequence of copy-to-reg nodes chained together with token chain 3314 // and flag operands which copy the outgoing args into the appropriate regs. 3315 SDValue InFlag; 3316 for (auto &RegToPass : RegsToPass) { 3317 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3318 RegToPass.second, InFlag); 3319 InFlag = Chain.getValue(1); 3320 } 3321 3322 3323 // We don't usually want to end the call-sequence here because we would tidy 3324 // the frame up *after* the call, however in the ABI-changing tail-call case 3325 // we've carefully laid out the parameters so that when sp is reset they'll be 3326 // in the correct location. 3327 if (IsTailCall && !IsSibCall) { 3328 Chain = DAG.getCALLSEQ_END(Chain, 3329 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3330 DAG.getTargetConstant(0, DL, MVT::i32), 3331 InFlag, DL); 3332 InFlag = Chain.getValue(1); 3333 } 3334 3335 std::vector<SDValue> Ops; 3336 Ops.push_back(Chain); 3337 Ops.push_back(Callee); 3338 // Add a redundant copy of the callee global which will not be legalized, as 3339 // we need direct access to the callee later. 3340 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3341 const GlobalValue *GV = GSD->getGlobal(); 3342 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3343 } else { 3344 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3345 } 3346 3347 if (IsTailCall) { 3348 // Each tail call may have to adjust the stack by a different amount, so 3349 // this information must travel along with the operation for eventual 3350 // consumption by emitEpilogue. 3351 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3352 } 3353 3354 // Add argument registers to the end of the list so that they are known live 3355 // into the call. 3356 for (auto &RegToPass : RegsToPass) { 3357 Ops.push_back(DAG.getRegister(RegToPass.first, 3358 RegToPass.second.getValueType())); 3359 } 3360 3361 // Add a register mask operand representing the call-preserved registers. 3362 3363 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3364 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3365 assert(Mask && "Missing call preserved mask for calling convention"); 3366 Ops.push_back(DAG.getRegisterMask(Mask)); 3367 3368 if (InFlag.getNode()) 3369 Ops.push_back(InFlag); 3370 3371 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3372 3373 // If we're doing a tall call, use a TC_RETURN here rather than an 3374 // actual call instruction. 3375 if (IsTailCall) { 3376 MFI.setHasTailCall(); 3377 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3378 } 3379 3380 // Returns a chain and a flag for retval copy to use. 3381 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3382 Chain = Call.getValue(0); 3383 InFlag = Call.getValue(1); 3384 3385 uint64_t CalleePopBytes = NumBytes; 3386 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3387 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3388 InFlag, DL); 3389 if (!Ins.empty()) 3390 InFlag = Chain.getValue(1); 3391 3392 // Handle result values, copying them out of physregs into vregs that we 3393 // return. 3394 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3395 InVals, IsThisReturn, 3396 IsThisReturn ? OutVals[0] : SDValue()); 3397 } 3398 3399 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3400 // except for applying the wave size scale to the increment amount. 3401 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3402 SDValue Op, SelectionDAG &DAG) const { 3403 const MachineFunction &MF = DAG.getMachineFunction(); 3404 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3405 3406 SDLoc dl(Op); 3407 EVT VT = Op.getValueType(); 3408 SDValue Tmp1 = Op; 3409 SDValue Tmp2 = Op.getValue(1); 3410 SDValue Tmp3 = Op.getOperand(2); 3411 SDValue Chain = Tmp1.getOperand(0); 3412 3413 Register SPReg = Info->getStackPtrOffsetReg(); 3414 3415 // Chain the dynamic stack allocation so that it doesn't modify the stack 3416 // pointer when other instructions are using the stack. 3417 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3418 3419 SDValue Size = Tmp2.getOperand(1); 3420 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3421 Chain = SP.getValue(1); 3422 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3423 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3424 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3425 unsigned Opc = 3426 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3427 ISD::ADD : ISD::SUB; 3428 3429 SDValue ScaledSize = DAG.getNode( 3430 ISD::SHL, dl, VT, Size, 3431 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3432 3433 Align StackAlign = TFL->getStackAlign(); 3434 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3435 if (Alignment && *Alignment > StackAlign) { 3436 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3437 DAG.getConstant(-(uint64_t)Alignment->value() 3438 << ST.getWavefrontSizeLog2(), 3439 dl, VT)); 3440 } 3441 3442 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3443 Tmp2 = DAG.getCALLSEQ_END( 3444 Chain, DAG.getIntPtrConstant(0, dl, true), 3445 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3446 3447 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3448 } 3449 3450 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3451 SelectionDAG &DAG) const { 3452 // We only handle constant sizes here to allow non-entry block, static sized 3453 // allocas. A truly dynamic value is more difficult to support because we 3454 // don't know if the size value is uniform or not. If the size isn't uniform, 3455 // we would need to do a wave reduction to get the maximum size to know how 3456 // much to increment the uniform stack pointer. 3457 SDValue Size = Op.getOperand(1); 3458 if (isa<ConstantSDNode>(Size)) 3459 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3460 3461 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3462 } 3463 3464 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3465 const MachineFunction &MF) const { 3466 Register Reg = StringSwitch<Register>(RegName) 3467 .Case("m0", AMDGPU::M0) 3468 .Case("exec", AMDGPU::EXEC) 3469 .Case("exec_lo", AMDGPU::EXEC_LO) 3470 .Case("exec_hi", AMDGPU::EXEC_HI) 3471 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3472 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3473 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3474 .Default(Register()); 3475 3476 if (Reg == AMDGPU::NoRegister) { 3477 report_fatal_error(Twine("invalid register name \"" 3478 + StringRef(RegName) + "\".")); 3479 3480 } 3481 3482 if (!Subtarget->hasFlatScrRegister() && 3483 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3484 report_fatal_error(Twine("invalid register \"" 3485 + StringRef(RegName) + "\" for subtarget.")); 3486 } 3487 3488 switch (Reg) { 3489 case AMDGPU::M0: 3490 case AMDGPU::EXEC_LO: 3491 case AMDGPU::EXEC_HI: 3492 case AMDGPU::FLAT_SCR_LO: 3493 case AMDGPU::FLAT_SCR_HI: 3494 if (VT.getSizeInBits() == 32) 3495 return Reg; 3496 break; 3497 case AMDGPU::EXEC: 3498 case AMDGPU::FLAT_SCR: 3499 if (VT.getSizeInBits() == 64) 3500 return Reg; 3501 break; 3502 default: 3503 llvm_unreachable("missing register type checking"); 3504 } 3505 3506 report_fatal_error(Twine("invalid type for register \"" 3507 + StringRef(RegName) + "\".")); 3508 } 3509 3510 // If kill is not the last instruction, split the block so kill is always a 3511 // proper terminator. 3512 MachineBasicBlock * 3513 SITargetLowering::splitKillBlock(MachineInstr &MI, 3514 MachineBasicBlock *BB) const { 3515 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3516 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3517 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3518 return SplitBB; 3519 } 3520 3521 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3522 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3523 // be the first instruction in the remainder block. 3524 // 3525 /// \returns { LoopBody, Remainder } 3526 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3527 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3528 MachineFunction *MF = MBB.getParent(); 3529 MachineBasicBlock::iterator I(&MI); 3530 3531 // To insert the loop we need to split the block. Move everything after this 3532 // point to a new block, and insert a new empty block between the two. 3533 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3534 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3535 MachineFunction::iterator MBBI(MBB); 3536 ++MBBI; 3537 3538 MF->insert(MBBI, LoopBB); 3539 MF->insert(MBBI, RemainderBB); 3540 3541 LoopBB->addSuccessor(LoopBB); 3542 LoopBB->addSuccessor(RemainderBB); 3543 3544 // Move the rest of the block into a new block. 3545 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3546 3547 if (InstInLoop) { 3548 auto Next = std::next(I); 3549 3550 // Move instruction to loop body. 3551 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3552 3553 // Move the rest of the block. 3554 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3555 } else { 3556 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3557 } 3558 3559 MBB.addSuccessor(LoopBB); 3560 3561 return std::make_pair(LoopBB, RemainderBB); 3562 } 3563 3564 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3565 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3566 MachineBasicBlock *MBB = MI.getParent(); 3567 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3568 auto I = MI.getIterator(); 3569 auto E = std::next(I); 3570 3571 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3572 .addImm(0); 3573 3574 MIBundleBuilder Bundler(*MBB, I, E); 3575 finalizeBundle(*MBB, Bundler.begin()); 3576 } 3577 3578 MachineBasicBlock * 3579 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3580 MachineBasicBlock *BB) const { 3581 const DebugLoc &DL = MI.getDebugLoc(); 3582 3583 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3584 3585 MachineBasicBlock *LoopBB; 3586 MachineBasicBlock *RemainderBB; 3587 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3588 3589 // Apparently kill flags are only valid if the def is in the same block? 3590 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3591 Src->setIsKill(false); 3592 3593 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3594 3595 MachineBasicBlock::iterator I = LoopBB->end(); 3596 3597 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3598 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3599 3600 // Clear TRAP_STS.MEM_VIOL 3601 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3602 .addImm(0) 3603 .addImm(EncodedReg); 3604 3605 bundleInstWithWaitcnt(MI); 3606 3607 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3608 3609 // Load and check TRAP_STS.MEM_VIOL 3610 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3611 .addImm(EncodedReg); 3612 3613 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3614 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3615 .addReg(Reg, RegState::Kill) 3616 .addImm(0); 3617 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3618 .addMBB(LoopBB); 3619 3620 return RemainderBB; 3621 } 3622 3623 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3624 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3625 // will only do one iteration. In the worst case, this will loop 64 times. 3626 // 3627 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3628 static MachineBasicBlock::iterator 3629 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3630 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3631 const DebugLoc &DL, const MachineOperand &Idx, 3632 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3633 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3634 Register &SGPRIdxReg) { 3635 3636 MachineFunction *MF = OrigBB.getParent(); 3637 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3638 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3639 MachineBasicBlock::iterator I = LoopBB.begin(); 3640 3641 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3642 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3643 Register NewExec = MRI.createVirtualRegister(BoolRC); 3644 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3645 Register CondReg = MRI.createVirtualRegister(BoolRC); 3646 3647 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3648 .addReg(InitReg) 3649 .addMBB(&OrigBB) 3650 .addReg(ResultReg) 3651 .addMBB(&LoopBB); 3652 3653 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3654 .addReg(InitSaveExecReg) 3655 .addMBB(&OrigBB) 3656 .addReg(NewExec) 3657 .addMBB(&LoopBB); 3658 3659 // Read the next variant <- also loop target. 3660 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3661 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3662 3663 // Compare the just read M0 value to all possible Idx values. 3664 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3665 .addReg(CurrentIdxReg) 3666 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3667 3668 // Update EXEC, save the original EXEC value to VCC. 3669 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3670 : AMDGPU::S_AND_SAVEEXEC_B64), 3671 NewExec) 3672 .addReg(CondReg, RegState::Kill); 3673 3674 MRI.setSimpleHint(NewExec, CondReg); 3675 3676 if (UseGPRIdxMode) { 3677 if (Offset == 0) { 3678 SGPRIdxReg = CurrentIdxReg; 3679 } else { 3680 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3681 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3682 .addReg(CurrentIdxReg, RegState::Kill) 3683 .addImm(Offset); 3684 } 3685 } else { 3686 // Move index from VCC into M0 3687 if (Offset == 0) { 3688 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3689 .addReg(CurrentIdxReg, RegState::Kill); 3690 } else { 3691 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3692 .addReg(CurrentIdxReg, RegState::Kill) 3693 .addImm(Offset); 3694 } 3695 } 3696 3697 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3698 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3699 MachineInstr *InsertPt = 3700 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3701 : AMDGPU::S_XOR_B64_term), Exec) 3702 .addReg(Exec) 3703 .addReg(NewExec); 3704 3705 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3706 // s_cbranch_scc0? 3707 3708 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3709 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3710 .addMBB(&LoopBB); 3711 3712 return InsertPt->getIterator(); 3713 } 3714 3715 // This has slightly sub-optimal regalloc when the source vector is killed by 3716 // the read. The register allocator does not understand that the kill is 3717 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3718 // subregister from it, using 1 more VGPR than necessary. This was saved when 3719 // this was expanded after register allocation. 3720 static MachineBasicBlock::iterator 3721 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3722 unsigned InitResultReg, unsigned PhiReg, int Offset, 3723 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3724 MachineFunction *MF = MBB.getParent(); 3725 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3726 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3727 MachineRegisterInfo &MRI = MF->getRegInfo(); 3728 const DebugLoc &DL = MI.getDebugLoc(); 3729 MachineBasicBlock::iterator I(&MI); 3730 3731 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3732 Register DstReg = MI.getOperand(0).getReg(); 3733 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3734 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3735 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3736 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3737 3738 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3739 3740 // Save the EXEC mask 3741 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3742 .addReg(Exec); 3743 3744 MachineBasicBlock *LoopBB; 3745 MachineBasicBlock *RemainderBB; 3746 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3747 3748 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3749 3750 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3751 InitResultReg, DstReg, PhiReg, TmpExec, 3752 Offset, UseGPRIdxMode, SGPRIdxReg); 3753 3754 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3755 MachineFunction::iterator MBBI(LoopBB); 3756 ++MBBI; 3757 MF->insert(MBBI, LandingPad); 3758 LoopBB->removeSuccessor(RemainderBB); 3759 LandingPad->addSuccessor(RemainderBB); 3760 LoopBB->addSuccessor(LandingPad); 3761 MachineBasicBlock::iterator First = LandingPad->begin(); 3762 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3763 .addReg(SaveExec); 3764 3765 return InsPt; 3766 } 3767 3768 // Returns subreg index, offset 3769 static std::pair<unsigned, int> 3770 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3771 const TargetRegisterClass *SuperRC, 3772 unsigned VecReg, 3773 int Offset) { 3774 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3775 3776 // Skip out of bounds offsets, or else we would end up using an undefined 3777 // register. 3778 if (Offset >= NumElts || Offset < 0) 3779 return std::make_pair(AMDGPU::sub0, Offset); 3780 3781 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3782 } 3783 3784 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3785 MachineRegisterInfo &MRI, MachineInstr &MI, 3786 int Offset) { 3787 MachineBasicBlock *MBB = MI.getParent(); 3788 const DebugLoc &DL = MI.getDebugLoc(); 3789 MachineBasicBlock::iterator I(&MI); 3790 3791 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3792 3793 assert(Idx->getReg() != AMDGPU::NoRegister); 3794 3795 if (Offset == 0) { 3796 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3797 } else { 3798 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3799 .add(*Idx) 3800 .addImm(Offset); 3801 } 3802 } 3803 3804 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3805 MachineRegisterInfo &MRI, MachineInstr &MI, 3806 int Offset) { 3807 MachineBasicBlock *MBB = MI.getParent(); 3808 const DebugLoc &DL = MI.getDebugLoc(); 3809 MachineBasicBlock::iterator I(&MI); 3810 3811 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3812 3813 if (Offset == 0) 3814 return Idx->getReg(); 3815 3816 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3817 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3818 .add(*Idx) 3819 .addImm(Offset); 3820 return Tmp; 3821 } 3822 3823 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3824 MachineBasicBlock &MBB, 3825 const GCNSubtarget &ST) { 3826 const SIInstrInfo *TII = ST.getInstrInfo(); 3827 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3828 MachineFunction *MF = MBB.getParent(); 3829 MachineRegisterInfo &MRI = MF->getRegInfo(); 3830 3831 Register Dst = MI.getOperand(0).getReg(); 3832 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3833 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3834 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3835 3836 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3837 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3838 3839 unsigned SubReg; 3840 std::tie(SubReg, Offset) 3841 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3842 3843 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3844 3845 // Check for a SGPR index. 3846 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3847 MachineBasicBlock::iterator I(&MI); 3848 const DebugLoc &DL = MI.getDebugLoc(); 3849 3850 if (UseGPRIdxMode) { 3851 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3852 // to avoid interfering with other uses, so probably requires a new 3853 // optimization pass. 3854 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3855 3856 const MCInstrDesc &GPRIDXDesc = 3857 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3858 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3859 .addReg(SrcReg) 3860 .addReg(Idx) 3861 .addImm(SubReg); 3862 } else { 3863 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3864 3865 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3866 .addReg(SrcReg, 0, SubReg) 3867 .addReg(SrcReg, RegState::Implicit); 3868 } 3869 3870 MI.eraseFromParent(); 3871 3872 return &MBB; 3873 } 3874 3875 // Control flow needs to be inserted if indexing with a VGPR. 3876 const DebugLoc &DL = MI.getDebugLoc(); 3877 MachineBasicBlock::iterator I(&MI); 3878 3879 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3880 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3881 3882 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3883 3884 Register SGPRIdxReg; 3885 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3886 UseGPRIdxMode, SGPRIdxReg); 3887 3888 MachineBasicBlock *LoopBB = InsPt->getParent(); 3889 3890 if (UseGPRIdxMode) { 3891 const MCInstrDesc &GPRIDXDesc = 3892 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3893 3894 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3895 .addReg(SrcReg) 3896 .addReg(SGPRIdxReg) 3897 .addImm(SubReg); 3898 } else { 3899 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3900 .addReg(SrcReg, 0, SubReg) 3901 .addReg(SrcReg, RegState::Implicit); 3902 } 3903 3904 MI.eraseFromParent(); 3905 3906 return LoopBB; 3907 } 3908 3909 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3910 MachineBasicBlock &MBB, 3911 const GCNSubtarget &ST) { 3912 const SIInstrInfo *TII = ST.getInstrInfo(); 3913 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3914 MachineFunction *MF = MBB.getParent(); 3915 MachineRegisterInfo &MRI = MF->getRegInfo(); 3916 3917 Register Dst = MI.getOperand(0).getReg(); 3918 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3919 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3920 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3921 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3922 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3923 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3924 3925 // This can be an immediate, but will be folded later. 3926 assert(Val->getReg()); 3927 3928 unsigned SubReg; 3929 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3930 SrcVec->getReg(), 3931 Offset); 3932 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3933 3934 if (Idx->getReg() == AMDGPU::NoRegister) { 3935 MachineBasicBlock::iterator I(&MI); 3936 const DebugLoc &DL = MI.getDebugLoc(); 3937 3938 assert(Offset == 0); 3939 3940 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3941 .add(*SrcVec) 3942 .add(*Val) 3943 .addImm(SubReg); 3944 3945 MI.eraseFromParent(); 3946 return &MBB; 3947 } 3948 3949 // Check for a SGPR index. 3950 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3951 MachineBasicBlock::iterator I(&MI); 3952 const DebugLoc &DL = MI.getDebugLoc(); 3953 3954 if (UseGPRIdxMode) { 3955 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3956 3957 const MCInstrDesc &GPRIDXDesc = 3958 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3959 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3960 .addReg(SrcVec->getReg()) 3961 .add(*Val) 3962 .addReg(Idx) 3963 .addImm(SubReg); 3964 } else { 3965 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3966 3967 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3968 TRI.getRegSizeInBits(*VecRC), 32, false); 3969 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3970 .addReg(SrcVec->getReg()) 3971 .add(*Val) 3972 .addImm(SubReg); 3973 } 3974 MI.eraseFromParent(); 3975 return &MBB; 3976 } 3977 3978 // Control flow needs to be inserted if indexing with a VGPR. 3979 if (Val->isReg()) 3980 MRI.clearKillFlags(Val->getReg()); 3981 3982 const DebugLoc &DL = MI.getDebugLoc(); 3983 3984 Register PhiReg = MRI.createVirtualRegister(VecRC); 3985 3986 Register SGPRIdxReg; 3987 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3988 UseGPRIdxMode, SGPRIdxReg); 3989 MachineBasicBlock *LoopBB = InsPt->getParent(); 3990 3991 if (UseGPRIdxMode) { 3992 const MCInstrDesc &GPRIDXDesc = 3993 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3994 3995 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3996 .addReg(PhiReg) 3997 .add(*Val) 3998 .addReg(SGPRIdxReg) 3999 .addImm(AMDGPU::sub0); 4000 } else { 4001 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4002 TRI.getRegSizeInBits(*VecRC), 32, false); 4003 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 4004 .addReg(PhiReg) 4005 .add(*Val) 4006 .addImm(AMDGPU::sub0); 4007 } 4008 4009 MI.eraseFromParent(); 4010 return LoopBB; 4011 } 4012 4013 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4014 MachineInstr &MI, MachineBasicBlock *BB) const { 4015 4016 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4017 MachineFunction *MF = BB->getParent(); 4018 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4019 4020 switch (MI.getOpcode()) { 4021 case AMDGPU::S_UADDO_PSEUDO: 4022 case AMDGPU::S_USUBO_PSEUDO: { 4023 const DebugLoc &DL = MI.getDebugLoc(); 4024 MachineOperand &Dest0 = MI.getOperand(0); 4025 MachineOperand &Dest1 = MI.getOperand(1); 4026 MachineOperand &Src0 = MI.getOperand(2); 4027 MachineOperand &Src1 = MI.getOperand(3); 4028 4029 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4030 ? AMDGPU::S_ADD_I32 4031 : AMDGPU::S_SUB_I32; 4032 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4033 4034 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4035 .addImm(1) 4036 .addImm(0); 4037 4038 MI.eraseFromParent(); 4039 return BB; 4040 } 4041 case AMDGPU::S_ADD_U64_PSEUDO: 4042 case AMDGPU::S_SUB_U64_PSEUDO: { 4043 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4044 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4045 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4046 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4047 const DebugLoc &DL = MI.getDebugLoc(); 4048 4049 MachineOperand &Dest = MI.getOperand(0); 4050 MachineOperand &Src0 = MI.getOperand(1); 4051 MachineOperand &Src1 = MI.getOperand(2); 4052 4053 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4054 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4055 4056 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4057 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4058 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4059 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4060 4061 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4062 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4063 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4064 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4065 4066 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4067 4068 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4069 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4070 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4071 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4072 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4073 .addReg(DestSub0) 4074 .addImm(AMDGPU::sub0) 4075 .addReg(DestSub1) 4076 .addImm(AMDGPU::sub1); 4077 MI.eraseFromParent(); 4078 return BB; 4079 } 4080 case AMDGPU::V_ADD_U64_PSEUDO: 4081 case AMDGPU::V_SUB_U64_PSEUDO: { 4082 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4083 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4084 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4085 const DebugLoc &DL = MI.getDebugLoc(); 4086 4087 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4088 4089 MachineOperand &Dest = MI.getOperand(0); 4090 MachineOperand &Src0 = MI.getOperand(1); 4091 MachineOperand &Src1 = MI.getOperand(2); 4092 4093 if (IsAdd && ST.hasLshlAddB64()) { 4094 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4095 Dest.getReg()) 4096 .add(Src0) 4097 .addImm(0) 4098 .add(Src1); 4099 TII->legalizeOperands(*Add); 4100 MI.eraseFromParent(); 4101 return BB; 4102 } 4103 4104 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4105 4106 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4107 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4108 4109 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4110 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4111 4112 const TargetRegisterClass *Src0RC = Src0.isReg() 4113 ? MRI.getRegClass(Src0.getReg()) 4114 : &AMDGPU::VReg_64RegClass; 4115 const TargetRegisterClass *Src1RC = Src1.isReg() 4116 ? MRI.getRegClass(Src1.getReg()) 4117 : &AMDGPU::VReg_64RegClass; 4118 4119 const TargetRegisterClass *Src0SubRC = 4120 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4121 const TargetRegisterClass *Src1SubRC = 4122 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4123 4124 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4125 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4126 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4127 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4128 4129 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4130 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4131 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4132 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4133 4134 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4135 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4136 .addReg(CarryReg, RegState::Define) 4137 .add(SrcReg0Sub0) 4138 .add(SrcReg1Sub0) 4139 .addImm(0); // clamp bit 4140 4141 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4142 MachineInstr *HiHalf = 4143 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4144 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4145 .add(SrcReg0Sub1) 4146 .add(SrcReg1Sub1) 4147 .addReg(CarryReg, RegState::Kill) 4148 .addImm(0); // clamp bit 4149 4150 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4151 .addReg(DestSub0) 4152 .addImm(AMDGPU::sub0) 4153 .addReg(DestSub1) 4154 .addImm(AMDGPU::sub1); 4155 TII->legalizeOperands(*LoHalf); 4156 TII->legalizeOperands(*HiHalf); 4157 MI.eraseFromParent(); 4158 return BB; 4159 } 4160 case AMDGPU::S_ADD_CO_PSEUDO: 4161 case AMDGPU::S_SUB_CO_PSEUDO: { 4162 // This pseudo has a chance to be selected 4163 // only from uniform add/subcarry node. All the VGPR operands 4164 // therefore assumed to be splat vectors. 4165 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4166 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4167 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4168 MachineBasicBlock::iterator MII = MI; 4169 const DebugLoc &DL = MI.getDebugLoc(); 4170 MachineOperand &Dest = MI.getOperand(0); 4171 MachineOperand &CarryDest = MI.getOperand(1); 4172 MachineOperand &Src0 = MI.getOperand(2); 4173 MachineOperand &Src1 = MI.getOperand(3); 4174 MachineOperand &Src2 = MI.getOperand(4); 4175 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4176 ? AMDGPU::S_ADDC_U32 4177 : AMDGPU::S_SUBB_U32; 4178 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4179 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4180 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4181 .addReg(Src0.getReg()); 4182 Src0.setReg(RegOp0); 4183 } 4184 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4185 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4186 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4187 .addReg(Src1.getReg()); 4188 Src1.setReg(RegOp1); 4189 } 4190 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4191 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4192 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4193 .addReg(Src2.getReg()); 4194 Src2.setReg(RegOp2); 4195 } 4196 4197 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4198 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4199 assert(WaveSize == 64 || WaveSize == 32); 4200 4201 if (WaveSize == 64) { 4202 if (ST.hasScalarCompareEq64()) { 4203 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4204 .addReg(Src2.getReg()) 4205 .addImm(0); 4206 } else { 4207 const TargetRegisterClass *SubRC = 4208 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4209 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4210 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4211 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4212 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4213 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4214 4215 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4216 .add(Src2Sub0) 4217 .add(Src2Sub1); 4218 4219 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4220 .addReg(Src2_32, RegState::Kill) 4221 .addImm(0); 4222 } 4223 } else { 4224 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4225 .addReg(Src2.getReg()) 4226 .addImm(0); 4227 } 4228 4229 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4230 4231 unsigned SelOpc = 4232 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4233 4234 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4235 .addImm(-1) 4236 .addImm(0); 4237 4238 MI.eraseFromParent(); 4239 return BB; 4240 } 4241 case AMDGPU::SI_INIT_M0: { 4242 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4243 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4244 .add(MI.getOperand(0)); 4245 MI.eraseFromParent(); 4246 return BB; 4247 } 4248 case AMDGPU::GET_GROUPSTATICSIZE: { 4249 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4250 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4251 DebugLoc DL = MI.getDebugLoc(); 4252 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4253 .add(MI.getOperand(0)) 4254 .addImm(MFI->getLDSSize()); 4255 MI.eraseFromParent(); 4256 return BB; 4257 } 4258 case AMDGPU::SI_INDIRECT_SRC_V1: 4259 case AMDGPU::SI_INDIRECT_SRC_V2: 4260 case AMDGPU::SI_INDIRECT_SRC_V4: 4261 case AMDGPU::SI_INDIRECT_SRC_V8: 4262 case AMDGPU::SI_INDIRECT_SRC_V16: 4263 case AMDGPU::SI_INDIRECT_SRC_V32: 4264 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4265 case AMDGPU::SI_INDIRECT_DST_V1: 4266 case AMDGPU::SI_INDIRECT_DST_V2: 4267 case AMDGPU::SI_INDIRECT_DST_V4: 4268 case AMDGPU::SI_INDIRECT_DST_V8: 4269 case AMDGPU::SI_INDIRECT_DST_V16: 4270 case AMDGPU::SI_INDIRECT_DST_V32: 4271 return emitIndirectDst(MI, *BB, *getSubtarget()); 4272 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4273 case AMDGPU::SI_KILL_I1_PSEUDO: 4274 return splitKillBlock(MI, BB); 4275 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4276 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4277 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4278 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4279 4280 Register Dst = MI.getOperand(0).getReg(); 4281 Register Src0 = MI.getOperand(1).getReg(); 4282 Register Src1 = MI.getOperand(2).getReg(); 4283 const DebugLoc &DL = MI.getDebugLoc(); 4284 Register SrcCond = MI.getOperand(3).getReg(); 4285 4286 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4287 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4288 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4289 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4290 4291 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4292 .addReg(SrcCond); 4293 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4294 .addImm(0) 4295 .addReg(Src0, 0, AMDGPU::sub0) 4296 .addImm(0) 4297 .addReg(Src1, 0, AMDGPU::sub0) 4298 .addReg(SrcCondCopy); 4299 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4300 .addImm(0) 4301 .addReg(Src0, 0, AMDGPU::sub1) 4302 .addImm(0) 4303 .addReg(Src1, 0, AMDGPU::sub1) 4304 .addReg(SrcCondCopy); 4305 4306 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4307 .addReg(DstLo) 4308 .addImm(AMDGPU::sub0) 4309 .addReg(DstHi) 4310 .addImm(AMDGPU::sub1); 4311 MI.eraseFromParent(); 4312 return BB; 4313 } 4314 case AMDGPU::SI_BR_UNDEF: { 4315 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4316 const DebugLoc &DL = MI.getDebugLoc(); 4317 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4318 .add(MI.getOperand(0)); 4319 Br->getOperand(1).setIsUndef(true); // read undef SCC 4320 MI.eraseFromParent(); 4321 return BB; 4322 } 4323 case AMDGPU::ADJCALLSTACKUP: 4324 case AMDGPU::ADJCALLSTACKDOWN: { 4325 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4326 MachineInstrBuilder MIB(*MF, &MI); 4327 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4328 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4329 return BB; 4330 } 4331 case AMDGPU::SI_CALL_ISEL: { 4332 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4333 const DebugLoc &DL = MI.getDebugLoc(); 4334 4335 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4336 4337 MachineInstrBuilder MIB; 4338 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4339 4340 for (const MachineOperand &MO : MI.operands()) 4341 MIB.add(MO); 4342 4343 MIB.cloneMemRefs(MI); 4344 MI.eraseFromParent(); 4345 return BB; 4346 } 4347 case AMDGPU::V_ADD_CO_U32_e32: 4348 case AMDGPU::V_SUB_CO_U32_e32: 4349 case AMDGPU::V_SUBREV_CO_U32_e32: { 4350 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4351 const DebugLoc &DL = MI.getDebugLoc(); 4352 unsigned Opc = MI.getOpcode(); 4353 4354 bool NeedClampOperand = false; 4355 if (TII->pseudoToMCOpcode(Opc) == -1) { 4356 Opc = AMDGPU::getVOPe64(Opc); 4357 NeedClampOperand = true; 4358 } 4359 4360 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4361 if (TII->isVOP3(*I)) { 4362 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4363 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4364 I.addReg(TRI->getVCC(), RegState::Define); 4365 } 4366 I.add(MI.getOperand(1)) 4367 .add(MI.getOperand(2)); 4368 if (NeedClampOperand) 4369 I.addImm(0); // clamp bit for e64 encoding 4370 4371 TII->legalizeOperands(*I); 4372 4373 MI.eraseFromParent(); 4374 return BB; 4375 } 4376 case AMDGPU::V_ADDC_U32_e32: 4377 case AMDGPU::V_SUBB_U32_e32: 4378 case AMDGPU::V_SUBBREV_U32_e32: 4379 // These instructions have an implicit use of vcc which counts towards the 4380 // constant bus limit. 4381 TII->legalizeOperands(MI); 4382 return BB; 4383 case AMDGPU::DS_GWS_INIT: 4384 case AMDGPU::DS_GWS_SEMA_BR: 4385 case AMDGPU::DS_GWS_BARRIER: 4386 if (Subtarget->needsAlignedVGPRs()) { 4387 // Add implicit aligned super-reg to force alignment on the data operand. 4388 const DebugLoc &DL = MI.getDebugLoc(); 4389 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4390 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4391 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4392 Register DataReg = Op->getReg(); 4393 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4394 Register Undef = MRI.createVirtualRegister( 4395 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4396 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4397 Register NewVR = 4398 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4399 : &AMDGPU::VReg_64_Align2RegClass); 4400 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4401 .addReg(DataReg, 0, Op->getSubReg()) 4402 .addImm(AMDGPU::sub0) 4403 .addReg(Undef) 4404 .addImm(AMDGPU::sub1); 4405 Op->setReg(NewVR); 4406 Op->setSubReg(AMDGPU::sub0); 4407 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4408 } 4409 LLVM_FALLTHROUGH; 4410 case AMDGPU::DS_GWS_SEMA_V: 4411 case AMDGPU::DS_GWS_SEMA_P: 4412 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4413 // A s_waitcnt 0 is required to be the instruction immediately following. 4414 if (getSubtarget()->hasGWSAutoReplay()) { 4415 bundleInstWithWaitcnt(MI); 4416 return BB; 4417 } 4418 4419 return emitGWSMemViolTestLoop(MI, BB); 4420 case AMDGPU::S_SETREG_B32: { 4421 // Try to optimize cases that only set the denormal mode or rounding mode. 4422 // 4423 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4424 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4425 // instead. 4426 // 4427 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4428 // allow you to have a no side effect instruction in the output of a 4429 // sideeffecting pattern. 4430 unsigned ID, Offset, Width; 4431 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4432 if (ID != AMDGPU::Hwreg::ID_MODE) 4433 return BB; 4434 4435 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4436 const unsigned SetMask = WidthMask << Offset; 4437 4438 if (getSubtarget()->hasDenormModeInst()) { 4439 unsigned SetDenormOp = 0; 4440 unsigned SetRoundOp = 0; 4441 4442 // The dedicated instructions can only set the whole denorm or round mode 4443 // at once, not a subset of bits in either. 4444 if (SetMask == 4445 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4446 // If this fully sets both the round and denorm mode, emit the two 4447 // dedicated instructions for these. 4448 SetRoundOp = AMDGPU::S_ROUND_MODE; 4449 SetDenormOp = AMDGPU::S_DENORM_MODE; 4450 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4451 SetRoundOp = AMDGPU::S_ROUND_MODE; 4452 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4453 SetDenormOp = AMDGPU::S_DENORM_MODE; 4454 } 4455 4456 if (SetRoundOp || SetDenormOp) { 4457 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4458 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4459 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4460 unsigned ImmVal = Def->getOperand(1).getImm(); 4461 if (SetRoundOp) { 4462 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4463 .addImm(ImmVal & 0xf); 4464 4465 // If we also have the denorm mode, get just the denorm mode bits. 4466 ImmVal >>= 4; 4467 } 4468 4469 if (SetDenormOp) { 4470 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4471 .addImm(ImmVal & 0xf); 4472 } 4473 4474 MI.eraseFromParent(); 4475 return BB; 4476 } 4477 } 4478 } 4479 4480 // If only FP bits are touched, used the no side effects pseudo. 4481 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4482 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4483 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4484 4485 return BB; 4486 } 4487 default: 4488 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4489 } 4490 } 4491 4492 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4493 return isTypeLegal(VT.getScalarType()); 4494 } 4495 4496 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4497 // This currently forces unfolding various combinations of fsub into fma with 4498 // free fneg'd operands. As long as we have fast FMA (controlled by 4499 // isFMAFasterThanFMulAndFAdd), we should perform these. 4500 4501 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4502 // most of these combines appear to be cycle neutral but save on instruction 4503 // count / code size. 4504 return true; 4505 } 4506 4507 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4508 4509 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4510 EVT VT) const { 4511 if (!VT.isVector()) { 4512 return MVT::i1; 4513 } 4514 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4515 } 4516 4517 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4518 // TODO: Should i16 be used always if legal? For now it would force VALU 4519 // shifts. 4520 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4521 } 4522 4523 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4524 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4525 ? Ty.changeElementSize(16) 4526 : Ty.changeElementSize(32); 4527 } 4528 4529 // Answering this is somewhat tricky and depends on the specific device which 4530 // have different rates for fma or all f64 operations. 4531 // 4532 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4533 // regardless of which device (although the number of cycles differs between 4534 // devices), so it is always profitable for f64. 4535 // 4536 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4537 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4538 // which we can always do even without fused FP ops since it returns the same 4539 // result as the separate operations and since it is always full 4540 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4541 // however does not support denormals, so we do report fma as faster if we have 4542 // a fast fma device and require denormals. 4543 // 4544 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4545 EVT VT) const { 4546 VT = VT.getScalarType(); 4547 4548 switch (VT.getSimpleVT().SimpleTy) { 4549 case MVT::f32: { 4550 // If mad is not available this depends only on if f32 fma is full rate. 4551 if (!Subtarget->hasMadMacF32Insts()) 4552 return Subtarget->hasFastFMAF32(); 4553 4554 // Otherwise f32 mad is always full rate and returns the same result as 4555 // the separate operations so should be preferred over fma. 4556 // However does not support denormals. 4557 if (hasFP32Denormals(MF)) 4558 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4559 4560 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4561 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4562 } 4563 case MVT::f64: 4564 return true; 4565 case MVT::f16: 4566 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4567 default: 4568 break; 4569 } 4570 4571 return false; 4572 } 4573 4574 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4575 LLT Ty) const { 4576 switch (Ty.getScalarSizeInBits()) { 4577 case 16: 4578 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4579 case 32: 4580 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4581 case 64: 4582 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4583 default: 4584 break; 4585 } 4586 4587 return false; 4588 } 4589 4590 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4591 if (!Ty.isScalar()) 4592 return false; 4593 4594 if (Ty.getScalarSizeInBits() == 16) 4595 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4596 if (Ty.getScalarSizeInBits() == 32) 4597 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4598 4599 return false; 4600 } 4601 4602 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4603 const SDNode *N) const { 4604 // TODO: Check future ftz flag 4605 // v_mad_f32/v_mac_f32 do not support denormals. 4606 EVT VT = N->getValueType(0); 4607 if (VT == MVT::f32) 4608 return Subtarget->hasMadMacF32Insts() && 4609 !hasFP32Denormals(DAG.getMachineFunction()); 4610 if (VT == MVT::f16) { 4611 return Subtarget->hasMadF16() && 4612 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4613 } 4614 4615 return false; 4616 } 4617 4618 //===----------------------------------------------------------------------===// 4619 // Custom DAG Lowering Operations 4620 //===----------------------------------------------------------------------===// 4621 4622 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4623 // wider vector type is legal. 4624 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4625 SelectionDAG &DAG) const { 4626 unsigned Opc = Op.getOpcode(); 4627 EVT VT = Op.getValueType(); 4628 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4629 4630 SDValue Lo, Hi; 4631 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4632 4633 SDLoc SL(Op); 4634 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4635 Op->getFlags()); 4636 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4637 Op->getFlags()); 4638 4639 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4640 } 4641 4642 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4643 // wider vector type is legal. 4644 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4645 SelectionDAG &DAG) const { 4646 unsigned Opc = Op.getOpcode(); 4647 EVT VT = Op.getValueType(); 4648 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4649 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4650 VT == MVT::v16f32 || VT == MVT::v32f32); 4651 4652 SDValue Lo0, Hi0; 4653 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4654 SDValue Lo1, Hi1; 4655 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4656 4657 SDLoc SL(Op); 4658 4659 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4660 Op->getFlags()); 4661 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4662 Op->getFlags()); 4663 4664 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4665 } 4666 4667 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4668 SelectionDAG &DAG) const { 4669 unsigned Opc = Op.getOpcode(); 4670 EVT VT = Op.getValueType(); 4671 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4672 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4673 VT == MVT::v16f32 || VT == MVT::v32f32); 4674 4675 SDValue Lo0, Hi0; 4676 SDValue Op0 = Op.getOperand(0); 4677 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4678 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4679 : std::make_pair(Op0, Op0); 4680 SDValue Lo1, Hi1; 4681 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4682 SDValue Lo2, Hi2; 4683 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4684 4685 SDLoc SL(Op); 4686 auto ResVT = DAG.GetSplitDestVTs(VT); 4687 4688 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4689 Op->getFlags()); 4690 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4691 Op->getFlags()); 4692 4693 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4694 } 4695 4696 4697 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4698 switch (Op.getOpcode()) { 4699 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4700 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4701 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4702 case ISD::LOAD: { 4703 SDValue Result = LowerLOAD(Op, DAG); 4704 assert((!Result.getNode() || 4705 Result.getNode()->getNumValues() == 2) && 4706 "Load should return a value and a chain"); 4707 return Result; 4708 } 4709 4710 case ISD::FSIN: 4711 case ISD::FCOS: 4712 return LowerTrig(Op, DAG); 4713 case ISD::SELECT: return LowerSELECT(Op, DAG); 4714 case ISD::FDIV: return LowerFDIV(Op, DAG); 4715 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4716 case ISD::STORE: return LowerSTORE(Op, DAG); 4717 case ISD::GlobalAddress: { 4718 MachineFunction &MF = DAG.getMachineFunction(); 4719 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4720 return LowerGlobalAddress(MFI, Op, DAG); 4721 } 4722 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4723 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4724 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4725 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4726 case ISD::INSERT_SUBVECTOR: 4727 return lowerINSERT_SUBVECTOR(Op, DAG); 4728 case ISD::INSERT_VECTOR_ELT: 4729 return lowerINSERT_VECTOR_ELT(Op, DAG); 4730 case ISD::EXTRACT_VECTOR_ELT: 4731 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4732 case ISD::VECTOR_SHUFFLE: 4733 return lowerVECTOR_SHUFFLE(Op, DAG); 4734 case ISD::BUILD_VECTOR: 4735 return lowerBUILD_VECTOR(Op, DAG); 4736 case ISD::FP_ROUND: 4737 return lowerFP_ROUND(Op, DAG); 4738 case ISD::FPTRUNC_ROUND: { 4739 unsigned Opc; 4740 SDLoc DL(Op); 4741 4742 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4743 return SDValue(); 4744 4745 // Get the rounding mode from the last operand 4746 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4747 if (RoundMode == (int)RoundingMode::TowardPositive) 4748 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4749 else if (RoundMode == (int)RoundingMode::TowardNegative) 4750 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4751 else 4752 return SDValue(); 4753 4754 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4755 } 4756 case ISD::TRAP: 4757 return lowerTRAP(Op, DAG); 4758 case ISD::DEBUGTRAP: 4759 return lowerDEBUGTRAP(Op, DAG); 4760 case ISD::FABS: 4761 case ISD::FNEG: 4762 case ISD::FCANONICALIZE: 4763 case ISD::BSWAP: 4764 return splitUnaryVectorOp(Op, DAG); 4765 case ISD::FMINNUM: 4766 case ISD::FMAXNUM: 4767 return lowerFMINNUM_FMAXNUM(Op, DAG); 4768 case ISD::FMA: 4769 return splitTernaryVectorOp(Op, DAG); 4770 case ISD::FP_TO_SINT: 4771 case ISD::FP_TO_UINT: 4772 return LowerFP_TO_INT(Op, DAG); 4773 case ISD::SHL: 4774 case ISD::SRA: 4775 case ISD::SRL: 4776 case ISD::ADD: 4777 case ISD::SUB: 4778 case ISD::MUL: 4779 case ISD::SMIN: 4780 case ISD::SMAX: 4781 case ISD::UMIN: 4782 case ISD::UMAX: 4783 case ISD::FADD: 4784 case ISD::FMUL: 4785 case ISD::FMINNUM_IEEE: 4786 case ISD::FMAXNUM_IEEE: 4787 case ISD::UADDSAT: 4788 case ISD::USUBSAT: 4789 case ISD::SADDSAT: 4790 case ISD::SSUBSAT: 4791 return splitBinaryVectorOp(Op, DAG); 4792 case ISD::SMULO: 4793 case ISD::UMULO: 4794 return lowerXMULO(Op, DAG); 4795 case ISD::SMUL_LOHI: 4796 case ISD::UMUL_LOHI: 4797 return lowerXMUL_LOHI(Op, DAG); 4798 case ISD::DYNAMIC_STACKALLOC: 4799 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4800 } 4801 return SDValue(); 4802 } 4803 4804 // Used for D16: Casts the result of an instruction into the right vector, 4805 // packs values if loads return unpacked values. 4806 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4807 const SDLoc &DL, 4808 SelectionDAG &DAG, bool Unpacked) { 4809 if (!LoadVT.isVector()) 4810 return Result; 4811 4812 // Cast back to the original packed type or to a larger type that is a 4813 // multiple of 32 bit for D16. Widening the return type is a required for 4814 // legalization. 4815 EVT FittingLoadVT = LoadVT; 4816 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4817 FittingLoadVT = 4818 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4819 LoadVT.getVectorNumElements() + 1); 4820 } 4821 4822 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4823 // Truncate to v2i16/v4i16. 4824 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4825 4826 // Workaround legalizer not scalarizing truncate after vector op 4827 // legalization but not creating intermediate vector trunc. 4828 SmallVector<SDValue, 4> Elts; 4829 DAG.ExtractVectorElements(Result, Elts); 4830 for (SDValue &Elt : Elts) 4831 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4832 4833 // Pad illegal v1i16/v3fi6 to v4i16 4834 if ((LoadVT.getVectorNumElements() % 2) == 1) 4835 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4836 4837 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4838 4839 // Bitcast to original type (v2f16/v4f16). 4840 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4841 } 4842 4843 // Cast back to the original packed type. 4844 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4845 } 4846 4847 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4848 MemSDNode *M, 4849 SelectionDAG &DAG, 4850 ArrayRef<SDValue> Ops, 4851 bool IsIntrinsic) const { 4852 SDLoc DL(M); 4853 4854 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4855 EVT LoadVT = M->getValueType(0); 4856 4857 EVT EquivLoadVT = LoadVT; 4858 if (LoadVT.isVector()) { 4859 if (Unpacked) { 4860 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4861 LoadVT.getVectorNumElements()); 4862 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4863 // Widen v3f16 to legal type 4864 EquivLoadVT = 4865 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4866 LoadVT.getVectorNumElements() + 1); 4867 } 4868 } 4869 4870 // Change from v4f16/v2f16 to EquivLoadVT. 4871 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4872 4873 SDValue Load 4874 = DAG.getMemIntrinsicNode( 4875 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4876 VTList, Ops, M->getMemoryVT(), 4877 M->getMemOperand()); 4878 4879 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4880 4881 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4882 } 4883 4884 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4885 SelectionDAG &DAG, 4886 ArrayRef<SDValue> Ops) const { 4887 SDLoc DL(M); 4888 EVT LoadVT = M->getValueType(0); 4889 EVT EltType = LoadVT.getScalarType(); 4890 EVT IntVT = LoadVT.changeTypeToInteger(); 4891 4892 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4893 4894 unsigned Opc = 4895 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4896 4897 if (IsD16) { 4898 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4899 } 4900 4901 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4902 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4903 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4904 4905 if (isTypeLegal(LoadVT)) { 4906 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4907 M->getMemOperand(), DAG); 4908 } 4909 4910 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4911 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4912 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4913 M->getMemOperand(), DAG); 4914 return DAG.getMergeValues( 4915 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4916 DL); 4917 } 4918 4919 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4920 SDNode *N, SelectionDAG &DAG) { 4921 EVT VT = N->getValueType(0); 4922 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4923 unsigned CondCode = CD->getZExtValue(); 4924 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4925 return DAG.getUNDEF(VT); 4926 4927 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4928 4929 SDValue LHS = N->getOperand(1); 4930 SDValue RHS = N->getOperand(2); 4931 4932 SDLoc DL(N); 4933 4934 EVT CmpVT = LHS.getValueType(); 4935 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4936 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4937 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4938 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4939 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4940 } 4941 4942 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4943 4944 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4945 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4946 4947 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4948 DAG.getCondCode(CCOpcode)); 4949 if (VT.bitsEq(CCVT)) 4950 return SetCC; 4951 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4952 } 4953 4954 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4955 SDNode *N, SelectionDAG &DAG) { 4956 EVT VT = N->getValueType(0); 4957 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4958 4959 unsigned CondCode = CD->getZExtValue(); 4960 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4961 return DAG.getUNDEF(VT); 4962 4963 SDValue Src0 = N->getOperand(1); 4964 SDValue Src1 = N->getOperand(2); 4965 EVT CmpVT = Src0.getValueType(); 4966 SDLoc SL(N); 4967 4968 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4969 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4970 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4971 } 4972 4973 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4974 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4975 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4976 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4977 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4978 Src1, DAG.getCondCode(CCOpcode)); 4979 if (VT.bitsEq(CCVT)) 4980 return SetCC; 4981 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4982 } 4983 4984 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4985 SelectionDAG &DAG) { 4986 EVT VT = N->getValueType(0); 4987 SDValue Src = N->getOperand(1); 4988 SDLoc SL(N); 4989 4990 if (Src.getOpcode() == ISD::SETCC) { 4991 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4992 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4993 Src.getOperand(1), Src.getOperand(2)); 4994 } 4995 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4996 // (ballot 0) -> 0 4997 if (Arg->isZero()) 4998 return DAG.getConstant(0, SL, VT); 4999 5000 // (ballot 1) -> EXEC/EXEC_LO 5001 if (Arg->isOne()) { 5002 Register Exec; 5003 if (VT.getScalarSizeInBits() == 32) 5004 Exec = AMDGPU::EXEC_LO; 5005 else if (VT.getScalarSizeInBits() == 64) 5006 Exec = AMDGPU::EXEC; 5007 else 5008 return SDValue(); 5009 5010 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 5011 } 5012 } 5013 5014 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5015 // ISD::SETNE) 5016 return DAG.getNode( 5017 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5018 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5019 } 5020 5021 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5022 SmallVectorImpl<SDValue> &Results, 5023 SelectionDAG &DAG) const { 5024 switch (N->getOpcode()) { 5025 case ISD::INSERT_VECTOR_ELT: { 5026 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5027 Results.push_back(Res); 5028 return; 5029 } 5030 case ISD::EXTRACT_VECTOR_ELT: { 5031 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5032 Results.push_back(Res); 5033 return; 5034 } 5035 case ISD::INTRINSIC_WO_CHAIN: { 5036 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5037 switch (IID) { 5038 case Intrinsic::amdgcn_cvt_pkrtz: { 5039 SDValue Src0 = N->getOperand(1); 5040 SDValue Src1 = N->getOperand(2); 5041 SDLoc SL(N); 5042 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5043 Src0, Src1); 5044 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5045 return; 5046 } 5047 case Intrinsic::amdgcn_cvt_pknorm_i16: 5048 case Intrinsic::amdgcn_cvt_pknorm_u16: 5049 case Intrinsic::amdgcn_cvt_pk_i16: 5050 case Intrinsic::amdgcn_cvt_pk_u16: { 5051 SDValue Src0 = N->getOperand(1); 5052 SDValue Src1 = N->getOperand(2); 5053 SDLoc SL(N); 5054 unsigned Opcode; 5055 5056 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5057 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5058 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5059 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5060 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5061 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5062 else 5063 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5064 5065 EVT VT = N->getValueType(0); 5066 if (isTypeLegal(VT)) 5067 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5068 else { 5069 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5070 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5071 } 5072 return; 5073 } 5074 } 5075 break; 5076 } 5077 case ISD::INTRINSIC_W_CHAIN: { 5078 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5079 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5080 // FIXME: Hacky 5081 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5082 Results.push_back(Res.getOperand(I)); 5083 } 5084 } else { 5085 Results.push_back(Res); 5086 Results.push_back(Res.getValue(1)); 5087 } 5088 return; 5089 } 5090 5091 break; 5092 } 5093 case ISD::SELECT: { 5094 SDLoc SL(N); 5095 EVT VT = N->getValueType(0); 5096 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5097 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5098 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5099 5100 EVT SelectVT = NewVT; 5101 if (NewVT.bitsLT(MVT::i32)) { 5102 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5103 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5104 SelectVT = MVT::i32; 5105 } 5106 5107 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5108 N->getOperand(0), LHS, RHS); 5109 5110 if (NewVT != SelectVT) 5111 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5112 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5113 return; 5114 } 5115 case ISD::FNEG: { 5116 if (N->getValueType(0) != MVT::v2f16) 5117 break; 5118 5119 SDLoc SL(N); 5120 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5121 5122 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5123 BC, 5124 DAG.getConstant(0x80008000, SL, MVT::i32)); 5125 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5126 return; 5127 } 5128 case ISD::FABS: { 5129 if (N->getValueType(0) != MVT::v2f16) 5130 break; 5131 5132 SDLoc SL(N); 5133 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5134 5135 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5136 BC, 5137 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5138 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5139 return; 5140 } 5141 default: 5142 break; 5143 } 5144 } 5145 5146 /// Helper function for LowerBRCOND 5147 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5148 5149 SDNode *Parent = Value.getNode(); 5150 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5151 I != E; ++I) { 5152 5153 if (I.getUse().get() != Value) 5154 continue; 5155 5156 if (I->getOpcode() == Opcode) 5157 return *I; 5158 } 5159 return nullptr; 5160 } 5161 5162 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5163 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5164 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5165 case Intrinsic::amdgcn_if: 5166 return AMDGPUISD::IF; 5167 case Intrinsic::amdgcn_else: 5168 return AMDGPUISD::ELSE; 5169 case Intrinsic::amdgcn_loop: 5170 return AMDGPUISD::LOOP; 5171 case Intrinsic::amdgcn_end_cf: 5172 llvm_unreachable("should not occur"); 5173 default: 5174 return 0; 5175 } 5176 } 5177 5178 // break, if_break, else_break are all only used as inputs to loop, not 5179 // directly as branch conditions. 5180 return 0; 5181 } 5182 5183 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5184 const Triple &TT = getTargetMachine().getTargetTriple(); 5185 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5186 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5187 AMDGPU::shouldEmitConstantsToTextSection(TT); 5188 } 5189 5190 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5191 // FIXME: Either avoid relying on address space here or change the default 5192 // address space for functions to avoid the explicit check. 5193 return (GV->getValueType()->isFunctionTy() || 5194 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5195 !shouldEmitFixup(GV) && 5196 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5197 } 5198 5199 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5200 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5201 } 5202 5203 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5204 if (!GV->hasExternalLinkage()) 5205 return true; 5206 5207 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5208 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5209 } 5210 5211 /// This transforms the control flow intrinsics to get the branch destination as 5212 /// last parameter, also switches branch target with BR if the need arise 5213 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5214 SelectionDAG &DAG) const { 5215 SDLoc DL(BRCOND); 5216 5217 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5218 SDValue Target = BRCOND.getOperand(2); 5219 SDNode *BR = nullptr; 5220 SDNode *SetCC = nullptr; 5221 5222 if (Intr->getOpcode() == ISD::SETCC) { 5223 // As long as we negate the condition everything is fine 5224 SetCC = Intr; 5225 Intr = SetCC->getOperand(0).getNode(); 5226 5227 } else { 5228 // Get the target from BR if we don't negate the condition 5229 BR = findUser(BRCOND, ISD::BR); 5230 assert(BR && "brcond missing unconditional branch user"); 5231 Target = BR->getOperand(1); 5232 } 5233 5234 unsigned CFNode = isCFIntrinsic(Intr); 5235 if (CFNode == 0) { 5236 // This is a uniform branch so we don't need to legalize. 5237 return BRCOND; 5238 } 5239 5240 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5241 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5242 5243 assert(!SetCC || 5244 (SetCC->getConstantOperandVal(1) == 1 && 5245 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5246 ISD::SETNE)); 5247 5248 // operands of the new intrinsic call 5249 SmallVector<SDValue, 4> Ops; 5250 if (HaveChain) 5251 Ops.push_back(BRCOND.getOperand(0)); 5252 5253 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5254 Ops.push_back(Target); 5255 5256 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5257 5258 // build the new intrinsic call 5259 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5260 5261 if (!HaveChain) { 5262 SDValue Ops[] = { 5263 SDValue(Result, 0), 5264 BRCOND.getOperand(0) 5265 }; 5266 5267 Result = DAG.getMergeValues(Ops, DL).getNode(); 5268 } 5269 5270 if (BR) { 5271 // Give the branch instruction our target 5272 SDValue Ops[] = { 5273 BR->getOperand(0), 5274 BRCOND.getOperand(2) 5275 }; 5276 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5277 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5278 } 5279 5280 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5281 5282 // Copy the intrinsic results to registers 5283 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5284 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5285 if (!CopyToReg) 5286 continue; 5287 5288 Chain = DAG.getCopyToReg( 5289 Chain, DL, 5290 CopyToReg->getOperand(1), 5291 SDValue(Result, i - 1), 5292 SDValue()); 5293 5294 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5295 } 5296 5297 // Remove the old intrinsic from the chain 5298 DAG.ReplaceAllUsesOfValueWith( 5299 SDValue(Intr, Intr->getNumValues() - 1), 5300 Intr->getOperand(0)); 5301 5302 return Chain; 5303 } 5304 5305 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5306 SelectionDAG &DAG) const { 5307 MVT VT = Op.getSimpleValueType(); 5308 SDLoc DL(Op); 5309 // Checking the depth 5310 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5311 return DAG.getConstant(0, DL, VT); 5312 5313 MachineFunction &MF = DAG.getMachineFunction(); 5314 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5315 // Check for kernel and shader functions 5316 if (Info->isEntryFunction()) 5317 return DAG.getConstant(0, DL, VT); 5318 5319 MachineFrameInfo &MFI = MF.getFrameInfo(); 5320 // There is a call to @llvm.returnaddress in this function 5321 MFI.setReturnAddressIsTaken(true); 5322 5323 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5324 // Get the return address reg and mark it as an implicit live-in 5325 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5326 5327 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5328 } 5329 5330 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5331 SDValue Op, 5332 const SDLoc &DL, 5333 EVT VT) const { 5334 return Op.getValueType().bitsLE(VT) ? 5335 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5336 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5337 DAG.getTargetConstant(0, DL, MVT::i32)); 5338 } 5339 5340 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5341 assert(Op.getValueType() == MVT::f16 && 5342 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5343 5344 SDValue Src = Op.getOperand(0); 5345 EVT SrcVT = Src.getValueType(); 5346 if (SrcVT != MVT::f64) 5347 return Op; 5348 5349 SDLoc DL(Op); 5350 5351 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5352 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5353 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5354 } 5355 5356 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5357 SelectionDAG &DAG) const { 5358 EVT VT = Op.getValueType(); 5359 const MachineFunction &MF = DAG.getMachineFunction(); 5360 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5361 bool IsIEEEMode = Info->getMode().IEEE; 5362 5363 // FIXME: Assert during selection that this is only selected for 5364 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5365 // mode functions, but this happens to be OK since it's only done in cases 5366 // where there is known no sNaN. 5367 if (IsIEEEMode) 5368 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5369 5370 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5371 return splitBinaryVectorOp(Op, DAG); 5372 return Op; 5373 } 5374 5375 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5376 EVT VT = Op.getValueType(); 5377 SDLoc SL(Op); 5378 SDValue LHS = Op.getOperand(0); 5379 SDValue RHS = Op.getOperand(1); 5380 bool isSigned = Op.getOpcode() == ISD::SMULO; 5381 5382 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5383 const APInt &C = RHSC->getAPIntValue(); 5384 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5385 if (C.isPowerOf2()) { 5386 // smulo(x, signed_min) is same as umulo(x, signed_min). 5387 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5388 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5389 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5390 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5391 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5392 SL, VT, Result, ShiftAmt), 5393 LHS, ISD::SETNE); 5394 return DAG.getMergeValues({ Result, Overflow }, SL); 5395 } 5396 } 5397 5398 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5399 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5400 SL, VT, LHS, RHS); 5401 5402 SDValue Sign = isSigned 5403 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5404 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5405 : DAG.getConstant(0, SL, VT); 5406 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5407 5408 return DAG.getMergeValues({ Result, Overflow }, SL); 5409 } 5410 5411 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5412 if (Op->isDivergent()) { 5413 // Select to V_MAD_[IU]64_[IU]32. 5414 return Op; 5415 } 5416 if (Subtarget->hasSMulHi()) { 5417 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5418 return SDValue(); 5419 } 5420 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5421 // calculate the high part, so we might as well do the whole thing with 5422 // V_MAD_[IU]64_[IU]32. 5423 return Op; 5424 } 5425 5426 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5427 if (!Subtarget->isTrapHandlerEnabled() || 5428 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5429 return lowerTrapEndpgm(Op, DAG); 5430 5431 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5432 switch (*HsaAbiVer) { 5433 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5434 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5435 return lowerTrapHsaQueuePtr(Op, DAG); 5436 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5437 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5438 return Subtarget->supportsGetDoorbellID() ? 5439 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5440 } 5441 } 5442 5443 llvm_unreachable("Unknown trap handler"); 5444 } 5445 5446 SDValue SITargetLowering::lowerTrapEndpgm( 5447 SDValue Op, SelectionDAG &DAG) const { 5448 SDLoc SL(Op); 5449 SDValue Chain = Op.getOperand(0); 5450 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5451 } 5452 5453 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5454 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5455 MachineFunction &MF = DAG.getMachineFunction(); 5456 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5457 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5458 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5459 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5460 MachineMemOperand::MODereferenceable | 5461 MachineMemOperand::MOInvariant); 5462 } 5463 5464 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5465 SDValue Op, SelectionDAG &DAG) const { 5466 SDLoc SL(Op); 5467 SDValue Chain = Op.getOperand(0); 5468 5469 SDValue QueuePtr; 5470 // For code object version 5, QueuePtr is passed through implicit kernarg. 5471 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5472 QueuePtr = 5473 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5474 } else { 5475 MachineFunction &MF = DAG.getMachineFunction(); 5476 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5477 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5478 5479 if (UserSGPR == AMDGPU::NoRegister) { 5480 // We probably are in a function incorrectly marked with 5481 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5482 // trap, so just use a null pointer. 5483 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5484 } else { 5485 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5486 MVT::i64); 5487 } 5488 } 5489 5490 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5491 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5492 QueuePtr, SDValue()); 5493 5494 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5495 SDValue Ops[] = { 5496 ToReg, 5497 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5498 SGPR01, 5499 ToReg.getValue(1) 5500 }; 5501 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5502 } 5503 5504 SDValue SITargetLowering::lowerTrapHsa( 5505 SDValue Op, SelectionDAG &DAG) const { 5506 SDLoc SL(Op); 5507 SDValue Chain = Op.getOperand(0); 5508 5509 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5510 SDValue Ops[] = { 5511 Chain, 5512 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5513 }; 5514 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5515 } 5516 5517 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5518 SDLoc SL(Op); 5519 SDValue Chain = Op.getOperand(0); 5520 MachineFunction &MF = DAG.getMachineFunction(); 5521 5522 if (!Subtarget->isTrapHandlerEnabled() || 5523 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5524 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5525 "debugtrap handler not supported", 5526 Op.getDebugLoc(), 5527 DS_Warning); 5528 LLVMContext &Ctx = MF.getFunction().getContext(); 5529 Ctx.diagnose(NoTrap); 5530 return Chain; 5531 } 5532 5533 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5534 SDValue Ops[] = { 5535 Chain, 5536 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5537 }; 5538 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5539 } 5540 5541 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5542 SelectionDAG &DAG) const { 5543 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5544 if (Subtarget->hasApertureRegs()) { 5545 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5546 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5547 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5548 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5549 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5550 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5551 unsigned Encoding = 5552 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5553 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5554 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5555 5556 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5557 SDValue ApertureReg = SDValue( 5558 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5559 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5560 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5561 } 5562 5563 // For code object version 5, private_base and shared_base are passed through 5564 // implicit kernargs. 5565 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5566 ImplicitParameter Param = 5567 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5568 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5569 } 5570 5571 MachineFunction &MF = DAG.getMachineFunction(); 5572 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5573 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5574 if (UserSGPR == AMDGPU::NoRegister) { 5575 // We probably are in a function incorrectly marked with 5576 // amdgpu-no-queue-ptr. This is undefined. 5577 return DAG.getUNDEF(MVT::i32); 5578 } 5579 5580 SDValue QueuePtr = CreateLiveInRegister( 5581 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5582 5583 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5584 // private_segment_aperture_base_hi. 5585 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5586 5587 SDValue Ptr = 5588 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5589 5590 // TODO: Use custom target PseudoSourceValue. 5591 // TODO: We should use the value from the IR intrinsic call, but it might not 5592 // be available and how do we get it? 5593 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5594 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5595 commonAlignment(Align(64), StructOffset), 5596 MachineMemOperand::MODereferenceable | 5597 MachineMemOperand::MOInvariant); 5598 } 5599 5600 /// Return true if the value is a known valid address, such that a null check is 5601 /// not necessary. 5602 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5603 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5604 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5605 isa<BasicBlockSDNode>(Val)) 5606 return true; 5607 5608 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5609 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5610 5611 // TODO: Search through arithmetic, handle arguments and loads 5612 // marked nonnull. 5613 return false; 5614 } 5615 5616 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5617 SelectionDAG &DAG) const { 5618 SDLoc SL(Op); 5619 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5620 5621 SDValue Src = ASC->getOperand(0); 5622 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5623 unsigned SrcAS = ASC->getSrcAddressSpace(); 5624 5625 const AMDGPUTargetMachine &TM = 5626 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5627 5628 // flat -> local/private 5629 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5630 unsigned DestAS = ASC->getDestAddressSpace(); 5631 5632 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5633 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5634 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5635 5636 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5637 return Ptr; 5638 5639 unsigned NullVal = TM.getNullPointerValue(DestAS); 5640 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5641 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5642 5643 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5644 SegmentNullPtr); 5645 } 5646 } 5647 5648 // local/private -> flat 5649 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5650 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5651 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5652 5653 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5654 SDValue CvtPtr = 5655 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5656 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5657 5658 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5659 return CvtPtr; 5660 5661 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5662 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5663 5664 SDValue NonNull 5665 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5666 5667 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5668 FlatNullPtr); 5669 } 5670 } 5671 5672 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5673 Op.getValueType() == MVT::i64) { 5674 const SIMachineFunctionInfo *Info = 5675 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5676 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5677 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5678 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5679 } 5680 5681 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5682 Src.getValueType() == MVT::i64) 5683 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5684 5685 // global <-> flat are no-ops and never emitted. 5686 5687 const MachineFunction &MF = DAG.getMachineFunction(); 5688 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5689 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5690 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5691 5692 return DAG.getUNDEF(ASC->getValueType(0)); 5693 } 5694 5695 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5696 // the small vector and inserting them into the big vector. That is better than 5697 // the default expansion of doing it via a stack slot. Even though the use of 5698 // the stack slot would be optimized away afterwards, the stack slot itself 5699 // remains. 5700 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5701 SelectionDAG &DAG) const { 5702 SDValue Vec = Op.getOperand(0); 5703 SDValue Ins = Op.getOperand(1); 5704 SDValue Idx = Op.getOperand(2); 5705 EVT VecVT = Vec.getValueType(); 5706 EVT InsVT = Ins.getValueType(); 5707 EVT EltVT = VecVT.getVectorElementType(); 5708 unsigned InsNumElts = InsVT.getVectorNumElements(); 5709 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5710 SDLoc SL(Op); 5711 5712 for (unsigned I = 0; I != InsNumElts; ++I) { 5713 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5714 DAG.getConstant(I, SL, MVT::i32)); 5715 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5716 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5717 } 5718 return Vec; 5719 } 5720 5721 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5722 SelectionDAG &DAG) const { 5723 SDValue Vec = Op.getOperand(0); 5724 SDValue InsVal = Op.getOperand(1); 5725 SDValue Idx = Op.getOperand(2); 5726 EVT VecVT = Vec.getValueType(); 5727 EVT EltVT = VecVT.getVectorElementType(); 5728 unsigned VecSize = VecVT.getSizeInBits(); 5729 unsigned EltSize = EltVT.getSizeInBits(); 5730 5731 5732 assert(VecSize <= 64); 5733 5734 unsigned NumElts = VecVT.getVectorNumElements(); 5735 SDLoc SL(Op); 5736 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5737 5738 if (NumElts == 4 && EltSize == 16 && KIdx) { 5739 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5740 5741 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5742 DAG.getConstant(0, SL, MVT::i32)); 5743 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5744 DAG.getConstant(1, SL, MVT::i32)); 5745 5746 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5747 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5748 5749 unsigned Idx = KIdx->getZExtValue(); 5750 bool InsertLo = Idx < 2; 5751 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5752 InsertLo ? LoVec : HiVec, 5753 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5754 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5755 5756 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5757 5758 SDValue Concat = InsertLo ? 5759 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5760 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5761 5762 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5763 } 5764 5765 if (isa<ConstantSDNode>(Idx)) 5766 return SDValue(); 5767 5768 MVT IntVT = MVT::getIntegerVT(VecSize); 5769 5770 // Avoid stack access for dynamic indexing. 5771 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5772 5773 // Create a congruent vector with the target value in each element so that 5774 // the required element can be masked and ORed into the target vector. 5775 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5776 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5777 5778 assert(isPowerOf2_32(EltSize)); 5779 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5780 5781 // Convert vector index to bit-index. 5782 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5783 5784 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5785 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5786 DAG.getConstant(0xffff, SL, IntVT), 5787 ScaledIdx); 5788 5789 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5790 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5791 DAG.getNOT(SL, BFM, IntVT), BCVec); 5792 5793 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5794 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5795 } 5796 5797 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5798 SelectionDAG &DAG) const { 5799 SDLoc SL(Op); 5800 5801 EVT ResultVT = Op.getValueType(); 5802 SDValue Vec = Op.getOperand(0); 5803 SDValue Idx = Op.getOperand(1); 5804 EVT VecVT = Vec.getValueType(); 5805 unsigned VecSize = VecVT.getSizeInBits(); 5806 EVT EltVT = VecVT.getVectorElementType(); 5807 5808 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5809 5810 // Make sure we do any optimizations that will make it easier to fold 5811 // source modifiers before obscuring it with bit operations. 5812 5813 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5814 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5815 return Combined; 5816 5817 if (VecSize == 128) { 5818 SDValue Lo, Hi; 5819 EVT LoVT, HiVT; 5820 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5821 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5822 Lo = 5823 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5824 V2, DAG.getConstant(0, SL, MVT::i32))); 5825 Hi = 5826 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5827 V2, DAG.getConstant(1, SL, MVT::i32))); 5828 EVT IdxVT = Idx.getValueType(); 5829 unsigned NElem = VecVT.getVectorNumElements(); 5830 assert(isPowerOf2_32(NElem)); 5831 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5832 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5833 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5835 } 5836 5837 assert(VecSize <= 64); 5838 5839 unsigned EltSize = EltVT.getSizeInBits(); 5840 assert(isPowerOf2_32(EltSize)); 5841 5842 MVT IntVT = MVT::getIntegerVT(VecSize); 5843 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5844 5845 // Convert vector index to bit-index (* EltSize) 5846 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5847 5848 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5849 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5850 5851 if (ResultVT == MVT::f16) { 5852 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5853 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5854 } 5855 5856 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5857 } 5858 5859 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5860 assert(Elt % 2 == 0); 5861 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5862 } 5863 5864 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5865 SelectionDAG &DAG) const { 5866 SDLoc SL(Op); 5867 EVT ResultVT = Op.getValueType(); 5868 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5869 5870 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5871 EVT EltVT = PackVT.getVectorElementType(); 5872 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5873 5874 // vector_shuffle <0,1,6,7> lhs, rhs 5875 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5876 // 5877 // vector_shuffle <6,7,2,3> lhs, rhs 5878 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5879 // 5880 // vector_shuffle <6,7,0,1> lhs, rhs 5881 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5882 5883 // Avoid scalarizing when both halves are reading from consecutive elements. 5884 SmallVector<SDValue, 4> Pieces; 5885 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5886 if (elementPairIsContiguous(SVN->getMask(), I)) { 5887 const int Idx = SVN->getMaskElt(I); 5888 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5889 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5890 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5891 PackVT, SVN->getOperand(VecIdx), 5892 DAG.getConstant(EltIdx, SL, MVT::i32)); 5893 Pieces.push_back(SubVec); 5894 } else { 5895 const int Idx0 = SVN->getMaskElt(I); 5896 const int Idx1 = SVN->getMaskElt(I + 1); 5897 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5898 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5899 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5900 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5901 5902 SDValue Vec0 = SVN->getOperand(VecIdx0); 5903 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5904 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5905 5906 SDValue Vec1 = SVN->getOperand(VecIdx1); 5907 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5908 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5909 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5910 } 5911 } 5912 5913 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5914 } 5915 5916 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5917 SelectionDAG &DAG) const { 5918 SDLoc SL(Op); 5919 EVT VT = Op.getValueType(); 5920 5921 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5922 VT == MVT::v8i16 || VT == MVT::v8f16) { 5923 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5924 VT.getVectorNumElements() / 2); 5925 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5926 5927 // Turn into pair of packed build_vectors. 5928 // TODO: Special case for constants that can be materialized with s_mov_b64. 5929 SmallVector<SDValue, 4> LoOps, HiOps; 5930 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 5931 LoOps.push_back(Op.getOperand(I)); 5932 HiOps.push_back(Op.getOperand(I + E)); 5933 } 5934 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 5935 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 5936 5937 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 5938 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 5939 5940 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 5941 { CastLo, CastHi }); 5942 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5943 } 5944 5945 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5946 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5947 5948 SDValue Lo = Op.getOperand(0); 5949 SDValue Hi = Op.getOperand(1); 5950 5951 // Avoid adding defined bits with the zero_extend. 5952 if (Hi.isUndef()) { 5953 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5954 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5955 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5956 } 5957 5958 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5959 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5960 5961 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5962 DAG.getConstant(16, SL, MVT::i32)); 5963 if (Lo.isUndef()) 5964 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5965 5966 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5967 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5968 5969 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5970 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5971 } 5972 5973 bool 5974 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5975 // We can fold offsets for anything that doesn't require a GOT relocation. 5976 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5977 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5978 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5979 !shouldEmitGOTReloc(GA->getGlobal()); 5980 } 5981 5982 static SDValue 5983 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5984 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5985 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5986 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5987 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5988 // lowered to the following code sequence: 5989 // 5990 // For constant address space: 5991 // s_getpc_b64 s[0:1] 5992 // s_add_u32 s0, s0, $symbol 5993 // s_addc_u32 s1, s1, 0 5994 // 5995 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5996 // a fixup or relocation is emitted to replace $symbol with a literal 5997 // constant, which is a pc-relative offset from the encoding of the $symbol 5998 // operand to the global variable. 5999 // 6000 // For global address space: 6001 // s_getpc_b64 s[0:1] 6002 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 6003 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 6004 // 6005 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6006 // fixups or relocations are emitted to replace $symbol@*@lo and 6007 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 6008 // which is a 64-bit pc-relative offset from the encoding of the $symbol 6009 // operand to the global variable. 6010 // 6011 // What we want here is an offset from the value returned by s_getpc 6012 // (which is the address of the s_add_u32 instruction) to the global 6013 // variable, but since the encoding of $symbol starts 4 bytes after the start 6014 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 6015 // small. This requires us to add 4 to the global variable offset in order to 6016 // compute the correct address. Similarly for the s_addc_u32 instruction, the 6017 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 6018 // instruction. 6019 SDValue PtrLo = 6020 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 6021 SDValue PtrHi; 6022 if (GAFlags == SIInstrInfo::MO_NONE) { 6023 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 6024 } else { 6025 PtrHi = 6026 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 6027 } 6028 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 6029 } 6030 6031 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 6032 SDValue Op, 6033 SelectionDAG &DAG) const { 6034 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 6035 SDLoc DL(GSD); 6036 EVT PtrVT = Op.getValueType(); 6037 6038 const GlobalValue *GV = GSD->getGlobal(); 6039 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6040 shouldUseLDSConstAddress(GV)) || 6041 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6042 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6043 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6044 GV->hasExternalLinkage()) { 6045 Type *Ty = GV->getValueType(); 6046 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6047 // zero-sized type in other languages to declare the dynamic shared 6048 // memory which size is not known at the compile time. They will be 6049 // allocated by the runtime and placed directly after the static 6050 // allocated ones. They all share the same offset. 6051 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6052 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6053 // Adjust alignment for that dynamic shared memory array. 6054 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6055 return SDValue( 6056 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6057 } 6058 } 6059 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6060 } 6061 6062 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6063 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6064 SIInstrInfo::MO_ABS32_LO); 6065 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6066 } 6067 6068 if (shouldEmitFixup(GV)) 6069 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6070 else if (shouldEmitPCReloc(GV)) 6071 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6072 SIInstrInfo::MO_REL32); 6073 6074 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6075 SIInstrInfo::MO_GOTPCREL32); 6076 6077 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6078 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6079 const DataLayout &DataLayout = DAG.getDataLayout(); 6080 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6081 MachinePointerInfo PtrInfo 6082 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6083 6084 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6085 MachineMemOperand::MODereferenceable | 6086 MachineMemOperand::MOInvariant); 6087 } 6088 6089 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6090 const SDLoc &DL, SDValue V) const { 6091 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6092 // the destination register. 6093 // 6094 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6095 // so we will end up with redundant moves to m0. 6096 // 6097 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6098 6099 // A Null SDValue creates a glue result. 6100 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6101 V, Chain); 6102 return SDValue(M0, 0); 6103 } 6104 6105 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6106 SDValue Op, 6107 MVT VT, 6108 unsigned Offset) const { 6109 SDLoc SL(Op); 6110 SDValue Param = lowerKernargMemParameter( 6111 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6112 // The local size values will have the hi 16-bits as zero. 6113 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6114 DAG.getValueType(VT)); 6115 } 6116 6117 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6118 EVT VT) { 6119 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6120 "non-hsa intrinsic with hsa target", 6121 DL.getDebugLoc()); 6122 DAG.getContext()->diagnose(BadIntrin); 6123 return DAG.getUNDEF(VT); 6124 } 6125 6126 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6127 EVT VT) { 6128 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6129 "intrinsic not supported on subtarget", 6130 DL.getDebugLoc()); 6131 DAG.getContext()->diagnose(BadIntrin); 6132 return DAG.getUNDEF(VT); 6133 } 6134 6135 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6136 ArrayRef<SDValue> Elts) { 6137 assert(!Elts.empty()); 6138 MVT Type; 6139 unsigned NumElts = Elts.size(); 6140 6141 if (NumElts <= 8) { 6142 Type = MVT::getVectorVT(MVT::f32, NumElts); 6143 } else { 6144 assert(Elts.size() <= 16); 6145 Type = MVT::v16f32; 6146 NumElts = 16; 6147 } 6148 6149 SmallVector<SDValue, 16> VecElts(NumElts); 6150 for (unsigned i = 0; i < Elts.size(); ++i) { 6151 SDValue Elt = Elts[i]; 6152 if (Elt.getValueType() != MVT::f32) 6153 Elt = DAG.getBitcast(MVT::f32, Elt); 6154 VecElts[i] = Elt; 6155 } 6156 for (unsigned i = Elts.size(); i < NumElts; ++i) 6157 VecElts[i] = DAG.getUNDEF(MVT::f32); 6158 6159 if (NumElts == 1) 6160 return VecElts[0]; 6161 return DAG.getBuildVector(Type, DL, VecElts); 6162 } 6163 6164 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6165 SDValue Src, int ExtraElts) { 6166 EVT SrcVT = Src.getValueType(); 6167 6168 SmallVector<SDValue, 8> Elts; 6169 6170 if (SrcVT.isVector()) 6171 DAG.ExtractVectorElements(Src, Elts); 6172 else 6173 Elts.push_back(Src); 6174 6175 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6176 while (ExtraElts--) 6177 Elts.push_back(Undef); 6178 6179 return DAG.getBuildVector(CastVT, DL, Elts); 6180 } 6181 6182 // Re-construct the required return value for a image load intrinsic. 6183 // This is more complicated due to the optional use TexFailCtrl which means the required 6184 // return type is an aggregate 6185 static SDValue constructRetValue(SelectionDAG &DAG, 6186 MachineSDNode *Result, 6187 ArrayRef<EVT> ResultTypes, 6188 bool IsTexFail, bool Unpacked, bool IsD16, 6189 int DMaskPop, int NumVDataDwords, 6190 const SDLoc &DL) { 6191 // Determine the required return type. This is the same regardless of IsTexFail flag 6192 EVT ReqRetVT = ResultTypes[0]; 6193 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6194 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6195 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6196 6197 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6198 DMaskPop : (DMaskPop + 1) / 2; 6199 6200 MVT DataDwordVT = NumDataDwords == 1 ? 6201 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6202 6203 MVT MaskPopVT = MaskPopDwords == 1 ? 6204 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6205 6206 SDValue Data(Result, 0); 6207 SDValue TexFail; 6208 6209 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6210 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6211 if (MaskPopVT.isVector()) { 6212 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6213 SDValue(Result, 0), ZeroIdx); 6214 } else { 6215 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6216 SDValue(Result, 0), ZeroIdx); 6217 } 6218 } 6219 6220 if (DataDwordVT.isVector()) 6221 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6222 NumDataDwords - MaskPopDwords); 6223 6224 if (IsD16) 6225 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6226 6227 EVT LegalReqRetVT = ReqRetVT; 6228 if (!ReqRetVT.isVector()) { 6229 if (!Data.getValueType().isInteger()) 6230 Data = DAG.getNode(ISD::BITCAST, DL, 6231 Data.getValueType().changeTypeToInteger(), Data); 6232 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6233 } else { 6234 // We need to widen the return vector to a legal type 6235 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6236 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6237 LegalReqRetVT = 6238 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6239 ReqRetVT.getVectorNumElements() + 1); 6240 } 6241 } 6242 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6243 6244 if (IsTexFail) { 6245 TexFail = 6246 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6247 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6248 6249 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6250 } 6251 6252 if (Result->getNumValues() == 1) 6253 return Data; 6254 6255 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6256 } 6257 6258 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6259 SDValue *LWE, bool &IsTexFail) { 6260 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6261 6262 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6263 if (Value) { 6264 IsTexFail = true; 6265 } 6266 6267 SDLoc DL(TexFailCtrlConst); 6268 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6269 Value &= ~(uint64_t)0x1; 6270 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6271 Value &= ~(uint64_t)0x2; 6272 6273 return Value == 0; 6274 } 6275 6276 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6277 MVT PackVectorVT, 6278 SmallVectorImpl<SDValue> &PackedAddrs, 6279 unsigned DimIdx, unsigned EndIdx, 6280 unsigned NumGradients) { 6281 SDLoc DL(Op); 6282 for (unsigned I = DimIdx; I < EndIdx; I++) { 6283 SDValue Addr = Op.getOperand(I); 6284 6285 // Gradients are packed with undef for each coordinate. 6286 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6287 // 1D: undef,dx/dh; undef,dx/dv 6288 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6289 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6290 if (((I + 1) >= EndIdx) || 6291 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6292 I == DimIdx + NumGradients - 1))) { 6293 if (Addr.getValueType() != MVT::i16) 6294 Addr = DAG.getBitcast(MVT::i16, Addr); 6295 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6296 } else { 6297 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6298 I++; 6299 } 6300 Addr = DAG.getBitcast(MVT::f32, Addr); 6301 PackedAddrs.push_back(Addr); 6302 } 6303 } 6304 6305 SDValue SITargetLowering::lowerImage(SDValue Op, 6306 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6307 SelectionDAG &DAG, bool WithChain) const { 6308 SDLoc DL(Op); 6309 MachineFunction &MF = DAG.getMachineFunction(); 6310 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6311 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6312 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6313 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6314 unsigned IntrOpcode = Intr->BaseOpcode; 6315 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6316 6317 SmallVector<EVT, 3> ResultTypes(Op->values()); 6318 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6319 bool IsD16 = false; 6320 bool IsG16 = false; 6321 bool IsA16 = false; 6322 SDValue VData; 6323 int NumVDataDwords; 6324 bool AdjustRetType = false; 6325 6326 // Offset of intrinsic arguments 6327 const unsigned ArgOffset = WithChain ? 2 : 1; 6328 6329 unsigned DMask; 6330 unsigned DMaskLanes = 0; 6331 6332 if (BaseOpcode->Atomic) { 6333 VData = Op.getOperand(2); 6334 6335 bool Is64Bit = VData.getValueType() == MVT::i64; 6336 if (BaseOpcode->AtomicX2) { 6337 SDValue VData2 = Op.getOperand(3); 6338 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6339 {VData, VData2}); 6340 if (Is64Bit) 6341 VData = DAG.getBitcast(MVT::v4i32, VData); 6342 6343 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6344 DMask = Is64Bit ? 0xf : 0x3; 6345 NumVDataDwords = Is64Bit ? 4 : 2; 6346 } else { 6347 DMask = Is64Bit ? 0x3 : 0x1; 6348 NumVDataDwords = Is64Bit ? 2 : 1; 6349 } 6350 } else { 6351 auto *DMaskConst = 6352 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6353 DMask = DMaskConst->getZExtValue(); 6354 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6355 6356 if (BaseOpcode->Store) { 6357 VData = Op.getOperand(2); 6358 6359 MVT StoreVT = VData.getSimpleValueType(); 6360 if (StoreVT.getScalarType() == MVT::f16) { 6361 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6362 return Op; // D16 is unsupported for this instruction 6363 6364 IsD16 = true; 6365 VData = handleD16VData(VData, DAG, true); 6366 } 6367 6368 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6369 } else { 6370 // Work out the num dwords based on the dmask popcount and underlying type 6371 // and whether packing is supported. 6372 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6373 if (LoadVT.getScalarType() == MVT::f16) { 6374 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6375 return Op; // D16 is unsupported for this instruction 6376 6377 IsD16 = true; 6378 } 6379 6380 // Confirm that the return type is large enough for the dmask specified 6381 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6382 (!LoadVT.isVector() && DMaskLanes > 1)) 6383 return Op; 6384 6385 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6386 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6387 // instructions. 6388 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6389 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6390 NumVDataDwords = (DMaskLanes + 1) / 2; 6391 else 6392 NumVDataDwords = DMaskLanes; 6393 6394 AdjustRetType = true; 6395 } 6396 } 6397 6398 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6399 SmallVector<SDValue, 4> VAddrs; 6400 6401 // Check for 16 bit addresses or derivatives and pack if true. 6402 MVT VAddrVT = 6403 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6404 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6405 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6406 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6407 6408 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6409 VAddrScalarVT = VAddrVT.getScalarType(); 6410 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6411 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6412 6413 // Push back extra arguments. 6414 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6415 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6416 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6417 // Special handling of bias when A16 is on. Bias is of type half but 6418 // occupies full 32-bit. 6419 SDValue Bias = DAG.getBuildVector( 6420 MVT::v2f16, DL, 6421 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6422 VAddrs.push_back(Bias); 6423 } else { 6424 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6425 "Bias needs to be converted to 16 bit in A16 mode"); 6426 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6427 } 6428 } 6429 6430 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6431 // 16 bit gradients are supported, but are tied to the A16 control 6432 // so both gradients and addresses must be 16 bit 6433 LLVM_DEBUG( 6434 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6435 "require 16 bit args for both gradients and addresses"); 6436 return Op; 6437 } 6438 6439 if (IsA16) { 6440 if (!ST->hasA16()) { 6441 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6442 "support 16 bit addresses\n"); 6443 return Op; 6444 } 6445 } 6446 6447 // We've dealt with incorrect input so we know that if IsA16, IsG16 6448 // are set then we have to compress/pack operands (either address, 6449 // gradient or both) 6450 // In the case where a16 and gradients are tied (no G16 support) then we 6451 // have already verified that both IsA16 and IsG16 are true 6452 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6453 // Activate g16 6454 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6455 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6456 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6457 } 6458 6459 // Add gradients (packed or unpacked) 6460 if (IsG16) { 6461 // Pack the gradients 6462 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6463 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6464 ArgOffset + Intr->GradientStart, 6465 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6466 } else { 6467 for (unsigned I = ArgOffset + Intr->GradientStart; 6468 I < ArgOffset + Intr->CoordStart; I++) 6469 VAddrs.push_back(Op.getOperand(I)); 6470 } 6471 6472 // Add addresses (packed or unpacked) 6473 if (IsA16) { 6474 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6475 ArgOffset + Intr->CoordStart, VAddrEnd, 6476 0 /* No gradients */); 6477 } else { 6478 // Add uncompressed address 6479 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6480 VAddrs.push_back(Op.getOperand(I)); 6481 } 6482 6483 // If the register allocator cannot place the address registers contiguously 6484 // without introducing moves, then using the non-sequential address encoding 6485 // is always preferable, since it saves VALU instructions and is usually a 6486 // wash in terms of code size or even better. 6487 // 6488 // However, we currently have no way of hinting to the register allocator that 6489 // MIMG addresses should be placed contiguously when it is possible to do so, 6490 // so force non-NSA for the common 2-address case as a heuristic. 6491 // 6492 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6493 // allocation when possible. 6494 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6495 VAddrs.size() >= 3 && 6496 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6497 SDValue VAddr; 6498 if (!UseNSA) 6499 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6500 6501 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6502 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6503 SDValue Unorm; 6504 if (!BaseOpcode->Sampler) { 6505 Unorm = True; 6506 } else { 6507 auto UnormConst = 6508 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6509 6510 Unorm = UnormConst->getZExtValue() ? True : False; 6511 } 6512 6513 SDValue TFE; 6514 SDValue LWE; 6515 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6516 bool IsTexFail = false; 6517 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6518 return Op; 6519 6520 if (IsTexFail) { 6521 if (!DMaskLanes) { 6522 // Expecting to get an error flag since TFC is on - and dmask is 0 6523 // Force dmask to be at least 1 otherwise the instruction will fail 6524 DMask = 0x1; 6525 DMaskLanes = 1; 6526 NumVDataDwords = 1; 6527 } 6528 NumVDataDwords += 1; 6529 AdjustRetType = true; 6530 } 6531 6532 // Has something earlier tagged that the return type needs adjusting 6533 // This happens if the instruction is a load or has set TexFailCtrl flags 6534 if (AdjustRetType) { 6535 // NumVDataDwords reflects the true number of dwords required in the return type 6536 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6537 // This is a no-op load. This can be eliminated 6538 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6539 if (isa<MemSDNode>(Op)) 6540 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6541 return Undef; 6542 } 6543 6544 EVT NewVT = NumVDataDwords > 1 ? 6545 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6546 : MVT::i32; 6547 6548 ResultTypes[0] = NewVT; 6549 if (ResultTypes.size() == 3) { 6550 // Original result was aggregate type used for TexFailCtrl results 6551 // The actual instruction returns as a vector type which has now been 6552 // created. Remove the aggregate result. 6553 ResultTypes.erase(&ResultTypes[1]); 6554 } 6555 } 6556 6557 unsigned CPol = cast<ConstantSDNode>( 6558 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6559 if (BaseOpcode->Atomic) 6560 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6561 if (CPol & ~AMDGPU::CPol::ALL) 6562 return Op; 6563 6564 SmallVector<SDValue, 26> Ops; 6565 if (BaseOpcode->Store || BaseOpcode->Atomic) 6566 Ops.push_back(VData); // vdata 6567 if (UseNSA) 6568 append_range(Ops, VAddrs); 6569 else 6570 Ops.push_back(VAddr); 6571 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6572 if (BaseOpcode->Sampler) 6573 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6574 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6575 if (IsGFX10Plus) 6576 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6577 Ops.push_back(Unorm); 6578 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6579 Ops.push_back(IsA16 && // r128, a16 for gfx9 6580 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6581 if (IsGFX10Plus) 6582 Ops.push_back(IsA16 ? True : False); 6583 if (!Subtarget->hasGFX90AInsts()) { 6584 Ops.push_back(TFE); //tfe 6585 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6586 report_fatal_error("TFE is not supported on this GPU"); 6587 } 6588 Ops.push_back(LWE); // lwe 6589 if (!IsGFX10Plus) 6590 Ops.push_back(DimInfo->DA ? True : False); 6591 if (BaseOpcode->HasD16) 6592 Ops.push_back(IsD16 ? True : False); 6593 if (isa<MemSDNode>(Op)) 6594 Ops.push_back(Op.getOperand(0)); // chain 6595 6596 int NumVAddrDwords = 6597 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6598 int Opcode = -1; 6599 6600 if (IsGFX10Plus) { 6601 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6602 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6603 : AMDGPU::MIMGEncGfx10Default, 6604 NumVDataDwords, NumVAddrDwords); 6605 } else { 6606 if (Subtarget->hasGFX90AInsts()) { 6607 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6608 NumVDataDwords, NumVAddrDwords); 6609 if (Opcode == -1) 6610 report_fatal_error( 6611 "requested image instruction is not supported on this GPU"); 6612 } 6613 if (Opcode == -1 && 6614 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6615 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6616 NumVDataDwords, NumVAddrDwords); 6617 if (Opcode == -1) 6618 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6619 NumVDataDwords, NumVAddrDwords); 6620 } 6621 assert(Opcode != -1); 6622 6623 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6624 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6625 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6626 DAG.setNodeMemRefs(NewNode, {MemRef}); 6627 } 6628 6629 if (BaseOpcode->AtomicX2) { 6630 SmallVector<SDValue, 1> Elt; 6631 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6632 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6633 } 6634 if (BaseOpcode->Store) 6635 return SDValue(NewNode, 0); 6636 return constructRetValue(DAG, NewNode, 6637 OrigResultTypes, IsTexFail, 6638 Subtarget->hasUnpackedD16VMem(), IsD16, 6639 DMaskLanes, NumVDataDwords, DL); 6640 } 6641 6642 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6643 SDValue Offset, SDValue CachePolicy, 6644 SelectionDAG &DAG) const { 6645 MachineFunction &MF = DAG.getMachineFunction(); 6646 6647 const DataLayout &DataLayout = DAG.getDataLayout(); 6648 Align Alignment = 6649 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6650 6651 MachineMemOperand *MMO = MF.getMachineMemOperand( 6652 MachinePointerInfo(), 6653 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6654 MachineMemOperand::MOInvariant, 6655 VT.getStoreSize(), Alignment); 6656 6657 if (!Offset->isDivergent()) { 6658 SDValue Ops[] = { 6659 Rsrc, 6660 Offset, // Offset 6661 CachePolicy 6662 }; 6663 6664 // Widen vec3 load to vec4. 6665 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6666 EVT WidenedVT = 6667 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6668 auto WidenedOp = DAG.getMemIntrinsicNode( 6669 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6670 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6671 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6672 DAG.getVectorIdxConstant(0, DL)); 6673 return Subvector; 6674 } 6675 6676 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6677 DAG.getVTList(VT), Ops, VT, MMO); 6678 } 6679 6680 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6681 // assume that the buffer is unswizzled. 6682 SmallVector<SDValue, 4> Loads; 6683 unsigned NumLoads = 1; 6684 MVT LoadVT = VT.getSimpleVT(); 6685 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6686 assert((LoadVT.getScalarType() == MVT::i32 || 6687 LoadVT.getScalarType() == MVT::f32)); 6688 6689 if (NumElts == 8 || NumElts == 16) { 6690 NumLoads = NumElts / 4; 6691 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6692 } 6693 6694 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6695 SDValue Ops[] = { 6696 DAG.getEntryNode(), // Chain 6697 Rsrc, // rsrc 6698 DAG.getConstant(0, DL, MVT::i32), // vindex 6699 {}, // voffset 6700 {}, // soffset 6701 {}, // offset 6702 CachePolicy, // cachepolicy 6703 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6704 }; 6705 6706 // Use the alignment to ensure that the required offsets will fit into the 6707 // immediate offsets. 6708 setBufferOffsets(Offset, DAG, &Ops[3], 6709 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6710 6711 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6712 for (unsigned i = 0; i < NumLoads; ++i) { 6713 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6714 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6715 LoadVT, MMO, DAG)); 6716 } 6717 6718 if (NumElts == 8 || NumElts == 16) 6719 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6720 6721 return Loads[0]; 6722 } 6723 6724 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6725 SelectionDAG &DAG) const { 6726 MachineFunction &MF = DAG.getMachineFunction(); 6727 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6728 6729 EVT VT = Op.getValueType(); 6730 SDLoc DL(Op); 6731 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6732 6733 // TODO: Should this propagate fast-math-flags? 6734 6735 switch (IntrinsicID) { 6736 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6737 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6738 return emitNonHSAIntrinsicError(DAG, DL, VT); 6739 return getPreloadedValue(DAG, *MFI, VT, 6740 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6741 } 6742 case Intrinsic::amdgcn_dispatch_ptr: 6743 case Intrinsic::amdgcn_queue_ptr: { 6744 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6745 DiagnosticInfoUnsupported BadIntrin( 6746 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6747 DL.getDebugLoc()); 6748 DAG.getContext()->diagnose(BadIntrin); 6749 return DAG.getUNDEF(VT); 6750 } 6751 6752 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6753 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6754 return getPreloadedValue(DAG, *MFI, VT, RegID); 6755 } 6756 case Intrinsic::amdgcn_implicitarg_ptr: { 6757 if (MFI->isEntryFunction()) 6758 return getImplicitArgPtr(DAG, DL); 6759 return getPreloadedValue(DAG, *MFI, VT, 6760 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6761 } 6762 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6763 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6764 // This only makes sense to call in a kernel, so just lower to null. 6765 return DAG.getConstant(0, DL, VT); 6766 } 6767 6768 return getPreloadedValue(DAG, *MFI, VT, 6769 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6770 } 6771 case Intrinsic::amdgcn_dispatch_id: { 6772 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6773 } 6774 case Intrinsic::amdgcn_rcp: 6775 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6776 case Intrinsic::amdgcn_rsq: 6777 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6778 case Intrinsic::amdgcn_rsq_legacy: 6779 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6780 return emitRemovedIntrinsicError(DAG, DL, VT); 6781 return SDValue(); 6782 case Intrinsic::amdgcn_rcp_legacy: 6783 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6784 return emitRemovedIntrinsicError(DAG, DL, VT); 6785 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6786 case Intrinsic::amdgcn_rsq_clamp: { 6787 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6788 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6789 6790 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6791 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6792 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6793 6794 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6795 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6796 DAG.getConstantFP(Max, DL, VT)); 6797 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6798 DAG.getConstantFP(Min, DL, VT)); 6799 } 6800 case Intrinsic::r600_read_ngroups_x: 6801 if (Subtarget->isAmdHsaOS()) 6802 return emitNonHSAIntrinsicError(DAG, DL, VT); 6803 6804 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6805 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6806 false); 6807 case Intrinsic::r600_read_ngroups_y: 6808 if (Subtarget->isAmdHsaOS()) 6809 return emitNonHSAIntrinsicError(DAG, DL, VT); 6810 6811 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6812 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6813 false); 6814 case Intrinsic::r600_read_ngroups_z: 6815 if (Subtarget->isAmdHsaOS()) 6816 return emitNonHSAIntrinsicError(DAG, DL, VT); 6817 6818 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6819 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6820 false); 6821 case Intrinsic::r600_read_global_size_x: 6822 if (Subtarget->isAmdHsaOS()) 6823 return emitNonHSAIntrinsicError(DAG, DL, VT); 6824 6825 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6826 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6827 Align(4), false); 6828 case Intrinsic::r600_read_global_size_y: 6829 if (Subtarget->isAmdHsaOS()) 6830 return emitNonHSAIntrinsicError(DAG, DL, VT); 6831 6832 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6833 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6834 Align(4), false); 6835 case Intrinsic::r600_read_global_size_z: 6836 if (Subtarget->isAmdHsaOS()) 6837 return emitNonHSAIntrinsicError(DAG, DL, VT); 6838 6839 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6840 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6841 Align(4), false); 6842 case Intrinsic::r600_read_local_size_x: 6843 if (Subtarget->isAmdHsaOS()) 6844 return emitNonHSAIntrinsicError(DAG, DL, VT); 6845 6846 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6847 SI::KernelInputOffsets::LOCAL_SIZE_X); 6848 case Intrinsic::r600_read_local_size_y: 6849 if (Subtarget->isAmdHsaOS()) 6850 return emitNonHSAIntrinsicError(DAG, DL, VT); 6851 6852 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6853 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6854 case Intrinsic::r600_read_local_size_z: 6855 if (Subtarget->isAmdHsaOS()) 6856 return emitNonHSAIntrinsicError(DAG, DL, VT); 6857 6858 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6859 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6860 case Intrinsic::amdgcn_workgroup_id_x: 6861 return getPreloadedValue(DAG, *MFI, VT, 6862 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6863 case Intrinsic::amdgcn_workgroup_id_y: 6864 return getPreloadedValue(DAG, *MFI, VT, 6865 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6866 case Intrinsic::amdgcn_workgroup_id_z: 6867 return getPreloadedValue(DAG, *MFI, VT, 6868 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6869 case Intrinsic::amdgcn_workitem_id_x: 6870 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0) 6871 return DAG.getConstant(0, DL, MVT::i32); 6872 6873 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6874 SDLoc(DAG.getEntryNode()), 6875 MFI->getArgInfo().WorkItemIDX); 6876 case Intrinsic::amdgcn_workitem_id_y: 6877 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0) 6878 return DAG.getConstant(0, DL, MVT::i32); 6879 6880 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6881 SDLoc(DAG.getEntryNode()), 6882 MFI->getArgInfo().WorkItemIDY); 6883 case Intrinsic::amdgcn_workitem_id_z: 6884 if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0) 6885 return DAG.getConstant(0, DL, MVT::i32); 6886 6887 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6888 SDLoc(DAG.getEntryNode()), 6889 MFI->getArgInfo().WorkItemIDZ); 6890 case Intrinsic::amdgcn_wavefrontsize: 6891 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6892 SDLoc(Op), MVT::i32); 6893 case Intrinsic::amdgcn_s_buffer_load: { 6894 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6895 if (CPol & ~AMDGPU::CPol::ALL) 6896 return Op; 6897 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6898 DAG); 6899 } 6900 case Intrinsic::amdgcn_fdiv_fast: 6901 return lowerFDIV_FAST(Op, DAG); 6902 case Intrinsic::amdgcn_sin: 6903 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6904 6905 case Intrinsic::amdgcn_cos: 6906 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6907 6908 case Intrinsic::amdgcn_mul_u24: 6909 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6910 case Intrinsic::amdgcn_mul_i24: 6911 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6912 6913 case Intrinsic::amdgcn_log_clamp: { 6914 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6915 return SDValue(); 6916 6917 return emitRemovedIntrinsicError(DAG, DL, VT); 6918 } 6919 case Intrinsic::amdgcn_ldexp: 6920 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6921 Op.getOperand(1), Op.getOperand(2)); 6922 6923 case Intrinsic::amdgcn_fract: 6924 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6925 6926 case Intrinsic::amdgcn_class: 6927 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6928 Op.getOperand(1), Op.getOperand(2)); 6929 case Intrinsic::amdgcn_div_fmas: 6930 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6931 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6932 Op.getOperand(4)); 6933 6934 case Intrinsic::amdgcn_div_fixup: 6935 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6936 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6937 6938 case Intrinsic::amdgcn_div_scale: { 6939 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6940 6941 // Translate to the operands expected by the machine instruction. The 6942 // first parameter must be the same as the first instruction. 6943 SDValue Numerator = Op.getOperand(1); 6944 SDValue Denominator = Op.getOperand(2); 6945 6946 // Note this order is opposite of the machine instruction's operations, 6947 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6948 // intrinsic has the numerator as the first operand to match a normal 6949 // division operation. 6950 6951 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6952 6953 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6954 Denominator, Numerator); 6955 } 6956 case Intrinsic::amdgcn_icmp: { 6957 // There is a Pat that handles this variant, so return it as-is. 6958 if (Op.getOperand(1).getValueType() == MVT::i1 && 6959 Op.getConstantOperandVal(2) == 0 && 6960 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6961 return Op; 6962 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6963 } 6964 case Intrinsic::amdgcn_fcmp: { 6965 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6966 } 6967 case Intrinsic::amdgcn_ballot: 6968 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6969 case Intrinsic::amdgcn_fmed3: 6970 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6971 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6972 case Intrinsic::amdgcn_fdot2: 6973 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6974 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6975 Op.getOperand(4)); 6976 case Intrinsic::amdgcn_fmul_legacy: 6977 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6978 Op.getOperand(1), Op.getOperand(2)); 6979 case Intrinsic::amdgcn_sffbh: 6980 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6981 case Intrinsic::amdgcn_sbfe: 6982 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6983 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6984 case Intrinsic::amdgcn_ubfe: 6985 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6986 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6987 case Intrinsic::amdgcn_cvt_pkrtz: 6988 case Intrinsic::amdgcn_cvt_pknorm_i16: 6989 case Intrinsic::amdgcn_cvt_pknorm_u16: 6990 case Intrinsic::amdgcn_cvt_pk_i16: 6991 case Intrinsic::amdgcn_cvt_pk_u16: { 6992 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6993 EVT VT = Op.getValueType(); 6994 unsigned Opcode; 6995 6996 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6997 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6998 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6999 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 7000 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 7001 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 7002 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 7003 Opcode = AMDGPUISD::CVT_PK_I16_I32; 7004 else 7005 Opcode = AMDGPUISD::CVT_PK_U16_U32; 7006 7007 if (isTypeLegal(VT)) 7008 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7009 7010 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 7011 Op.getOperand(1), Op.getOperand(2)); 7012 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 7013 } 7014 case Intrinsic::amdgcn_fmad_ftz: 7015 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 7016 Op.getOperand(2), Op.getOperand(3)); 7017 7018 case Intrinsic::amdgcn_if_break: 7019 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 7020 Op->getOperand(1), Op->getOperand(2)), 0); 7021 7022 case Intrinsic::amdgcn_groupstaticsize: { 7023 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 7024 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 7025 return Op; 7026 7027 const Module *M = MF.getFunction().getParent(); 7028 const GlobalValue *GV = 7029 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 7030 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 7031 SIInstrInfo::MO_ABS32_LO); 7032 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7033 } 7034 case Intrinsic::amdgcn_is_shared: 7035 case Intrinsic::amdgcn_is_private: { 7036 SDLoc SL(Op); 7037 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 7038 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7039 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7040 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7041 Op.getOperand(1)); 7042 7043 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7044 DAG.getConstant(1, SL, MVT::i32)); 7045 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7046 } 7047 case Intrinsic::amdgcn_perm: 7048 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7049 Op.getOperand(2), Op.getOperand(3)); 7050 case Intrinsic::amdgcn_reloc_constant: { 7051 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7052 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7053 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7054 auto RelocSymbol = cast<GlobalVariable>( 7055 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7056 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7057 SIInstrInfo::MO_ABS32_LO); 7058 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7059 } 7060 default: 7061 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7062 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7063 return lowerImage(Op, ImageDimIntr, DAG, false); 7064 7065 return Op; 7066 } 7067 } 7068 7069 /// Update \p MMO based on the offset inputs to an intrinsic. 7070 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7071 SDValue SOffset, SDValue Offset, 7072 SDValue VIndex = SDValue()) { 7073 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7074 !isa<ConstantSDNode>(Offset)) { 7075 // The combined offset is not known to be constant, so we cannot represent 7076 // it in the MMO. Give up. 7077 MMO->setValue((Value *)nullptr); 7078 return; 7079 } 7080 7081 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7082 !cast<ConstantSDNode>(VIndex)->isZero())) { 7083 // The strided index component of the address is not known to be zero, so we 7084 // cannot represent it in the MMO. Give up. 7085 MMO->setValue((Value *)nullptr); 7086 return; 7087 } 7088 7089 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7090 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7091 cast<ConstantSDNode>(Offset)->getSExtValue()); 7092 } 7093 7094 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7095 SelectionDAG &DAG, 7096 unsigned NewOpcode) const { 7097 SDLoc DL(Op); 7098 7099 SDValue VData = Op.getOperand(2); 7100 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7101 SDValue Ops[] = { 7102 Op.getOperand(0), // Chain 7103 VData, // vdata 7104 Op.getOperand(3), // rsrc 7105 DAG.getConstant(0, DL, MVT::i32), // vindex 7106 Offsets.first, // voffset 7107 Op.getOperand(5), // soffset 7108 Offsets.second, // offset 7109 Op.getOperand(6), // cachepolicy 7110 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7111 }; 7112 7113 auto *M = cast<MemSDNode>(Op); 7114 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7115 7116 EVT MemVT = VData.getValueType(); 7117 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7118 M->getMemOperand()); 7119 } 7120 7121 // Return a value to use for the idxen operand by examining the vindex operand. 7122 static unsigned getIdxEn(SDValue VIndex) { 7123 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7124 // No need to set idxen if vindex is known to be zero. 7125 return VIndexC->getZExtValue() != 0; 7126 return 1; 7127 } 7128 7129 SDValue 7130 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7131 unsigned NewOpcode) const { 7132 SDLoc DL(Op); 7133 7134 SDValue VData = Op.getOperand(2); 7135 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7136 SDValue Ops[] = { 7137 Op.getOperand(0), // Chain 7138 VData, // vdata 7139 Op.getOperand(3), // rsrc 7140 Op.getOperand(4), // vindex 7141 Offsets.first, // voffset 7142 Op.getOperand(6), // soffset 7143 Offsets.second, // offset 7144 Op.getOperand(7), // cachepolicy 7145 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7146 }; 7147 7148 auto *M = cast<MemSDNode>(Op); 7149 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7150 7151 EVT MemVT = VData.getValueType(); 7152 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7153 M->getMemOperand()); 7154 } 7155 7156 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7157 SelectionDAG &DAG) const { 7158 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7159 SDLoc DL(Op); 7160 7161 switch (IntrID) { 7162 case Intrinsic::amdgcn_ds_ordered_add: 7163 case Intrinsic::amdgcn_ds_ordered_swap: { 7164 MemSDNode *M = cast<MemSDNode>(Op); 7165 SDValue Chain = M->getOperand(0); 7166 SDValue M0 = M->getOperand(2); 7167 SDValue Value = M->getOperand(3); 7168 unsigned IndexOperand = M->getConstantOperandVal(7); 7169 unsigned WaveRelease = M->getConstantOperandVal(8); 7170 unsigned WaveDone = M->getConstantOperandVal(9); 7171 7172 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7173 IndexOperand &= ~0x3f; 7174 unsigned CountDw = 0; 7175 7176 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7177 CountDw = (IndexOperand >> 24) & 0xf; 7178 IndexOperand &= ~(0xf << 24); 7179 7180 if (CountDw < 1 || CountDw > 4) { 7181 report_fatal_error( 7182 "ds_ordered_count: dword count must be between 1 and 4"); 7183 } 7184 } 7185 7186 if (IndexOperand) 7187 report_fatal_error("ds_ordered_count: bad index operand"); 7188 7189 if (WaveDone && !WaveRelease) 7190 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7191 7192 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7193 unsigned ShaderType = 7194 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7195 unsigned Offset0 = OrderedCountIndex << 2; 7196 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7197 (Instruction << 4); 7198 7199 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7200 Offset1 |= (CountDw - 1) << 6; 7201 7202 unsigned Offset = Offset0 | (Offset1 << 8); 7203 7204 SDValue Ops[] = { 7205 Chain, 7206 Value, 7207 DAG.getTargetConstant(Offset, DL, MVT::i16), 7208 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7209 }; 7210 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7211 M->getVTList(), Ops, M->getMemoryVT(), 7212 M->getMemOperand()); 7213 } 7214 case Intrinsic::amdgcn_ds_fadd: { 7215 MemSDNode *M = cast<MemSDNode>(Op); 7216 unsigned Opc; 7217 switch (IntrID) { 7218 case Intrinsic::amdgcn_ds_fadd: 7219 Opc = ISD::ATOMIC_LOAD_FADD; 7220 break; 7221 } 7222 7223 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7224 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7225 M->getMemOperand()); 7226 } 7227 case Intrinsic::amdgcn_atomic_inc: 7228 case Intrinsic::amdgcn_atomic_dec: 7229 case Intrinsic::amdgcn_ds_fmin: 7230 case Intrinsic::amdgcn_ds_fmax: { 7231 MemSDNode *M = cast<MemSDNode>(Op); 7232 unsigned Opc; 7233 switch (IntrID) { 7234 case Intrinsic::amdgcn_atomic_inc: 7235 Opc = AMDGPUISD::ATOMIC_INC; 7236 break; 7237 case Intrinsic::amdgcn_atomic_dec: 7238 Opc = AMDGPUISD::ATOMIC_DEC; 7239 break; 7240 case Intrinsic::amdgcn_ds_fmin: 7241 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7242 break; 7243 case Intrinsic::amdgcn_ds_fmax: 7244 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7245 break; 7246 default: 7247 llvm_unreachable("Unknown intrinsic!"); 7248 } 7249 SDValue Ops[] = { 7250 M->getOperand(0), // Chain 7251 M->getOperand(2), // Ptr 7252 M->getOperand(3) // Value 7253 }; 7254 7255 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7256 M->getMemoryVT(), M->getMemOperand()); 7257 } 7258 case Intrinsic::amdgcn_buffer_load: 7259 case Intrinsic::amdgcn_buffer_load_format: { 7260 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7261 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7262 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7263 SDValue Ops[] = { 7264 Op.getOperand(0), // Chain 7265 Op.getOperand(2), // rsrc 7266 Op.getOperand(3), // vindex 7267 SDValue(), // voffset -- will be set by setBufferOffsets 7268 SDValue(), // soffset -- will be set by setBufferOffsets 7269 SDValue(), // offset -- will be set by setBufferOffsets 7270 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7271 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7272 }; 7273 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7274 7275 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7276 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7277 7278 EVT VT = Op.getValueType(); 7279 EVT IntVT = VT.changeTypeToInteger(); 7280 auto *M = cast<MemSDNode>(Op); 7281 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7282 EVT LoadVT = Op.getValueType(); 7283 7284 if (LoadVT.getScalarType() == MVT::f16) 7285 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7286 M, DAG, Ops); 7287 7288 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7289 if (LoadVT.getScalarType() == MVT::i8 || 7290 LoadVT.getScalarType() == MVT::i16) 7291 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7292 7293 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7294 M->getMemOperand(), DAG); 7295 } 7296 case Intrinsic::amdgcn_raw_buffer_load: 7297 case Intrinsic::amdgcn_raw_buffer_load_format: { 7298 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7299 7300 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7301 SDValue Ops[] = { 7302 Op.getOperand(0), // Chain 7303 Op.getOperand(2), // rsrc 7304 DAG.getConstant(0, DL, MVT::i32), // vindex 7305 Offsets.first, // voffset 7306 Op.getOperand(4), // soffset 7307 Offsets.second, // offset 7308 Op.getOperand(5), // cachepolicy, swizzled buffer 7309 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7310 }; 7311 7312 auto *M = cast<MemSDNode>(Op); 7313 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7314 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7315 } 7316 case Intrinsic::amdgcn_struct_buffer_load: 7317 case Intrinsic::amdgcn_struct_buffer_load_format: { 7318 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7319 7320 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7321 SDValue Ops[] = { 7322 Op.getOperand(0), // Chain 7323 Op.getOperand(2), // rsrc 7324 Op.getOperand(3), // vindex 7325 Offsets.first, // voffset 7326 Op.getOperand(5), // soffset 7327 Offsets.second, // offset 7328 Op.getOperand(6), // cachepolicy, swizzled buffer 7329 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7330 }; 7331 7332 auto *M = cast<MemSDNode>(Op); 7333 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7334 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7335 } 7336 case Intrinsic::amdgcn_tbuffer_load: { 7337 MemSDNode *M = cast<MemSDNode>(Op); 7338 EVT LoadVT = Op.getValueType(); 7339 7340 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7341 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7342 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7343 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7344 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7345 SDValue Ops[] = { 7346 Op.getOperand(0), // Chain 7347 Op.getOperand(2), // rsrc 7348 Op.getOperand(3), // vindex 7349 Op.getOperand(4), // voffset 7350 Op.getOperand(5), // soffset 7351 Op.getOperand(6), // offset 7352 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7353 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7354 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7355 }; 7356 7357 if (LoadVT.getScalarType() == MVT::f16) 7358 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7359 M, DAG, Ops); 7360 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7361 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7362 DAG); 7363 } 7364 case Intrinsic::amdgcn_raw_tbuffer_load: { 7365 MemSDNode *M = cast<MemSDNode>(Op); 7366 EVT LoadVT = Op.getValueType(); 7367 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7368 7369 SDValue Ops[] = { 7370 Op.getOperand(0), // Chain 7371 Op.getOperand(2), // rsrc 7372 DAG.getConstant(0, DL, MVT::i32), // vindex 7373 Offsets.first, // voffset 7374 Op.getOperand(4), // soffset 7375 Offsets.second, // offset 7376 Op.getOperand(5), // format 7377 Op.getOperand(6), // cachepolicy, swizzled buffer 7378 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7379 }; 7380 7381 if (LoadVT.getScalarType() == MVT::f16) 7382 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7383 M, DAG, Ops); 7384 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7385 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7386 DAG); 7387 } 7388 case Intrinsic::amdgcn_struct_tbuffer_load: { 7389 MemSDNode *M = cast<MemSDNode>(Op); 7390 EVT LoadVT = Op.getValueType(); 7391 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7392 7393 SDValue Ops[] = { 7394 Op.getOperand(0), // Chain 7395 Op.getOperand(2), // rsrc 7396 Op.getOperand(3), // vindex 7397 Offsets.first, // voffset 7398 Op.getOperand(5), // soffset 7399 Offsets.second, // offset 7400 Op.getOperand(6), // format 7401 Op.getOperand(7), // cachepolicy, swizzled buffer 7402 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7403 }; 7404 7405 if (LoadVT.getScalarType() == MVT::f16) 7406 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7407 M, DAG, Ops); 7408 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7409 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7410 DAG); 7411 } 7412 case Intrinsic::amdgcn_buffer_atomic_swap: 7413 case Intrinsic::amdgcn_buffer_atomic_add: 7414 case Intrinsic::amdgcn_buffer_atomic_sub: 7415 case Intrinsic::amdgcn_buffer_atomic_csub: 7416 case Intrinsic::amdgcn_buffer_atomic_smin: 7417 case Intrinsic::amdgcn_buffer_atomic_umin: 7418 case Intrinsic::amdgcn_buffer_atomic_smax: 7419 case Intrinsic::amdgcn_buffer_atomic_umax: 7420 case Intrinsic::amdgcn_buffer_atomic_and: 7421 case Intrinsic::amdgcn_buffer_atomic_or: 7422 case Intrinsic::amdgcn_buffer_atomic_xor: 7423 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7424 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7425 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7426 SDValue Ops[] = { 7427 Op.getOperand(0), // Chain 7428 Op.getOperand(2), // vdata 7429 Op.getOperand(3), // rsrc 7430 Op.getOperand(4), // vindex 7431 SDValue(), // voffset -- will be set by setBufferOffsets 7432 SDValue(), // soffset -- will be set by setBufferOffsets 7433 SDValue(), // offset -- will be set by setBufferOffsets 7434 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7435 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7436 }; 7437 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7438 7439 EVT VT = Op.getValueType(); 7440 7441 auto *M = cast<MemSDNode>(Op); 7442 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7443 unsigned Opcode = 0; 7444 7445 switch (IntrID) { 7446 case Intrinsic::amdgcn_buffer_atomic_swap: 7447 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7448 break; 7449 case Intrinsic::amdgcn_buffer_atomic_add: 7450 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7451 break; 7452 case Intrinsic::amdgcn_buffer_atomic_sub: 7453 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7454 break; 7455 case Intrinsic::amdgcn_buffer_atomic_csub: 7456 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7457 break; 7458 case Intrinsic::amdgcn_buffer_atomic_smin: 7459 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7460 break; 7461 case Intrinsic::amdgcn_buffer_atomic_umin: 7462 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7463 break; 7464 case Intrinsic::amdgcn_buffer_atomic_smax: 7465 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7466 break; 7467 case Intrinsic::amdgcn_buffer_atomic_umax: 7468 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7469 break; 7470 case Intrinsic::amdgcn_buffer_atomic_and: 7471 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7472 break; 7473 case Intrinsic::amdgcn_buffer_atomic_or: 7474 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7475 break; 7476 case Intrinsic::amdgcn_buffer_atomic_xor: 7477 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7478 break; 7479 case Intrinsic::amdgcn_buffer_atomic_fadd: 7480 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7481 DiagnosticInfoUnsupported 7482 NoFpRet(DAG.getMachineFunction().getFunction(), 7483 "return versions of fp atomics not supported", 7484 DL.getDebugLoc(), DS_Error); 7485 DAG.getContext()->diagnose(NoFpRet); 7486 return SDValue(); 7487 } 7488 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7489 break; 7490 default: 7491 llvm_unreachable("unhandled atomic opcode"); 7492 } 7493 7494 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7495 M->getMemOperand()); 7496 } 7497 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7498 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7499 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7500 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7501 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7502 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7503 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7504 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7505 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7506 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7507 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7508 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7509 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7510 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7511 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7512 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7513 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7514 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7515 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7516 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7517 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7518 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7519 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7520 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7521 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7522 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7523 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7524 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7525 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7526 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7527 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7528 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7529 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7530 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7531 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7532 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7533 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7534 return lowerStructBufferAtomicIntrin(Op, DAG, 7535 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7536 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7537 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7538 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7539 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7540 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7541 return lowerStructBufferAtomicIntrin(Op, DAG, 7542 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7543 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7544 return lowerStructBufferAtomicIntrin(Op, DAG, 7545 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7546 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7547 return lowerStructBufferAtomicIntrin(Op, DAG, 7548 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7549 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7550 return lowerStructBufferAtomicIntrin(Op, DAG, 7551 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7552 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7553 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7554 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7555 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7556 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7557 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7558 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7559 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7560 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7561 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7562 7563 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7564 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7565 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7566 SDValue Ops[] = { 7567 Op.getOperand(0), // Chain 7568 Op.getOperand(2), // src 7569 Op.getOperand(3), // cmp 7570 Op.getOperand(4), // rsrc 7571 Op.getOperand(5), // vindex 7572 SDValue(), // voffset -- will be set by setBufferOffsets 7573 SDValue(), // soffset -- will be set by setBufferOffsets 7574 SDValue(), // offset -- will be set by setBufferOffsets 7575 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7576 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7577 }; 7578 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7579 7580 EVT VT = Op.getValueType(); 7581 auto *M = cast<MemSDNode>(Op); 7582 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7583 7584 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7585 Op->getVTList(), Ops, VT, M->getMemOperand()); 7586 } 7587 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7588 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7589 SDValue Ops[] = { 7590 Op.getOperand(0), // Chain 7591 Op.getOperand(2), // src 7592 Op.getOperand(3), // cmp 7593 Op.getOperand(4), // rsrc 7594 DAG.getConstant(0, DL, MVT::i32), // vindex 7595 Offsets.first, // voffset 7596 Op.getOperand(6), // soffset 7597 Offsets.second, // offset 7598 Op.getOperand(7), // cachepolicy 7599 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7600 }; 7601 EVT VT = Op.getValueType(); 7602 auto *M = cast<MemSDNode>(Op); 7603 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7604 7605 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7606 Op->getVTList(), Ops, VT, M->getMemOperand()); 7607 } 7608 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7609 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7610 SDValue Ops[] = { 7611 Op.getOperand(0), // Chain 7612 Op.getOperand(2), // src 7613 Op.getOperand(3), // cmp 7614 Op.getOperand(4), // rsrc 7615 Op.getOperand(5), // vindex 7616 Offsets.first, // voffset 7617 Op.getOperand(7), // soffset 7618 Offsets.second, // offset 7619 Op.getOperand(8), // cachepolicy 7620 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7621 }; 7622 EVT VT = Op.getValueType(); 7623 auto *M = cast<MemSDNode>(Op); 7624 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7625 7626 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7627 Op->getVTList(), Ops, VT, M->getMemOperand()); 7628 } 7629 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7630 MemSDNode *M = cast<MemSDNode>(Op); 7631 SDValue NodePtr = M->getOperand(2); 7632 SDValue RayExtent = M->getOperand(3); 7633 SDValue RayOrigin = M->getOperand(4); 7634 SDValue RayDir = M->getOperand(5); 7635 SDValue RayInvDir = M->getOperand(6); 7636 SDValue TDescr = M->getOperand(7); 7637 7638 assert(NodePtr.getValueType() == MVT::i32 || 7639 NodePtr.getValueType() == MVT::i64); 7640 assert(RayDir.getValueType() == MVT::v3f16 || 7641 RayDir.getValueType() == MVT::v3f32); 7642 7643 if (!Subtarget->hasGFX10_AEncoding()) { 7644 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7645 return SDValue(); 7646 } 7647 7648 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7649 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7650 const unsigned NumVDataDwords = 4; 7651 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7652 const bool UseNSA = Subtarget->hasNSAEncoding() && 7653 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7654 const unsigned BaseOpcodes[2][2] = { 7655 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7656 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7657 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7658 int Opcode; 7659 if (UseNSA) { 7660 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7661 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7662 NumVAddrDwords); 7663 } else { 7664 Opcode = AMDGPU::getMIMGOpcode( 7665 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7666 PowerOf2Ceil(NumVAddrDwords)); 7667 } 7668 assert(Opcode != -1); 7669 7670 SmallVector<SDValue, 16> Ops; 7671 7672 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7673 SmallVector<SDValue, 3> Lanes; 7674 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7675 if (Lanes[0].getValueSizeInBits() == 32) { 7676 for (unsigned I = 0; I < 3; ++I) 7677 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7678 } else { 7679 if (IsAligned) { 7680 Ops.push_back( 7681 DAG.getBitcast(MVT::i32, 7682 DAG.getBuildVector(MVT::v2f16, DL, 7683 { Lanes[0], Lanes[1] }))); 7684 Ops.push_back(Lanes[2]); 7685 } else { 7686 SDValue Elt0 = Ops.pop_back_val(); 7687 Ops.push_back( 7688 DAG.getBitcast(MVT::i32, 7689 DAG.getBuildVector(MVT::v2f16, DL, 7690 { Elt0, Lanes[0] }))); 7691 Ops.push_back( 7692 DAG.getBitcast(MVT::i32, 7693 DAG.getBuildVector(MVT::v2f16, DL, 7694 { Lanes[1], Lanes[2] }))); 7695 } 7696 } 7697 }; 7698 7699 if (Is64) 7700 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7701 else 7702 Ops.push_back(NodePtr); 7703 7704 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7705 packLanes(RayOrigin, true); 7706 packLanes(RayDir, true); 7707 packLanes(RayInvDir, false); 7708 7709 if (!UseNSA) { 7710 // Build a single vector containing all the operands so far prepared. 7711 if (NumVAddrDwords > 8) { 7712 SDValue Undef = DAG.getUNDEF(MVT::i32); 7713 Ops.append(16 - Ops.size(), Undef); 7714 } 7715 assert(Ops.size() == 8 || Ops.size() == 16); 7716 SDValue MergedOps = DAG.getBuildVector( 7717 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7718 Ops.clear(); 7719 Ops.push_back(MergedOps); 7720 } 7721 7722 Ops.push_back(TDescr); 7723 if (IsA16) 7724 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7725 Ops.push_back(M->getChain()); 7726 7727 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7728 MachineMemOperand *MemRef = M->getMemOperand(); 7729 DAG.setNodeMemRefs(NewNode, {MemRef}); 7730 return SDValue(NewNode, 0); 7731 } 7732 case Intrinsic::amdgcn_global_atomic_fadd: 7733 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7734 DiagnosticInfoUnsupported 7735 NoFpRet(DAG.getMachineFunction().getFunction(), 7736 "return versions of fp atomics not supported", 7737 DL.getDebugLoc(), DS_Error); 7738 DAG.getContext()->diagnose(NoFpRet); 7739 return SDValue(); 7740 } 7741 LLVM_FALLTHROUGH; 7742 case Intrinsic::amdgcn_global_atomic_fmin: 7743 case Intrinsic::amdgcn_global_atomic_fmax: 7744 case Intrinsic::amdgcn_flat_atomic_fadd: 7745 case Intrinsic::amdgcn_flat_atomic_fmin: 7746 case Intrinsic::amdgcn_flat_atomic_fmax: { 7747 MemSDNode *M = cast<MemSDNode>(Op); 7748 SDValue Ops[] = { 7749 M->getOperand(0), // Chain 7750 M->getOperand(2), // Ptr 7751 M->getOperand(3) // Value 7752 }; 7753 unsigned Opcode = 0; 7754 switch (IntrID) { 7755 case Intrinsic::amdgcn_global_atomic_fadd: 7756 case Intrinsic::amdgcn_flat_atomic_fadd: { 7757 EVT VT = Op.getOperand(3).getValueType(); 7758 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7759 DAG.getVTList(VT, MVT::Other), Ops, 7760 M->getMemOperand()); 7761 } 7762 case Intrinsic::amdgcn_global_atomic_fmin: 7763 case Intrinsic::amdgcn_flat_atomic_fmin: { 7764 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7765 break; 7766 } 7767 case Intrinsic::amdgcn_global_atomic_fmax: 7768 case Intrinsic::amdgcn_flat_atomic_fmax: { 7769 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7770 break; 7771 } 7772 default: 7773 llvm_unreachable("unhandled atomic opcode"); 7774 } 7775 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7776 M->getVTList(), Ops, M->getMemoryVT(), 7777 M->getMemOperand()); 7778 } 7779 default: 7780 7781 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7782 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7783 return lowerImage(Op, ImageDimIntr, DAG, true); 7784 7785 return SDValue(); 7786 } 7787 } 7788 7789 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7790 // dwordx4 if on SI. 7791 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7792 SDVTList VTList, 7793 ArrayRef<SDValue> Ops, EVT MemVT, 7794 MachineMemOperand *MMO, 7795 SelectionDAG &DAG) const { 7796 EVT VT = VTList.VTs[0]; 7797 EVT WidenedVT = VT; 7798 EVT WidenedMemVT = MemVT; 7799 if (!Subtarget->hasDwordx3LoadStores() && 7800 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7801 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7802 WidenedVT.getVectorElementType(), 4); 7803 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7804 WidenedMemVT.getVectorElementType(), 4); 7805 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7806 } 7807 7808 assert(VTList.NumVTs == 2); 7809 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7810 7811 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7812 WidenedMemVT, MMO); 7813 if (WidenedVT != VT) { 7814 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7815 DAG.getVectorIdxConstant(0, DL)); 7816 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7817 } 7818 return NewOp; 7819 } 7820 7821 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7822 bool ImageStore) const { 7823 EVT StoreVT = VData.getValueType(); 7824 7825 // No change for f16 and legal vector D16 types. 7826 if (!StoreVT.isVector()) 7827 return VData; 7828 7829 SDLoc DL(VData); 7830 unsigned NumElements = StoreVT.getVectorNumElements(); 7831 7832 if (Subtarget->hasUnpackedD16VMem()) { 7833 // We need to unpack the packed data to store. 7834 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7835 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7836 7837 EVT EquivStoreVT = 7838 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7839 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7840 return DAG.UnrollVectorOp(ZExt.getNode()); 7841 } 7842 7843 // The sq block of gfx8.1 does not estimate register use correctly for d16 7844 // image store instructions. The data operand is computed as if it were not a 7845 // d16 image instruction. 7846 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7847 // Bitcast to i16 7848 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7849 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7850 7851 // Decompose into scalars 7852 SmallVector<SDValue, 4> Elts; 7853 DAG.ExtractVectorElements(IntVData, Elts); 7854 7855 // Group pairs of i16 into v2i16 and bitcast to i32 7856 SmallVector<SDValue, 4> PackedElts; 7857 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7858 SDValue Pair = 7859 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7860 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7861 PackedElts.push_back(IntPair); 7862 } 7863 if ((NumElements % 2) == 1) { 7864 // Handle v3i16 7865 unsigned I = Elts.size() / 2; 7866 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7867 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7868 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7869 PackedElts.push_back(IntPair); 7870 } 7871 7872 // Pad using UNDEF 7873 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7874 7875 // Build final vector 7876 EVT VecVT = 7877 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7878 return DAG.getBuildVector(VecVT, DL, PackedElts); 7879 } 7880 7881 if (NumElements == 3) { 7882 EVT IntStoreVT = 7883 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7884 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7885 7886 EVT WidenedStoreVT = EVT::getVectorVT( 7887 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7888 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7889 WidenedStoreVT.getStoreSizeInBits()); 7890 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7891 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7892 } 7893 7894 assert(isTypeLegal(StoreVT)); 7895 return VData; 7896 } 7897 7898 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7899 SelectionDAG &DAG) const { 7900 SDLoc DL(Op); 7901 SDValue Chain = Op.getOperand(0); 7902 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7903 MachineFunction &MF = DAG.getMachineFunction(); 7904 7905 switch (IntrinsicID) { 7906 case Intrinsic::amdgcn_exp_compr: { 7907 SDValue Src0 = Op.getOperand(4); 7908 SDValue Src1 = Op.getOperand(5); 7909 // Hack around illegal type on SI by directly selecting it. 7910 if (isTypeLegal(Src0.getValueType())) 7911 return SDValue(); 7912 7913 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7914 SDValue Undef = DAG.getUNDEF(MVT::f32); 7915 const SDValue Ops[] = { 7916 Op.getOperand(2), // tgt 7917 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7918 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7919 Undef, // src2 7920 Undef, // src3 7921 Op.getOperand(7), // vm 7922 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7923 Op.getOperand(3), // en 7924 Op.getOperand(0) // Chain 7925 }; 7926 7927 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7928 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7929 } 7930 case Intrinsic::amdgcn_s_barrier: { 7931 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7932 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7933 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7934 if (WGSize <= ST.getWavefrontSize()) 7935 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7936 Op.getOperand(0)), 0); 7937 } 7938 return SDValue(); 7939 }; 7940 case Intrinsic::amdgcn_tbuffer_store: { 7941 SDValue VData = Op.getOperand(2); 7942 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7943 if (IsD16) 7944 VData = handleD16VData(VData, DAG); 7945 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7946 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7947 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7948 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7949 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7950 SDValue Ops[] = { 7951 Chain, 7952 VData, // vdata 7953 Op.getOperand(3), // rsrc 7954 Op.getOperand(4), // vindex 7955 Op.getOperand(5), // voffset 7956 Op.getOperand(6), // soffset 7957 Op.getOperand(7), // offset 7958 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7959 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7960 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7961 }; 7962 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7963 AMDGPUISD::TBUFFER_STORE_FORMAT; 7964 MemSDNode *M = cast<MemSDNode>(Op); 7965 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7966 M->getMemoryVT(), M->getMemOperand()); 7967 } 7968 7969 case Intrinsic::amdgcn_struct_tbuffer_store: { 7970 SDValue VData = Op.getOperand(2); 7971 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7972 if (IsD16) 7973 VData = handleD16VData(VData, DAG); 7974 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7975 SDValue Ops[] = { 7976 Chain, 7977 VData, // vdata 7978 Op.getOperand(3), // rsrc 7979 Op.getOperand(4), // vindex 7980 Offsets.first, // voffset 7981 Op.getOperand(6), // soffset 7982 Offsets.second, // offset 7983 Op.getOperand(7), // format 7984 Op.getOperand(8), // cachepolicy, swizzled buffer 7985 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7986 }; 7987 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7988 AMDGPUISD::TBUFFER_STORE_FORMAT; 7989 MemSDNode *M = cast<MemSDNode>(Op); 7990 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7991 M->getMemoryVT(), M->getMemOperand()); 7992 } 7993 7994 case Intrinsic::amdgcn_raw_tbuffer_store: { 7995 SDValue VData = Op.getOperand(2); 7996 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7997 if (IsD16) 7998 VData = handleD16VData(VData, DAG); 7999 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8000 SDValue Ops[] = { 8001 Chain, 8002 VData, // vdata 8003 Op.getOperand(3), // rsrc 8004 DAG.getConstant(0, DL, MVT::i32), // vindex 8005 Offsets.first, // voffset 8006 Op.getOperand(5), // soffset 8007 Offsets.second, // offset 8008 Op.getOperand(6), // format 8009 Op.getOperand(7), // cachepolicy, swizzled buffer 8010 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8011 }; 8012 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8013 AMDGPUISD::TBUFFER_STORE_FORMAT; 8014 MemSDNode *M = cast<MemSDNode>(Op); 8015 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8016 M->getMemoryVT(), M->getMemOperand()); 8017 } 8018 8019 case Intrinsic::amdgcn_buffer_store: 8020 case Intrinsic::amdgcn_buffer_store_format: { 8021 SDValue VData = Op.getOperand(2); 8022 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8023 if (IsD16) 8024 VData = handleD16VData(VData, DAG); 8025 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8026 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8027 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8028 SDValue Ops[] = { 8029 Chain, 8030 VData, 8031 Op.getOperand(3), // rsrc 8032 Op.getOperand(4), // vindex 8033 SDValue(), // voffset -- will be set by setBufferOffsets 8034 SDValue(), // soffset -- will be set by setBufferOffsets 8035 SDValue(), // offset -- will be set by setBufferOffsets 8036 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8037 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8038 }; 8039 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8040 8041 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8042 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8043 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8044 MemSDNode *M = cast<MemSDNode>(Op); 8045 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8046 8047 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8048 EVT VDataType = VData.getValueType().getScalarType(); 8049 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8050 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8051 8052 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8053 M->getMemoryVT(), M->getMemOperand()); 8054 } 8055 8056 case Intrinsic::amdgcn_raw_buffer_store: 8057 case Intrinsic::amdgcn_raw_buffer_store_format: { 8058 const bool IsFormat = 8059 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8060 8061 SDValue VData = Op.getOperand(2); 8062 EVT VDataVT = VData.getValueType(); 8063 EVT EltType = VDataVT.getScalarType(); 8064 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8065 if (IsD16) { 8066 VData = handleD16VData(VData, DAG); 8067 VDataVT = VData.getValueType(); 8068 } 8069 8070 if (!isTypeLegal(VDataVT)) { 8071 VData = 8072 DAG.getNode(ISD::BITCAST, DL, 8073 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8074 } 8075 8076 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8077 SDValue Ops[] = { 8078 Chain, 8079 VData, 8080 Op.getOperand(3), // rsrc 8081 DAG.getConstant(0, DL, MVT::i32), // vindex 8082 Offsets.first, // voffset 8083 Op.getOperand(5), // soffset 8084 Offsets.second, // offset 8085 Op.getOperand(6), // cachepolicy, swizzled buffer 8086 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8087 }; 8088 unsigned Opc = 8089 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8090 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8091 MemSDNode *M = cast<MemSDNode>(Op); 8092 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8093 8094 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8095 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8096 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8097 8098 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8099 M->getMemoryVT(), M->getMemOperand()); 8100 } 8101 8102 case Intrinsic::amdgcn_struct_buffer_store: 8103 case Intrinsic::amdgcn_struct_buffer_store_format: { 8104 const bool IsFormat = 8105 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8106 8107 SDValue VData = Op.getOperand(2); 8108 EVT VDataVT = VData.getValueType(); 8109 EVT EltType = VDataVT.getScalarType(); 8110 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8111 8112 if (IsD16) { 8113 VData = handleD16VData(VData, DAG); 8114 VDataVT = VData.getValueType(); 8115 } 8116 8117 if (!isTypeLegal(VDataVT)) { 8118 VData = 8119 DAG.getNode(ISD::BITCAST, DL, 8120 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8121 } 8122 8123 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8124 SDValue Ops[] = { 8125 Chain, 8126 VData, 8127 Op.getOperand(3), // rsrc 8128 Op.getOperand(4), // vindex 8129 Offsets.first, // voffset 8130 Op.getOperand(6), // soffset 8131 Offsets.second, // offset 8132 Op.getOperand(7), // cachepolicy, swizzled buffer 8133 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8134 }; 8135 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8136 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8137 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8138 MemSDNode *M = cast<MemSDNode>(Op); 8139 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8140 8141 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8142 EVT VDataType = VData.getValueType().getScalarType(); 8143 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8144 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8145 8146 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8147 M->getMemoryVT(), M->getMemOperand()); 8148 } 8149 case Intrinsic::amdgcn_end_cf: 8150 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8151 Op->getOperand(2), Chain), 0); 8152 8153 default: { 8154 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8155 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8156 return lowerImage(Op, ImageDimIntr, DAG, true); 8157 8158 return Op; 8159 } 8160 } 8161 } 8162 8163 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8164 // offset (the offset that is included in bounds checking and swizzling, to be 8165 // split between the instruction's voffset and immoffset fields) and soffset 8166 // (the offset that is excluded from bounds checking and swizzling, to go in 8167 // the instruction's soffset field). This function takes the first kind of 8168 // offset and figures out how to split it between voffset and immoffset. 8169 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8170 SDValue Offset, SelectionDAG &DAG) const { 8171 SDLoc DL(Offset); 8172 const unsigned MaxImm = 4095; 8173 SDValue N0 = Offset; 8174 ConstantSDNode *C1 = nullptr; 8175 8176 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8177 N0 = SDValue(); 8178 else if (DAG.isBaseWithConstantOffset(N0)) { 8179 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8180 N0 = N0.getOperand(0); 8181 } 8182 8183 if (C1) { 8184 unsigned ImmOffset = C1->getZExtValue(); 8185 // If the immediate value is too big for the immoffset field, put the value 8186 // and -4096 into the immoffset field so that the value that is copied/added 8187 // for the voffset field is a multiple of 4096, and it stands more chance 8188 // of being CSEd with the copy/add for another similar load/store. 8189 // However, do not do that rounding down to a multiple of 4096 if that is a 8190 // negative number, as it appears to be illegal to have a negative offset 8191 // in the vgpr, even if adding the immediate offset makes it positive. 8192 unsigned Overflow = ImmOffset & ~MaxImm; 8193 ImmOffset -= Overflow; 8194 if ((int32_t)Overflow < 0) { 8195 Overflow += ImmOffset; 8196 ImmOffset = 0; 8197 } 8198 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8199 if (Overflow) { 8200 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8201 if (!N0) 8202 N0 = OverflowVal; 8203 else { 8204 SDValue Ops[] = { N0, OverflowVal }; 8205 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8206 } 8207 } 8208 } 8209 if (!N0) 8210 N0 = DAG.getConstant(0, DL, MVT::i32); 8211 if (!C1) 8212 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8213 return {N0, SDValue(C1, 0)}; 8214 } 8215 8216 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8217 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8218 // pointed to by Offsets. 8219 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8220 SelectionDAG &DAG, SDValue *Offsets, 8221 Align Alignment) const { 8222 SDLoc DL(CombinedOffset); 8223 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8224 uint32_t Imm = C->getZExtValue(); 8225 uint32_t SOffset, ImmOffset; 8226 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8227 Alignment)) { 8228 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8229 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8230 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8231 return; 8232 } 8233 } 8234 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8235 SDValue N0 = CombinedOffset.getOperand(0); 8236 SDValue N1 = CombinedOffset.getOperand(1); 8237 uint32_t SOffset, ImmOffset; 8238 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8239 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8240 Subtarget, Alignment)) { 8241 Offsets[0] = N0; 8242 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8243 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8244 return; 8245 } 8246 } 8247 Offsets[0] = CombinedOffset; 8248 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8249 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8250 } 8251 8252 // Handle 8 bit and 16 bit buffer loads 8253 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8254 EVT LoadVT, SDLoc DL, 8255 ArrayRef<SDValue> Ops, 8256 MemSDNode *M) const { 8257 EVT IntVT = LoadVT.changeTypeToInteger(); 8258 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8259 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8260 8261 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8262 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8263 Ops, IntVT, 8264 M->getMemOperand()); 8265 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8266 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8267 8268 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8269 } 8270 8271 // Handle 8 bit and 16 bit buffer stores 8272 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8273 EVT VDataType, SDLoc DL, 8274 SDValue Ops[], 8275 MemSDNode *M) const { 8276 if (VDataType == MVT::f16) 8277 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8278 8279 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8280 Ops[1] = BufferStoreExt; 8281 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8282 AMDGPUISD::BUFFER_STORE_SHORT; 8283 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8284 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8285 M->getMemOperand()); 8286 } 8287 8288 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8289 ISD::LoadExtType ExtType, SDValue Op, 8290 const SDLoc &SL, EVT VT) { 8291 if (VT.bitsLT(Op.getValueType())) 8292 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8293 8294 switch (ExtType) { 8295 case ISD::SEXTLOAD: 8296 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8297 case ISD::ZEXTLOAD: 8298 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8299 case ISD::EXTLOAD: 8300 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8301 case ISD::NON_EXTLOAD: 8302 return Op; 8303 } 8304 8305 llvm_unreachable("invalid ext type"); 8306 } 8307 8308 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8309 SelectionDAG &DAG = DCI.DAG; 8310 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8311 return SDValue(); 8312 8313 // FIXME: Constant loads should all be marked invariant. 8314 unsigned AS = Ld->getAddressSpace(); 8315 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8316 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8317 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8318 return SDValue(); 8319 8320 // Don't do this early, since it may interfere with adjacent load merging for 8321 // illegal types. We can avoid losing alignment information for exotic types 8322 // pre-legalize. 8323 EVT MemVT = Ld->getMemoryVT(); 8324 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8325 MemVT.getSizeInBits() >= 32) 8326 return SDValue(); 8327 8328 SDLoc SL(Ld); 8329 8330 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8331 "unexpected vector extload"); 8332 8333 // TODO: Drop only high part of range. 8334 SDValue Ptr = Ld->getBasePtr(); 8335 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8336 MVT::i32, SL, Ld->getChain(), Ptr, 8337 Ld->getOffset(), 8338 Ld->getPointerInfo(), MVT::i32, 8339 Ld->getAlignment(), 8340 Ld->getMemOperand()->getFlags(), 8341 Ld->getAAInfo(), 8342 nullptr); // Drop ranges 8343 8344 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8345 if (MemVT.isFloatingPoint()) { 8346 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8347 "unexpected fp extload"); 8348 TruncVT = MemVT.changeTypeToInteger(); 8349 } 8350 8351 SDValue Cvt = NewLoad; 8352 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8353 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8354 DAG.getValueType(TruncVT)); 8355 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8356 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8357 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8358 } else { 8359 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8360 } 8361 8362 EVT VT = Ld->getValueType(0); 8363 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8364 8365 DCI.AddToWorklist(Cvt.getNode()); 8366 8367 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8368 // the appropriate extension from the 32-bit load. 8369 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8370 DCI.AddToWorklist(Cvt.getNode()); 8371 8372 // Handle conversion back to floating point if necessary. 8373 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8374 8375 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8376 } 8377 8378 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8379 SDLoc DL(Op); 8380 LoadSDNode *Load = cast<LoadSDNode>(Op); 8381 ISD::LoadExtType ExtType = Load->getExtensionType(); 8382 EVT MemVT = Load->getMemoryVT(); 8383 8384 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8385 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8386 return SDValue(); 8387 8388 // FIXME: Copied from PPC 8389 // First, load into 32 bits, then truncate to 1 bit. 8390 8391 SDValue Chain = Load->getChain(); 8392 SDValue BasePtr = Load->getBasePtr(); 8393 MachineMemOperand *MMO = Load->getMemOperand(); 8394 8395 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8396 8397 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8398 BasePtr, RealMemVT, MMO); 8399 8400 if (!MemVT.isVector()) { 8401 SDValue Ops[] = { 8402 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8403 NewLD.getValue(1) 8404 }; 8405 8406 return DAG.getMergeValues(Ops, DL); 8407 } 8408 8409 SmallVector<SDValue, 3> Elts; 8410 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8411 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8412 DAG.getConstant(I, DL, MVT::i32)); 8413 8414 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8415 } 8416 8417 SDValue Ops[] = { 8418 DAG.getBuildVector(MemVT, DL, Elts), 8419 NewLD.getValue(1) 8420 }; 8421 8422 return DAG.getMergeValues(Ops, DL); 8423 } 8424 8425 if (!MemVT.isVector()) 8426 return SDValue(); 8427 8428 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8429 "Custom lowering for non-i32 vectors hasn't been implemented."); 8430 8431 unsigned Alignment = Load->getAlignment(); 8432 unsigned AS = Load->getAddressSpace(); 8433 if (Subtarget->hasLDSMisalignedBug() && 8434 AS == AMDGPUAS::FLAT_ADDRESS && 8435 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8436 return SplitVectorLoad(Op, DAG); 8437 } 8438 8439 MachineFunction &MF = DAG.getMachineFunction(); 8440 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8441 // If there is a possibility that flat instruction access scratch memory 8442 // then we need to use the same legalization rules we use for private. 8443 if (AS == AMDGPUAS::FLAT_ADDRESS && 8444 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8445 AS = MFI->hasFlatScratchInit() ? 8446 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8447 8448 unsigned NumElements = MemVT.getVectorNumElements(); 8449 8450 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8451 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8452 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8453 if (MemVT.isPow2VectorType()) 8454 return SDValue(); 8455 return WidenOrSplitVectorLoad(Op, DAG); 8456 } 8457 // Non-uniform loads will be selected to MUBUF instructions, so they 8458 // have the same legalization requirements as global and private 8459 // loads. 8460 // 8461 } 8462 8463 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8464 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8465 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8466 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8467 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8468 Alignment >= 4 && NumElements < 32) { 8469 if (MemVT.isPow2VectorType()) 8470 return SDValue(); 8471 return WidenOrSplitVectorLoad(Op, DAG); 8472 } 8473 // Non-uniform loads will be selected to MUBUF instructions, so they 8474 // have the same legalization requirements as global and private 8475 // loads. 8476 // 8477 } 8478 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8479 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8480 AS == AMDGPUAS::GLOBAL_ADDRESS || 8481 AS == AMDGPUAS::FLAT_ADDRESS) { 8482 if (NumElements > 4) 8483 return SplitVectorLoad(Op, DAG); 8484 // v3 loads not supported on SI. 8485 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8486 return WidenOrSplitVectorLoad(Op, DAG); 8487 8488 // v3 and v4 loads are supported for private and global memory. 8489 return SDValue(); 8490 } 8491 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8492 // Depending on the setting of the private_element_size field in the 8493 // resource descriptor, we can only make private accesses up to a certain 8494 // size. 8495 switch (Subtarget->getMaxPrivateElementSize()) { 8496 case 4: { 8497 SDValue Ops[2]; 8498 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8499 return DAG.getMergeValues(Ops, DL); 8500 } 8501 case 8: 8502 if (NumElements > 2) 8503 return SplitVectorLoad(Op, DAG); 8504 return SDValue(); 8505 case 16: 8506 // Same as global/flat 8507 if (NumElements > 4) 8508 return SplitVectorLoad(Op, DAG); 8509 // v3 loads not supported on SI. 8510 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8511 return WidenOrSplitVectorLoad(Op, DAG); 8512 8513 return SDValue(); 8514 default: 8515 llvm_unreachable("unsupported private_element_size"); 8516 } 8517 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8518 // Use ds_read_b128 or ds_read_b96 when possible. 8519 if (Subtarget->hasDS96AndDS128() && 8520 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8521 MemVT.getStoreSize() == 12) && 8522 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8523 Load->getAlign())) 8524 return SDValue(); 8525 8526 if (NumElements > 2) 8527 return SplitVectorLoad(Op, DAG); 8528 8529 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 8530 // address is negative, then the instruction is incorrectly treated as 8531 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8532 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8533 // load later in the SILoadStoreOptimizer. 8534 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8535 NumElements == 2 && MemVT.getStoreSize() == 8 && 8536 Load->getAlignment() < 8) { 8537 return SplitVectorLoad(Op, DAG); 8538 } 8539 } 8540 8541 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8542 MemVT, *Load->getMemOperand())) { 8543 SDValue Ops[2]; 8544 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8545 return DAG.getMergeValues(Ops, DL); 8546 } 8547 8548 return SDValue(); 8549 } 8550 8551 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8552 EVT VT = Op.getValueType(); 8553 if (VT.getSizeInBits() == 128) 8554 return splitTernaryVectorOp(Op, DAG); 8555 8556 assert(VT.getSizeInBits() == 64); 8557 8558 SDLoc DL(Op); 8559 SDValue Cond = Op.getOperand(0); 8560 8561 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8562 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8563 8564 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8565 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8566 8567 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8568 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8569 8570 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8571 8572 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8573 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8574 8575 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8576 8577 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8578 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8579 } 8580 8581 // Catch division cases where we can use shortcuts with rcp and rsq 8582 // instructions. 8583 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8584 SelectionDAG &DAG) const { 8585 SDLoc SL(Op); 8586 SDValue LHS = Op.getOperand(0); 8587 SDValue RHS = Op.getOperand(1); 8588 EVT VT = Op.getValueType(); 8589 const SDNodeFlags Flags = Op->getFlags(); 8590 8591 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8592 8593 // Without !fpmath accuracy information, we can't do more because we don't 8594 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8595 if (!AllowInaccurateRcp) 8596 return SDValue(); 8597 8598 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8599 if (CLHS->isExactlyValue(1.0)) { 8600 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8601 // the CI documentation has a worst case error of 1 ulp. 8602 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8603 // use it as long as we aren't trying to use denormals. 8604 // 8605 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8606 8607 // 1.0 / sqrt(x) -> rsq(x) 8608 8609 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8610 // error seems really high at 2^29 ULP. 8611 if (RHS.getOpcode() == ISD::FSQRT) 8612 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8613 8614 // 1.0 / x -> rcp(x) 8615 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8616 } 8617 8618 // Same as for 1.0, but expand the sign out of the constant. 8619 if (CLHS->isExactlyValue(-1.0)) { 8620 // -1.0 / x -> rcp (fneg x) 8621 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8622 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8623 } 8624 } 8625 8626 // Turn into multiply by the reciprocal. 8627 // x / y -> x * (1.0 / y) 8628 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8629 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8630 } 8631 8632 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8633 SelectionDAG &DAG) const { 8634 SDLoc SL(Op); 8635 SDValue X = Op.getOperand(0); 8636 SDValue Y = Op.getOperand(1); 8637 EVT VT = Op.getValueType(); 8638 const SDNodeFlags Flags = Op->getFlags(); 8639 8640 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8641 DAG.getTarget().Options.UnsafeFPMath; 8642 if (!AllowInaccurateDiv) 8643 return SDValue(); 8644 8645 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8646 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8647 8648 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8649 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8650 8651 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8652 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8653 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8654 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8655 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8656 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8657 } 8658 8659 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8660 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8661 SDNodeFlags Flags) { 8662 if (GlueChain->getNumValues() <= 1) { 8663 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8664 } 8665 8666 assert(GlueChain->getNumValues() == 3); 8667 8668 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8669 switch (Opcode) { 8670 default: llvm_unreachable("no chain equivalent for opcode"); 8671 case ISD::FMUL: 8672 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8673 break; 8674 } 8675 8676 return DAG.getNode(Opcode, SL, VTList, 8677 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8678 Flags); 8679 } 8680 8681 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8682 EVT VT, SDValue A, SDValue B, SDValue C, 8683 SDValue GlueChain, SDNodeFlags Flags) { 8684 if (GlueChain->getNumValues() <= 1) { 8685 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8686 } 8687 8688 assert(GlueChain->getNumValues() == 3); 8689 8690 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8691 switch (Opcode) { 8692 default: llvm_unreachable("no chain equivalent for opcode"); 8693 case ISD::FMA: 8694 Opcode = AMDGPUISD::FMA_W_CHAIN; 8695 break; 8696 } 8697 8698 return DAG.getNode(Opcode, SL, VTList, 8699 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8700 Flags); 8701 } 8702 8703 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8704 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8705 return FastLowered; 8706 8707 SDLoc SL(Op); 8708 SDValue Src0 = Op.getOperand(0); 8709 SDValue Src1 = Op.getOperand(1); 8710 8711 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8712 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8713 8714 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8715 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8716 8717 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8718 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8719 8720 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8721 } 8722 8723 // Faster 2.5 ULP division that does not support denormals. 8724 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8725 SDLoc SL(Op); 8726 SDValue LHS = Op.getOperand(1); 8727 SDValue RHS = Op.getOperand(2); 8728 8729 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8730 8731 const APFloat K0Val(BitsToFloat(0x6f800000)); 8732 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8733 8734 const APFloat K1Val(BitsToFloat(0x2f800000)); 8735 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8736 8737 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8738 8739 EVT SetCCVT = 8740 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8741 8742 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8743 8744 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8745 8746 // TODO: Should this propagate fast-math-flags? 8747 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8748 8749 // rcp does not support denormals. 8750 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8751 8752 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8753 8754 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8755 } 8756 8757 // Returns immediate value for setting the F32 denorm mode when using the 8758 // S_DENORM_MODE instruction. 8759 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8760 const SDLoc &SL, const GCNSubtarget *ST) { 8761 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8762 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8763 ? FP_DENORM_FLUSH_NONE 8764 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8765 8766 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8767 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8768 } 8769 8770 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8771 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8772 return FastLowered; 8773 8774 // The selection matcher assumes anything with a chain selecting to a 8775 // mayRaiseFPException machine instruction. Since we're introducing a chain 8776 // here, we need to explicitly report nofpexcept for the regular fdiv 8777 // lowering. 8778 SDNodeFlags Flags = Op->getFlags(); 8779 Flags.setNoFPExcept(true); 8780 8781 SDLoc SL(Op); 8782 SDValue LHS = Op.getOperand(0); 8783 SDValue RHS = Op.getOperand(1); 8784 8785 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8786 8787 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8788 8789 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8790 {RHS, RHS, LHS}, Flags); 8791 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8792 {LHS, RHS, LHS}, Flags); 8793 8794 // Denominator is scaled to not be denormal, so using rcp is ok. 8795 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8796 DenominatorScaled, Flags); 8797 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8798 DenominatorScaled, Flags); 8799 8800 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8801 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8802 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8803 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8804 8805 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8806 8807 if (!HasFP32Denormals) { 8808 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8809 // lowering. The chain dependence is insufficient, and we need glue. We do 8810 // not need the glue variants in a strictfp function. 8811 8812 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8813 8814 SDNode *EnableDenorm; 8815 if (Subtarget->hasDenormModeInst()) { 8816 const SDValue EnableDenormValue = 8817 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8818 8819 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8820 DAG.getEntryNode(), EnableDenormValue).getNode(); 8821 } else { 8822 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8823 SL, MVT::i32); 8824 EnableDenorm = 8825 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8826 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8827 } 8828 8829 SDValue Ops[3] = { 8830 NegDivScale0, 8831 SDValue(EnableDenorm, 0), 8832 SDValue(EnableDenorm, 1) 8833 }; 8834 8835 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8836 } 8837 8838 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8839 ApproxRcp, One, NegDivScale0, Flags); 8840 8841 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8842 ApproxRcp, Fma0, Flags); 8843 8844 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8845 Fma1, Fma1, Flags); 8846 8847 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8848 NumeratorScaled, Mul, Flags); 8849 8850 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8851 Fma2, Fma1, Mul, Fma2, Flags); 8852 8853 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8854 NumeratorScaled, Fma3, Flags); 8855 8856 if (!HasFP32Denormals) { 8857 SDNode *DisableDenorm; 8858 if (Subtarget->hasDenormModeInst()) { 8859 const SDValue DisableDenormValue = 8860 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8861 8862 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8863 Fma4.getValue(1), DisableDenormValue, 8864 Fma4.getValue(2)).getNode(); 8865 } else { 8866 const SDValue DisableDenormValue = 8867 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8868 8869 DisableDenorm = DAG.getMachineNode( 8870 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8871 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8872 } 8873 8874 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8875 SDValue(DisableDenorm, 0), DAG.getRoot()); 8876 DAG.setRoot(OutputChain); 8877 } 8878 8879 SDValue Scale = NumeratorScaled.getValue(1); 8880 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8881 {Fma4, Fma1, Fma3, Scale}, Flags); 8882 8883 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8884 } 8885 8886 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8887 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8888 return FastLowered; 8889 8890 SDLoc SL(Op); 8891 SDValue X = Op.getOperand(0); 8892 SDValue Y = Op.getOperand(1); 8893 8894 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8895 8896 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8897 8898 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8899 8900 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8901 8902 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8903 8904 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8905 8906 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8907 8908 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8909 8910 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8911 8912 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8913 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8914 8915 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8916 NegDivScale0, Mul, DivScale1); 8917 8918 SDValue Scale; 8919 8920 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8921 // Workaround a hardware bug on SI where the condition output from div_scale 8922 // is not usable. 8923 8924 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8925 8926 // Figure out if the scale to use for div_fmas. 8927 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8928 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8929 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8930 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8931 8932 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8933 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8934 8935 SDValue Scale0Hi 8936 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8937 SDValue Scale1Hi 8938 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8939 8940 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8941 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8942 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8943 } else { 8944 Scale = DivScale1.getValue(1); 8945 } 8946 8947 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8948 Fma4, Fma3, Mul, Scale); 8949 8950 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8951 } 8952 8953 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8954 EVT VT = Op.getValueType(); 8955 8956 if (VT == MVT::f32) 8957 return LowerFDIV32(Op, DAG); 8958 8959 if (VT == MVT::f64) 8960 return LowerFDIV64(Op, DAG); 8961 8962 if (VT == MVT::f16) 8963 return LowerFDIV16(Op, DAG); 8964 8965 llvm_unreachable("Unexpected type for fdiv"); 8966 } 8967 8968 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8969 SDLoc DL(Op); 8970 StoreSDNode *Store = cast<StoreSDNode>(Op); 8971 EVT VT = Store->getMemoryVT(); 8972 8973 if (VT == MVT::i1) { 8974 return DAG.getTruncStore(Store->getChain(), DL, 8975 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8976 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8977 } 8978 8979 assert(VT.isVector() && 8980 Store->getValue().getValueType().getScalarType() == MVT::i32); 8981 8982 unsigned AS = Store->getAddressSpace(); 8983 if (Subtarget->hasLDSMisalignedBug() && 8984 AS == AMDGPUAS::FLAT_ADDRESS && 8985 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8986 return SplitVectorStore(Op, DAG); 8987 } 8988 8989 MachineFunction &MF = DAG.getMachineFunction(); 8990 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8991 // If there is a possibility that flat instruction access scratch memory 8992 // then we need to use the same legalization rules we use for private. 8993 if (AS == AMDGPUAS::FLAT_ADDRESS && 8994 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8995 AS = MFI->hasFlatScratchInit() ? 8996 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8997 8998 unsigned NumElements = VT.getVectorNumElements(); 8999 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9000 AS == AMDGPUAS::FLAT_ADDRESS) { 9001 if (NumElements > 4) 9002 return SplitVectorStore(Op, DAG); 9003 // v3 stores not supported on SI. 9004 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9005 return SplitVectorStore(Op, DAG); 9006 9007 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9008 VT, *Store->getMemOperand())) 9009 return expandUnalignedStore(Store, DAG); 9010 9011 return SDValue(); 9012 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9013 switch (Subtarget->getMaxPrivateElementSize()) { 9014 case 4: 9015 return scalarizeVectorStore(Store, DAG); 9016 case 8: 9017 if (NumElements > 2) 9018 return SplitVectorStore(Op, DAG); 9019 return SDValue(); 9020 case 16: 9021 if (NumElements > 4 || 9022 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9023 return SplitVectorStore(Op, DAG); 9024 return SDValue(); 9025 default: 9026 llvm_unreachable("unsupported private_element_size"); 9027 } 9028 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9029 // Use ds_write_b128 or ds_write_b96 when possible. 9030 if (Subtarget->hasDS96AndDS128() && 9031 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 9032 (VT.getStoreSize() == 12)) && 9033 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9034 Store->getAlign())) 9035 return SDValue(); 9036 9037 if (NumElements > 2) 9038 return SplitVectorStore(Op, DAG); 9039 9040 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 9041 // address is negative, then the instruction is incorrectly treated as 9042 // out-of-bounds even if base + offsets is in bounds. Split vectorized 9043 // stores here to avoid emitting ds_write2_b32. We may re-combine the 9044 // store later in the SILoadStoreOptimizer. 9045 if (!Subtarget->hasUsableDSOffset() && 9046 NumElements == 2 && VT.getStoreSize() == 8 && 9047 Store->getAlignment() < 8) { 9048 return SplitVectorStore(Op, DAG); 9049 } 9050 9051 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9052 VT, *Store->getMemOperand())) { 9053 if (VT.isVector()) 9054 return SplitVectorStore(Op, DAG); 9055 return expandUnalignedStore(Store, DAG); 9056 } 9057 9058 return SDValue(); 9059 } else { 9060 llvm_unreachable("unhandled address space"); 9061 } 9062 } 9063 9064 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9065 SDLoc DL(Op); 9066 EVT VT = Op.getValueType(); 9067 SDValue Arg = Op.getOperand(0); 9068 SDValue TrigVal; 9069 9070 // Propagate fast-math flags so that the multiply we introduce can be folded 9071 // if Arg is already the result of a multiply by constant. 9072 auto Flags = Op->getFlags(); 9073 9074 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9075 9076 if (Subtarget->hasTrigReducedRange()) { 9077 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9078 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9079 } else { 9080 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9081 } 9082 9083 switch (Op.getOpcode()) { 9084 case ISD::FCOS: 9085 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9086 case ISD::FSIN: 9087 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9088 default: 9089 llvm_unreachable("Wrong trig opcode"); 9090 } 9091 } 9092 9093 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9094 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9095 assert(AtomicNode->isCompareAndSwap()); 9096 unsigned AS = AtomicNode->getAddressSpace(); 9097 9098 // No custom lowering required for local address space 9099 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9100 return Op; 9101 9102 // Non-local address space requires custom lowering for atomic compare 9103 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9104 SDLoc DL(Op); 9105 SDValue ChainIn = Op.getOperand(0); 9106 SDValue Addr = Op.getOperand(1); 9107 SDValue Old = Op.getOperand(2); 9108 SDValue New = Op.getOperand(3); 9109 EVT VT = Op.getValueType(); 9110 MVT SimpleVT = VT.getSimpleVT(); 9111 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9112 9113 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9114 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9115 9116 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9117 Ops, VT, AtomicNode->getMemOperand()); 9118 } 9119 9120 //===----------------------------------------------------------------------===// 9121 // Custom DAG optimizations 9122 //===----------------------------------------------------------------------===// 9123 9124 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9125 DAGCombinerInfo &DCI) const { 9126 EVT VT = N->getValueType(0); 9127 EVT ScalarVT = VT.getScalarType(); 9128 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9129 return SDValue(); 9130 9131 SelectionDAG &DAG = DCI.DAG; 9132 SDLoc DL(N); 9133 9134 SDValue Src = N->getOperand(0); 9135 EVT SrcVT = Src.getValueType(); 9136 9137 // TODO: We could try to match extracting the higher bytes, which would be 9138 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9139 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9140 // about in practice. 9141 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9142 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9143 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9144 DCI.AddToWorklist(Cvt.getNode()); 9145 9146 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9147 if (ScalarVT != MVT::f32) { 9148 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9149 DAG.getTargetConstant(0, DL, MVT::i32)); 9150 } 9151 return Cvt; 9152 } 9153 } 9154 9155 return SDValue(); 9156 } 9157 9158 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9159 9160 // This is a variant of 9161 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9162 // 9163 // The normal DAG combiner will do this, but only if the add has one use since 9164 // that would increase the number of instructions. 9165 // 9166 // This prevents us from seeing a constant offset that can be folded into a 9167 // memory instruction's addressing mode. If we know the resulting add offset of 9168 // a pointer can be folded into an addressing offset, we can replace the pointer 9169 // operand with the add of new constant offset. This eliminates one of the uses, 9170 // and may allow the remaining use to also be simplified. 9171 // 9172 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9173 unsigned AddrSpace, 9174 EVT MemVT, 9175 DAGCombinerInfo &DCI) const { 9176 SDValue N0 = N->getOperand(0); 9177 SDValue N1 = N->getOperand(1); 9178 9179 // We only do this to handle cases where it's profitable when there are 9180 // multiple uses of the add, so defer to the standard combine. 9181 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9182 N0->hasOneUse()) 9183 return SDValue(); 9184 9185 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9186 if (!CN1) 9187 return SDValue(); 9188 9189 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9190 if (!CAdd) 9191 return SDValue(); 9192 9193 // If the resulting offset is too large, we can't fold it into the addressing 9194 // mode offset. 9195 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9196 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9197 9198 AddrMode AM; 9199 AM.HasBaseReg = true; 9200 AM.BaseOffs = Offset.getSExtValue(); 9201 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9202 return SDValue(); 9203 9204 SelectionDAG &DAG = DCI.DAG; 9205 SDLoc SL(N); 9206 EVT VT = N->getValueType(0); 9207 9208 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9209 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9210 9211 SDNodeFlags Flags; 9212 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9213 (N0.getOpcode() == ISD::OR || 9214 N0->getFlags().hasNoUnsignedWrap())); 9215 9216 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9217 } 9218 9219 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9220 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9221 /// specific intrinsic, but they all place the pointer operand first. 9222 static unsigned getBasePtrIndex(const MemSDNode *N) { 9223 switch (N->getOpcode()) { 9224 case ISD::STORE: 9225 case ISD::INTRINSIC_W_CHAIN: 9226 case ISD::INTRINSIC_VOID: 9227 return 2; 9228 default: 9229 return 1; 9230 } 9231 } 9232 9233 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9234 DAGCombinerInfo &DCI) const { 9235 SelectionDAG &DAG = DCI.DAG; 9236 SDLoc SL(N); 9237 9238 unsigned PtrIdx = getBasePtrIndex(N); 9239 SDValue Ptr = N->getOperand(PtrIdx); 9240 9241 // TODO: We could also do this for multiplies. 9242 if (Ptr.getOpcode() == ISD::SHL) { 9243 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9244 N->getMemoryVT(), DCI); 9245 if (NewPtr) { 9246 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9247 9248 NewOps[PtrIdx] = NewPtr; 9249 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9250 } 9251 } 9252 9253 return SDValue(); 9254 } 9255 9256 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9257 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9258 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9259 (Opc == ISD::XOR && Val == 0); 9260 } 9261 9262 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9263 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9264 // integer combine opportunities since most 64-bit operations are decomposed 9265 // this way. TODO: We won't want this for SALU especially if it is an inline 9266 // immediate. 9267 SDValue SITargetLowering::splitBinaryBitConstantOp( 9268 DAGCombinerInfo &DCI, 9269 const SDLoc &SL, 9270 unsigned Opc, SDValue LHS, 9271 const ConstantSDNode *CRHS) const { 9272 uint64_t Val = CRHS->getZExtValue(); 9273 uint32_t ValLo = Lo_32(Val); 9274 uint32_t ValHi = Hi_32(Val); 9275 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9276 9277 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9278 bitOpWithConstantIsReducible(Opc, ValHi)) || 9279 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9280 // If we need to materialize a 64-bit immediate, it will be split up later 9281 // anyway. Avoid creating the harder to understand 64-bit immediate 9282 // materialization. 9283 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9284 } 9285 9286 return SDValue(); 9287 } 9288 9289 // Returns true if argument is a boolean value which is not serialized into 9290 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9291 static bool isBoolSGPR(SDValue V) { 9292 if (V.getValueType() != MVT::i1) 9293 return false; 9294 switch (V.getOpcode()) { 9295 default: 9296 break; 9297 case ISD::SETCC: 9298 case AMDGPUISD::FP_CLASS: 9299 return true; 9300 case ISD::AND: 9301 case ISD::OR: 9302 case ISD::XOR: 9303 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9304 } 9305 return false; 9306 } 9307 9308 // If a constant has all zeroes or all ones within each byte return it. 9309 // Otherwise return 0. 9310 static uint32_t getConstantPermuteMask(uint32_t C) { 9311 // 0xff for any zero byte in the mask 9312 uint32_t ZeroByteMask = 0; 9313 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9314 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9315 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9316 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9317 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9318 if ((NonZeroByteMask & C) != NonZeroByteMask) 9319 return 0; // Partial bytes selected. 9320 return C; 9321 } 9322 9323 // Check if a node selects whole bytes from its operand 0 starting at a byte 9324 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9325 // or -1 if not succeeded. 9326 // Note byte select encoding: 9327 // value 0-3 selects corresponding source byte; 9328 // value 0xc selects zero; 9329 // value 0xff selects 0xff. 9330 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9331 assert(V.getValueSizeInBits() == 32); 9332 9333 if (V.getNumOperands() != 2) 9334 return ~0; 9335 9336 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9337 if (!N1) 9338 return ~0; 9339 9340 uint32_t C = N1->getZExtValue(); 9341 9342 switch (V.getOpcode()) { 9343 default: 9344 break; 9345 case ISD::AND: 9346 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9347 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9348 } 9349 break; 9350 9351 case ISD::OR: 9352 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9353 return (0x03020100 & ~ConstMask) | ConstMask; 9354 } 9355 break; 9356 9357 case ISD::SHL: 9358 if (C % 8) 9359 return ~0; 9360 9361 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9362 9363 case ISD::SRL: 9364 if (C % 8) 9365 return ~0; 9366 9367 return uint32_t(0x0c0c0c0c03020100ull >> C); 9368 } 9369 9370 return ~0; 9371 } 9372 9373 SDValue SITargetLowering::performAndCombine(SDNode *N, 9374 DAGCombinerInfo &DCI) const { 9375 if (DCI.isBeforeLegalize()) 9376 return SDValue(); 9377 9378 SelectionDAG &DAG = DCI.DAG; 9379 EVT VT = N->getValueType(0); 9380 SDValue LHS = N->getOperand(0); 9381 SDValue RHS = N->getOperand(1); 9382 9383 9384 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9385 if (VT == MVT::i64 && CRHS) { 9386 if (SDValue Split 9387 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9388 return Split; 9389 } 9390 9391 if (CRHS && VT == MVT::i32) { 9392 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9393 // nb = number of trailing zeroes in mask 9394 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9395 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9396 uint64_t Mask = CRHS->getZExtValue(); 9397 unsigned Bits = countPopulation(Mask); 9398 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9399 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9400 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9401 unsigned Shift = CShift->getZExtValue(); 9402 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9403 unsigned Offset = NB + Shift; 9404 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9405 SDLoc SL(N); 9406 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9407 LHS->getOperand(0), 9408 DAG.getConstant(Offset, SL, MVT::i32), 9409 DAG.getConstant(Bits, SL, MVT::i32)); 9410 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9411 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9412 DAG.getValueType(NarrowVT)); 9413 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9414 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9415 return Shl; 9416 } 9417 } 9418 } 9419 9420 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9421 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9422 isa<ConstantSDNode>(LHS.getOperand(2))) { 9423 uint32_t Sel = getConstantPermuteMask(Mask); 9424 if (!Sel) 9425 return SDValue(); 9426 9427 // Select 0xc for all zero bytes 9428 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9429 SDLoc DL(N); 9430 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9431 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9432 } 9433 } 9434 9435 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9436 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9437 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9438 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9439 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9440 9441 SDValue X = LHS.getOperand(0); 9442 SDValue Y = RHS.getOperand(0); 9443 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9444 return SDValue(); 9445 9446 if (LCC == ISD::SETO) { 9447 if (X != LHS.getOperand(1)) 9448 return SDValue(); 9449 9450 if (RCC == ISD::SETUNE) { 9451 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9452 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9453 return SDValue(); 9454 9455 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9456 SIInstrFlags::N_SUBNORMAL | 9457 SIInstrFlags::N_ZERO | 9458 SIInstrFlags::P_ZERO | 9459 SIInstrFlags::P_SUBNORMAL | 9460 SIInstrFlags::P_NORMAL; 9461 9462 static_assert(((~(SIInstrFlags::S_NAN | 9463 SIInstrFlags::Q_NAN | 9464 SIInstrFlags::N_INFINITY | 9465 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9466 "mask not equal"); 9467 9468 SDLoc DL(N); 9469 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9470 X, DAG.getConstant(Mask, DL, MVT::i32)); 9471 } 9472 } 9473 } 9474 9475 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9476 std::swap(LHS, RHS); 9477 9478 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9479 RHS.hasOneUse()) { 9480 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9481 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9482 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9483 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9484 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9485 (RHS.getOperand(0) == LHS.getOperand(0) && 9486 LHS.getOperand(0) == LHS.getOperand(1))) { 9487 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9488 unsigned NewMask = LCC == ISD::SETO ? 9489 Mask->getZExtValue() & ~OrdMask : 9490 Mask->getZExtValue() & OrdMask; 9491 9492 SDLoc DL(N); 9493 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9494 DAG.getConstant(NewMask, DL, MVT::i32)); 9495 } 9496 } 9497 9498 if (VT == MVT::i32 && 9499 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9500 // and x, (sext cc from i1) => select cc, x, 0 9501 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9502 std::swap(LHS, RHS); 9503 if (isBoolSGPR(RHS.getOperand(0))) 9504 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9505 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9506 } 9507 9508 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9509 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9510 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9511 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9512 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9513 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9514 if (LHSMask != ~0u && RHSMask != ~0u) { 9515 // Canonicalize the expression in an attempt to have fewer unique masks 9516 // and therefore fewer registers used to hold the masks. 9517 if (LHSMask > RHSMask) { 9518 std::swap(LHSMask, RHSMask); 9519 std::swap(LHS, RHS); 9520 } 9521 9522 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9523 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9524 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9525 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9526 9527 // Check of we need to combine values from two sources within a byte. 9528 if (!(LHSUsedLanes & RHSUsedLanes) && 9529 // If we select high and lower word keep it for SDWA. 9530 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9531 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9532 // Each byte in each mask is either selector mask 0-3, or has higher 9533 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9534 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9535 // mask which is not 0xff wins. By anding both masks we have a correct 9536 // result except that 0x0c shall be corrected to give 0x0c only. 9537 uint32_t Mask = LHSMask & RHSMask; 9538 for (unsigned I = 0; I < 32; I += 8) { 9539 uint32_t ByteSel = 0xff << I; 9540 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9541 Mask &= (0x0c << I) & 0xffffffff; 9542 } 9543 9544 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9545 // or 0x0c. 9546 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9547 SDLoc DL(N); 9548 9549 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9550 LHS.getOperand(0), RHS.getOperand(0), 9551 DAG.getConstant(Sel, DL, MVT::i32)); 9552 } 9553 } 9554 } 9555 9556 return SDValue(); 9557 } 9558 9559 SDValue SITargetLowering::performOrCombine(SDNode *N, 9560 DAGCombinerInfo &DCI) const { 9561 SelectionDAG &DAG = DCI.DAG; 9562 SDValue LHS = N->getOperand(0); 9563 SDValue RHS = N->getOperand(1); 9564 9565 EVT VT = N->getValueType(0); 9566 if (VT == MVT::i1) { 9567 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9568 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9569 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9570 SDValue Src = LHS.getOperand(0); 9571 if (Src != RHS.getOperand(0)) 9572 return SDValue(); 9573 9574 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9575 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9576 if (!CLHS || !CRHS) 9577 return SDValue(); 9578 9579 // Only 10 bits are used. 9580 static const uint32_t MaxMask = 0x3ff; 9581 9582 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9583 SDLoc DL(N); 9584 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9585 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9586 } 9587 9588 return SDValue(); 9589 } 9590 9591 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9592 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9593 LHS.getOpcode() == AMDGPUISD::PERM && 9594 isa<ConstantSDNode>(LHS.getOperand(2))) { 9595 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9596 if (!Sel) 9597 return SDValue(); 9598 9599 Sel |= LHS.getConstantOperandVal(2); 9600 SDLoc DL(N); 9601 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9602 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9603 } 9604 9605 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9606 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9607 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9608 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9609 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9610 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9611 if (LHSMask != ~0u && RHSMask != ~0u) { 9612 // Canonicalize the expression in an attempt to have fewer unique masks 9613 // and therefore fewer registers used to hold the masks. 9614 if (LHSMask > RHSMask) { 9615 std::swap(LHSMask, RHSMask); 9616 std::swap(LHS, RHS); 9617 } 9618 9619 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9620 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9621 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9622 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9623 9624 // Check of we need to combine values from two sources within a byte. 9625 if (!(LHSUsedLanes & RHSUsedLanes) && 9626 // If we select high and lower word keep it for SDWA. 9627 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9628 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9629 // Kill zero bytes selected by other mask. Zero value is 0xc. 9630 LHSMask &= ~RHSUsedLanes; 9631 RHSMask &= ~LHSUsedLanes; 9632 // Add 4 to each active LHS lane 9633 LHSMask |= LHSUsedLanes & 0x04040404; 9634 // Combine masks 9635 uint32_t Sel = LHSMask | RHSMask; 9636 SDLoc DL(N); 9637 9638 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9639 LHS.getOperand(0), RHS.getOperand(0), 9640 DAG.getConstant(Sel, DL, MVT::i32)); 9641 } 9642 } 9643 } 9644 9645 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9646 return SDValue(); 9647 9648 // TODO: This could be a generic combine with a predicate for extracting the 9649 // high half of an integer being free. 9650 9651 // (or i64:x, (zero_extend i32:y)) -> 9652 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9653 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9654 RHS.getOpcode() != ISD::ZERO_EXTEND) 9655 std::swap(LHS, RHS); 9656 9657 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9658 SDValue ExtSrc = RHS.getOperand(0); 9659 EVT SrcVT = ExtSrc.getValueType(); 9660 if (SrcVT == MVT::i32) { 9661 SDLoc SL(N); 9662 SDValue LowLHS, HiBits; 9663 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9664 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9665 9666 DCI.AddToWorklist(LowOr.getNode()); 9667 DCI.AddToWorklist(HiBits.getNode()); 9668 9669 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9670 LowOr, HiBits); 9671 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9672 } 9673 } 9674 9675 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9676 if (CRHS) { 9677 if (SDValue Split 9678 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9679 N->getOperand(0), CRHS)) 9680 return Split; 9681 } 9682 9683 return SDValue(); 9684 } 9685 9686 SDValue SITargetLowering::performXorCombine(SDNode *N, 9687 DAGCombinerInfo &DCI) const { 9688 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9689 return RV; 9690 9691 EVT VT = N->getValueType(0); 9692 if (VT != MVT::i64) 9693 return SDValue(); 9694 9695 SDValue LHS = N->getOperand(0); 9696 SDValue RHS = N->getOperand(1); 9697 9698 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9699 if (CRHS) { 9700 if (SDValue Split 9701 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9702 return Split; 9703 } 9704 9705 return SDValue(); 9706 } 9707 9708 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9709 DAGCombinerInfo &DCI) const { 9710 if (!Subtarget->has16BitInsts() || 9711 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9712 return SDValue(); 9713 9714 EVT VT = N->getValueType(0); 9715 if (VT != MVT::i32) 9716 return SDValue(); 9717 9718 SDValue Src = N->getOperand(0); 9719 if (Src.getValueType() != MVT::i16) 9720 return SDValue(); 9721 9722 return SDValue(); 9723 } 9724 9725 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9726 DAGCombinerInfo &DCI) 9727 const { 9728 SDValue Src = N->getOperand(0); 9729 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9730 9731 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9732 VTSign->getVT() == MVT::i8) || 9733 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9734 VTSign->getVT() == MVT::i16)) && 9735 Src.hasOneUse()) { 9736 auto *M = cast<MemSDNode>(Src); 9737 SDValue Ops[] = { 9738 Src.getOperand(0), // Chain 9739 Src.getOperand(1), // rsrc 9740 Src.getOperand(2), // vindex 9741 Src.getOperand(3), // voffset 9742 Src.getOperand(4), // soffset 9743 Src.getOperand(5), // offset 9744 Src.getOperand(6), 9745 Src.getOperand(7) 9746 }; 9747 // replace with BUFFER_LOAD_BYTE/SHORT 9748 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9749 Src.getOperand(0).getValueType()); 9750 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9751 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9752 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9753 ResList, 9754 Ops, M->getMemoryVT(), 9755 M->getMemOperand()); 9756 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9757 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9758 } 9759 return SDValue(); 9760 } 9761 9762 SDValue SITargetLowering::performClassCombine(SDNode *N, 9763 DAGCombinerInfo &DCI) const { 9764 SelectionDAG &DAG = DCI.DAG; 9765 SDValue Mask = N->getOperand(1); 9766 9767 // fp_class x, 0 -> false 9768 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9769 if (CMask->isZero()) 9770 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9771 } 9772 9773 if (N->getOperand(0).isUndef()) 9774 return DAG.getUNDEF(MVT::i1); 9775 9776 return SDValue(); 9777 } 9778 9779 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9780 DAGCombinerInfo &DCI) const { 9781 EVT VT = N->getValueType(0); 9782 SDValue N0 = N->getOperand(0); 9783 9784 if (N0.isUndef()) 9785 return N0; 9786 9787 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9788 N0.getOpcode() == ISD::SINT_TO_FP)) { 9789 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9790 N->getFlags()); 9791 } 9792 9793 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9794 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9795 N0.getOperand(0), N->getFlags()); 9796 } 9797 9798 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9799 } 9800 9801 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9802 unsigned MaxDepth) const { 9803 unsigned Opcode = Op.getOpcode(); 9804 if (Opcode == ISD::FCANONICALIZE) 9805 return true; 9806 9807 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9808 auto F = CFP->getValueAPF(); 9809 if (F.isNaN() && F.isSignaling()) 9810 return false; 9811 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9812 } 9813 9814 // If source is a result of another standard FP operation it is already in 9815 // canonical form. 9816 if (MaxDepth == 0) 9817 return false; 9818 9819 switch (Opcode) { 9820 // These will flush denorms if required. 9821 case ISD::FADD: 9822 case ISD::FSUB: 9823 case ISD::FMUL: 9824 case ISD::FCEIL: 9825 case ISD::FFLOOR: 9826 case ISD::FMA: 9827 case ISD::FMAD: 9828 case ISD::FSQRT: 9829 case ISD::FDIV: 9830 case ISD::FREM: 9831 case ISD::FP_ROUND: 9832 case ISD::FP_EXTEND: 9833 case AMDGPUISD::FMUL_LEGACY: 9834 case AMDGPUISD::FMAD_FTZ: 9835 case AMDGPUISD::RCP: 9836 case AMDGPUISD::RSQ: 9837 case AMDGPUISD::RSQ_CLAMP: 9838 case AMDGPUISD::RCP_LEGACY: 9839 case AMDGPUISD::RCP_IFLAG: 9840 case AMDGPUISD::DIV_SCALE: 9841 case AMDGPUISD::DIV_FMAS: 9842 case AMDGPUISD::DIV_FIXUP: 9843 case AMDGPUISD::FRACT: 9844 case AMDGPUISD::LDEXP: 9845 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9846 case AMDGPUISD::CVT_F32_UBYTE0: 9847 case AMDGPUISD::CVT_F32_UBYTE1: 9848 case AMDGPUISD::CVT_F32_UBYTE2: 9849 case AMDGPUISD::CVT_F32_UBYTE3: 9850 return true; 9851 9852 // It can/will be lowered or combined as a bit operation. 9853 // Need to check their input recursively to handle. 9854 case ISD::FNEG: 9855 case ISD::FABS: 9856 case ISD::FCOPYSIGN: 9857 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9858 9859 case ISD::FSIN: 9860 case ISD::FCOS: 9861 case ISD::FSINCOS: 9862 return Op.getValueType().getScalarType() != MVT::f16; 9863 9864 case ISD::FMINNUM: 9865 case ISD::FMAXNUM: 9866 case ISD::FMINNUM_IEEE: 9867 case ISD::FMAXNUM_IEEE: 9868 case AMDGPUISD::CLAMP: 9869 case AMDGPUISD::FMED3: 9870 case AMDGPUISD::FMAX3: 9871 case AMDGPUISD::FMIN3: { 9872 // FIXME: Shouldn't treat the generic operations different based these. 9873 // However, we aren't really required to flush the result from 9874 // minnum/maxnum.. 9875 9876 // snans will be quieted, so we only need to worry about denormals. 9877 if (Subtarget->supportsMinMaxDenormModes() || 9878 denormalsEnabledForType(DAG, Op.getValueType())) 9879 return true; 9880 9881 // Flushing may be required. 9882 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9883 // targets need to check their input recursively. 9884 9885 // FIXME: Does this apply with clamp? It's implemented with max. 9886 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9887 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9888 return false; 9889 } 9890 9891 return true; 9892 } 9893 case ISD::SELECT: { 9894 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9895 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9896 } 9897 case ISD::BUILD_VECTOR: { 9898 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9899 SDValue SrcOp = Op.getOperand(i); 9900 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9901 return false; 9902 } 9903 9904 return true; 9905 } 9906 case ISD::EXTRACT_VECTOR_ELT: 9907 case ISD::EXTRACT_SUBVECTOR: { 9908 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9909 } 9910 case ISD::INSERT_VECTOR_ELT: { 9911 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9912 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9913 } 9914 case ISD::UNDEF: 9915 // Could be anything. 9916 return false; 9917 9918 case ISD::BITCAST: 9919 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9920 case ISD::TRUNCATE: { 9921 // Hack round the mess we make when legalizing extract_vector_elt 9922 if (Op.getValueType() == MVT::i16) { 9923 SDValue TruncSrc = Op.getOperand(0); 9924 if (TruncSrc.getValueType() == MVT::i32 && 9925 TruncSrc.getOpcode() == ISD::BITCAST && 9926 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9927 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9928 } 9929 } 9930 return false; 9931 } 9932 case ISD::INTRINSIC_WO_CHAIN: { 9933 unsigned IntrinsicID 9934 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9935 // TODO: Handle more intrinsics 9936 switch (IntrinsicID) { 9937 case Intrinsic::amdgcn_cvt_pkrtz: 9938 case Intrinsic::amdgcn_cubeid: 9939 case Intrinsic::amdgcn_frexp_mant: 9940 case Intrinsic::amdgcn_fdot2: 9941 case Intrinsic::amdgcn_rcp: 9942 case Intrinsic::amdgcn_rsq: 9943 case Intrinsic::amdgcn_rsq_clamp: 9944 case Intrinsic::amdgcn_rcp_legacy: 9945 case Intrinsic::amdgcn_rsq_legacy: 9946 case Intrinsic::amdgcn_trig_preop: 9947 return true; 9948 default: 9949 break; 9950 } 9951 9952 LLVM_FALLTHROUGH; 9953 } 9954 default: 9955 return denormalsEnabledForType(DAG, Op.getValueType()) && 9956 DAG.isKnownNeverSNaN(Op); 9957 } 9958 9959 llvm_unreachable("invalid operation"); 9960 } 9961 9962 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9963 unsigned MaxDepth) const { 9964 MachineRegisterInfo &MRI = MF.getRegInfo(); 9965 MachineInstr *MI = MRI.getVRegDef(Reg); 9966 unsigned Opcode = MI->getOpcode(); 9967 9968 if (Opcode == AMDGPU::G_FCANONICALIZE) 9969 return true; 9970 9971 Optional<FPValueAndVReg> FCR; 9972 // Constant splat (can be padded with undef) or scalar constant. 9973 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9974 if (FCR->Value.isSignaling()) 9975 return false; 9976 return !FCR->Value.isDenormal() || 9977 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9978 } 9979 9980 if (MaxDepth == 0) 9981 return false; 9982 9983 switch (Opcode) { 9984 case AMDGPU::G_FMINNUM_IEEE: 9985 case AMDGPU::G_FMAXNUM_IEEE: { 9986 if (Subtarget->supportsMinMaxDenormModes() || 9987 denormalsEnabledForType(MRI.getType(Reg), MF)) 9988 return true; 9989 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9990 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9991 return false; 9992 return true; 9993 } 9994 default: 9995 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9996 isKnownNeverSNaN(Reg, MRI); 9997 } 9998 9999 llvm_unreachable("invalid operation"); 10000 } 10001 10002 // Constant fold canonicalize. 10003 SDValue SITargetLowering::getCanonicalConstantFP( 10004 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10005 // Flush denormals to 0 if not enabled. 10006 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10007 return DAG.getConstantFP(0.0, SL, VT); 10008 10009 if (C.isNaN()) { 10010 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10011 if (C.isSignaling()) { 10012 // Quiet a signaling NaN. 10013 // FIXME: Is this supposed to preserve payload bits? 10014 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10015 } 10016 10017 // Make sure it is the canonical NaN bitpattern. 10018 // 10019 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10020 // immediate? 10021 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10022 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10023 } 10024 10025 // Already canonical. 10026 return DAG.getConstantFP(C, SL, VT); 10027 } 10028 10029 static bool vectorEltWillFoldAway(SDValue Op) { 10030 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10031 } 10032 10033 SDValue SITargetLowering::performFCanonicalizeCombine( 10034 SDNode *N, 10035 DAGCombinerInfo &DCI) const { 10036 SelectionDAG &DAG = DCI.DAG; 10037 SDValue N0 = N->getOperand(0); 10038 EVT VT = N->getValueType(0); 10039 10040 // fcanonicalize undef -> qnan 10041 if (N0.isUndef()) { 10042 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10043 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10044 } 10045 10046 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10047 EVT VT = N->getValueType(0); 10048 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10049 } 10050 10051 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10052 // (fcanonicalize k) 10053 // 10054 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10055 10056 // TODO: This could be better with wider vectors that will be split to v2f16, 10057 // and to consider uses since there aren't that many packed operations. 10058 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10059 isTypeLegal(MVT::v2f16)) { 10060 SDLoc SL(N); 10061 SDValue NewElts[2]; 10062 SDValue Lo = N0.getOperand(0); 10063 SDValue Hi = N0.getOperand(1); 10064 EVT EltVT = Lo.getValueType(); 10065 10066 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10067 for (unsigned I = 0; I != 2; ++I) { 10068 SDValue Op = N0.getOperand(I); 10069 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10070 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10071 CFP->getValueAPF()); 10072 } else if (Op.isUndef()) { 10073 // Handled below based on what the other operand is. 10074 NewElts[I] = Op; 10075 } else { 10076 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10077 } 10078 } 10079 10080 // If one half is undef, and one is constant, prefer a splat vector rather 10081 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10082 // cheaper to use and may be free with a packed operation. 10083 if (NewElts[0].isUndef()) { 10084 if (isa<ConstantFPSDNode>(NewElts[1])) 10085 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10086 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10087 } 10088 10089 if (NewElts[1].isUndef()) { 10090 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10091 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10092 } 10093 10094 return DAG.getBuildVector(VT, SL, NewElts); 10095 } 10096 } 10097 10098 unsigned SrcOpc = N0.getOpcode(); 10099 10100 // If it's free to do so, push canonicalizes further up the source, which may 10101 // find a canonical source. 10102 // 10103 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10104 // sNaNs. 10105 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10106 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10107 if (CRHS && N0.hasOneUse()) { 10108 SDLoc SL(N); 10109 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10110 N0.getOperand(0)); 10111 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10112 DCI.AddToWorklist(Canon0.getNode()); 10113 10114 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10115 } 10116 } 10117 10118 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10119 } 10120 10121 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10122 switch (Opc) { 10123 case ISD::FMAXNUM: 10124 case ISD::FMAXNUM_IEEE: 10125 return AMDGPUISD::FMAX3; 10126 case ISD::SMAX: 10127 return AMDGPUISD::SMAX3; 10128 case ISD::UMAX: 10129 return AMDGPUISD::UMAX3; 10130 case ISD::FMINNUM: 10131 case ISD::FMINNUM_IEEE: 10132 return AMDGPUISD::FMIN3; 10133 case ISD::SMIN: 10134 return AMDGPUISD::SMIN3; 10135 case ISD::UMIN: 10136 return AMDGPUISD::UMIN3; 10137 default: 10138 llvm_unreachable("Not a min/max opcode"); 10139 } 10140 } 10141 10142 SDValue SITargetLowering::performIntMed3ImmCombine( 10143 SelectionDAG &DAG, const SDLoc &SL, 10144 SDValue Op0, SDValue Op1, bool Signed) const { 10145 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10146 if (!K1) 10147 return SDValue(); 10148 10149 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10150 if (!K0) 10151 return SDValue(); 10152 10153 if (Signed) { 10154 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10155 return SDValue(); 10156 } else { 10157 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10158 return SDValue(); 10159 } 10160 10161 EVT VT = K0->getValueType(0); 10162 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10163 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10164 return DAG.getNode(Med3Opc, SL, VT, 10165 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10166 } 10167 10168 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10169 if (VT == MVT::i16) { 10170 MVT NVT = MVT::i32; 10171 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10172 10173 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10174 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10175 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10176 10177 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10178 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10179 } 10180 10181 return SDValue(); 10182 } 10183 10184 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10185 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10186 return C; 10187 10188 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10189 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10190 return C; 10191 } 10192 10193 return nullptr; 10194 } 10195 10196 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10197 const SDLoc &SL, 10198 SDValue Op0, 10199 SDValue Op1) const { 10200 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10201 if (!K1) 10202 return SDValue(); 10203 10204 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10205 if (!K0) 10206 return SDValue(); 10207 10208 // Ordered >= (although NaN inputs should have folded away by now). 10209 if (K0->getValueAPF() > K1->getValueAPF()) 10210 return SDValue(); 10211 10212 const MachineFunction &MF = DAG.getMachineFunction(); 10213 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10214 10215 // TODO: Check IEEE bit enabled? 10216 EVT VT = Op0.getValueType(); 10217 if (Info->getMode().DX10Clamp) { 10218 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10219 // hardware fmed3 behavior converting to a min. 10220 // FIXME: Should this be allowing -0.0? 10221 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10222 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10223 } 10224 10225 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10226 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10227 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10228 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10229 // then give the other result, which is different from med3 with a NaN 10230 // input. 10231 SDValue Var = Op0.getOperand(0); 10232 if (!DAG.isKnownNeverSNaN(Var)) 10233 return SDValue(); 10234 10235 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10236 10237 if ((!K0->hasOneUse() || 10238 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10239 (!K1->hasOneUse() || 10240 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10241 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10242 Var, SDValue(K0, 0), SDValue(K1, 0)); 10243 } 10244 } 10245 10246 return SDValue(); 10247 } 10248 10249 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10250 DAGCombinerInfo &DCI) const { 10251 SelectionDAG &DAG = DCI.DAG; 10252 10253 EVT VT = N->getValueType(0); 10254 unsigned Opc = N->getOpcode(); 10255 SDValue Op0 = N->getOperand(0); 10256 SDValue Op1 = N->getOperand(1); 10257 10258 // Only do this if the inner op has one use since this will just increases 10259 // register pressure for no benefit. 10260 10261 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10262 !VT.isVector() && 10263 (VT == MVT::i32 || VT == MVT::f32 || 10264 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10265 // max(max(a, b), c) -> max3(a, b, c) 10266 // min(min(a, b), c) -> min3(a, b, c) 10267 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10268 SDLoc DL(N); 10269 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10270 DL, 10271 N->getValueType(0), 10272 Op0.getOperand(0), 10273 Op0.getOperand(1), 10274 Op1); 10275 } 10276 10277 // Try commuted. 10278 // max(a, max(b, c)) -> max3(a, b, c) 10279 // min(a, min(b, c)) -> min3(a, b, c) 10280 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10281 SDLoc DL(N); 10282 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10283 DL, 10284 N->getValueType(0), 10285 Op0, 10286 Op1.getOperand(0), 10287 Op1.getOperand(1)); 10288 } 10289 } 10290 10291 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10292 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10293 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10294 return Med3; 10295 } 10296 10297 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10298 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10299 return Med3; 10300 } 10301 10302 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10303 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10304 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10305 (Opc == AMDGPUISD::FMIN_LEGACY && 10306 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10307 (VT == MVT::f32 || VT == MVT::f64 || 10308 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10309 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10310 Op0.hasOneUse()) { 10311 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10312 return Res; 10313 } 10314 10315 return SDValue(); 10316 } 10317 10318 static bool isClampZeroToOne(SDValue A, SDValue B) { 10319 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10320 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10321 // FIXME: Should this be allowing -0.0? 10322 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10323 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10324 } 10325 } 10326 10327 return false; 10328 } 10329 10330 // FIXME: Should only worry about snans for version with chain. 10331 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10332 DAGCombinerInfo &DCI) const { 10333 EVT VT = N->getValueType(0); 10334 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10335 // NaNs. With a NaN input, the order of the operands may change the result. 10336 10337 SelectionDAG &DAG = DCI.DAG; 10338 SDLoc SL(N); 10339 10340 SDValue Src0 = N->getOperand(0); 10341 SDValue Src1 = N->getOperand(1); 10342 SDValue Src2 = N->getOperand(2); 10343 10344 if (isClampZeroToOne(Src0, Src1)) { 10345 // const_a, const_b, x -> clamp is safe in all cases including signaling 10346 // nans. 10347 // FIXME: Should this be allowing -0.0? 10348 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10349 } 10350 10351 const MachineFunction &MF = DAG.getMachineFunction(); 10352 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10353 10354 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10355 // handling no dx10-clamp? 10356 if (Info->getMode().DX10Clamp) { 10357 // If NaNs is clamped to 0, we are free to reorder the inputs. 10358 10359 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10360 std::swap(Src0, Src1); 10361 10362 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10363 std::swap(Src1, Src2); 10364 10365 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10366 std::swap(Src0, Src1); 10367 10368 if (isClampZeroToOne(Src1, Src2)) 10369 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10370 } 10371 10372 return SDValue(); 10373 } 10374 10375 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10376 DAGCombinerInfo &DCI) const { 10377 SDValue Src0 = N->getOperand(0); 10378 SDValue Src1 = N->getOperand(1); 10379 if (Src0.isUndef() && Src1.isUndef()) 10380 return DCI.DAG.getUNDEF(N->getValueType(0)); 10381 return SDValue(); 10382 } 10383 10384 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10385 // expanded into a set of cmp/select instructions. 10386 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10387 unsigned NumElem, 10388 bool IsDivergentIdx) { 10389 if (UseDivergentRegisterIndexing) 10390 return false; 10391 10392 unsigned VecSize = EltSize * NumElem; 10393 10394 // Sub-dword vectors of size 2 dword or less have better implementation. 10395 if (VecSize <= 64 && EltSize < 32) 10396 return false; 10397 10398 // Always expand the rest of sub-dword instructions, otherwise it will be 10399 // lowered via memory. 10400 if (EltSize < 32) 10401 return true; 10402 10403 // Always do this if var-idx is divergent, otherwise it will become a loop. 10404 if (IsDivergentIdx) 10405 return true; 10406 10407 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10408 unsigned NumInsts = NumElem /* Number of compares */ + 10409 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10410 return NumInsts <= 16; 10411 } 10412 10413 static bool shouldExpandVectorDynExt(SDNode *N) { 10414 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10415 if (isa<ConstantSDNode>(Idx)) 10416 return false; 10417 10418 SDValue Vec = N->getOperand(0); 10419 EVT VecVT = Vec.getValueType(); 10420 EVT EltVT = VecVT.getVectorElementType(); 10421 unsigned EltSize = EltVT.getSizeInBits(); 10422 unsigned NumElem = VecVT.getVectorNumElements(); 10423 10424 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10425 Idx->isDivergent()); 10426 } 10427 10428 SDValue SITargetLowering::performExtractVectorEltCombine( 10429 SDNode *N, DAGCombinerInfo &DCI) const { 10430 SDValue Vec = N->getOperand(0); 10431 SelectionDAG &DAG = DCI.DAG; 10432 10433 EVT VecVT = Vec.getValueType(); 10434 EVT EltVT = VecVT.getVectorElementType(); 10435 10436 if ((Vec.getOpcode() == ISD::FNEG || 10437 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10438 SDLoc SL(N); 10439 EVT EltVT = N->getValueType(0); 10440 SDValue Idx = N->getOperand(1); 10441 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10442 Vec.getOperand(0), Idx); 10443 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10444 } 10445 10446 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10447 // => 10448 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10449 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10450 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10451 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10452 SDLoc SL(N); 10453 EVT EltVT = N->getValueType(0); 10454 SDValue Idx = N->getOperand(1); 10455 unsigned Opc = Vec.getOpcode(); 10456 10457 switch(Opc) { 10458 default: 10459 break; 10460 // TODO: Support other binary operations. 10461 case ISD::FADD: 10462 case ISD::FSUB: 10463 case ISD::FMUL: 10464 case ISD::ADD: 10465 case ISD::UMIN: 10466 case ISD::UMAX: 10467 case ISD::SMIN: 10468 case ISD::SMAX: 10469 case ISD::FMAXNUM: 10470 case ISD::FMINNUM: 10471 case ISD::FMAXNUM_IEEE: 10472 case ISD::FMINNUM_IEEE: { 10473 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10474 Vec.getOperand(0), Idx); 10475 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10476 Vec.getOperand(1), Idx); 10477 10478 DCI.AddToWorklist(Elt0.getNode()); 10479 DCI.AddToWorklist(Elt1.getNode()); 10480 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10481 } 10482 } 10483 } 10484 10485 unsigned VecSize = VecVT.getSizeInBits(); 10486 unsigned EltSize = EltVT.getSizeInBits(); 10487 10488 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10489 if (::shouldExpandVectorDynExt(N)) { 10490 SDLoc SL(N); 10491 SDValue Idx = N->getOperand(1); 10492 SDValue V; 10493 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10494 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10495 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10496 if (I == 0) 10497 V = Elt; 10498 else 10499 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10500 } 10501 return V; 10502 } 10503 10504 if (!DCI.isBeforeLegalize()) 10505 return SDValue(); 10506 10507 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10508 // elements. This exposes more load reduction opportunities by replacing 10509 // multiple small extract_vector_elements with a single 32-bit extract. 10510 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10511 if (isa<MemSDNode>(Vec) && 10512 EltSize <= 16 && 10513 EltVT.isByteSized() && 10514 VecSize > 32 && 10515 VecSize % 32 == 0 && 10516 Idx) { 10517 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10518 10519 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10520 unsigned EltIdx = BitIndex / 32; 10521 unsigned LeftoverBitIdx = BitIndex % 32; 10522 SDLoc SL(N); 10523 10524 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10525 DCI.AddToWorklist(Cast.getNode()); 10526 10527 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10528 DAG.getConstant(EltIdx, SL, MVT::i32)); 10529 DCI.AddToWorklist(Elt.getNode()); 10530 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10531 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10532 DCI.AddToWorklist(Srl.getNode()); 10533 10534 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10535 DCI.AddToWorklist(Trunc.getNode()); 10536 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10537 } 10538 10539 return SDValue(); 10540 } 10541 10542 SDValue 10543 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10544 DAGCombinerInfo &DCI) const { 10545 SDValue Vec = N->getOperand(0); 10546 SDValue Idx = N->getOperand(2); 10547 EVT VecVT = Vec.getValueType(); 10548 EVT EltVT = VecVT.getVectorElementType(); 10549 10550 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10551 // => BUILD_VECTOR n x select (e, const-idx) 10552 if (!::shouldExpandVectorDynExt(N)) 10553 return SDValue(); 10554 10555 SelectionDAG &DAG = DCI.DAG; 10556 SDLoc SL(N); 10557 SDValue Ins = N->getOperand(1); 10558 EVT IdxVT = Idx.getValueType(); 10559 10560 SmallVector<SDValue, 16> Ops; 10561 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10562 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10563 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10564 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10565 Ops.push_back(V); 10566 } 10567 10568 return DAG.getBuildVector(VecVT, SL, Ops); 10569 } 10570 10571 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10572 const SDNode *N0, 10573 const SDNode *N1) const { 10574 EVT VT = N0->getValueType(0); 10575 10576 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10577 // support denormals ever. 10578 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10579 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10580 getSubtarget()->hasMadF16())) && 10581 isOperationLegal(ISD::FMAD, VT)) 10582 return ISD::FMAD; 10583 10584 const TargetOptions &Options = DAG.getTarget().Options; 10585 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10586 (N0->getFlags().hasAllowContract() && 10587 N1->getFlags().hasAllowContract())) && 10588 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10589 return ISD::FMA; 10590 } 10591 10592 return 0; 10593 } 10594 10595 // For a reassociatable opcode perform: 10596 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10597 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10598 SelectionDAG &DAG) const { 10599 EVT VT = N->getValueType(0); 10600 if (VT != MVT::i32 && VT != MVT::i64) 10601 return SDValue(); 10602 10603 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10604 return SDValue(); 10605 10606 unsigned Opc = N->getOpcode(); 10607 SDValue Op0 = N->getOperand(0); 10608 SDValue Op1 = N->getOperand(1); 10609 10610 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10611 return SDValue(); 10612 10613 if (Op0->isDivergent()) 10614 std::swap(Op0, Op1); 10615 10616 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10617 return SDValue(); 10618 10619 SDValue Op2 = Op1.getOperand(1); 10620 Op1 = Op1.getOperand(0); 10621 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10622 return SDValue(); 10623 10624 if (Op1->isDivergent()) 10625 std::swap(Op1, Op2); 10626 10627 SDLoc SL(N); 10628 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10629 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10630 } 10631 10632 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10633 EVT VT, 10634 SDValue N0, SDValue N1, SDValue N2, 10635 bool Signed) { 10636 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10637 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10638 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10639 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10640 } 10641 10642 SDValue SITargetLowering::performAddCombine(SDNode *N, 10643 DAGCombinerInfo &DCI) const { 10644 SelectionDAG &DAG = DCI.DAG; 10645 EVT VT = N->getValueType(0); 10646 SDLoc SL(N); 10647 SDValue LHS = N->getOperand(0); 10648 SDValue RHS = N->getOperand(1); 10649 10650 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10651 && Subtarget->hasMad64_32() && 10652 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10653 VT.getScalarSizeInBits() <= 64) { 10654 if (LHS.getOpcode() != ISD::MUL) 10655 std::swap(LHS, RHS); 10656 10657 SDValue MulLHS = LHS.getOperand(0); 10658 SDValue MulRHS = LHS.getOperand(1); 10659 SDValue AddRHS = RHS; 10660 10661 // TODO: Maybe restrict if SGPR inputs. 10662 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10663 numBitsUnsigned(MulRHS, DAG) <= 32) { 10664 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10665 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10666 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10667 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10668 } 10669 10670 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10671 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10672 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10673 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10674 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10675 } 10676 10677 return SDValue(); 10678 } 10679 10680 if (SDValue V = reassociateScalarOps(N, DAG)) { 10681 return V; 10682 } 10683 10684 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10685 return SDValue(); 10686 10687 // add x, zext (setcc) => addcarry x, 0, setcc 10688 // add x, sext (setcc) => subcarry x, 0, setcc 10689 unsigned Opc = LHS.getOpcode(); 10690 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10691 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10692 std::swap(RHS, LHS); 10693 10694 Opc = RHS.getOpcode(); 10695 switch (Opc) { 10696 default: break; 10697 case ISD::ZERO_EXTEND: 10698 case ISD::SIGN_EXTEND: 10699 case ISD::ANY_EXTEND: { 10700 auto Cond = RHS.getOperand(0); 10701 // If this won't be a real VOPC output, we would still need to insert an 10702 // extra instruction anyway. 10703 if (!isBoolSGPR(Cond)) 10704 break; 10705 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10706 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10707 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10708 return DAG.getNode(Opc, SL, VTList, Args); 10709 } 10710 case ISD::ADDCARRY: { 10711 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10712 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10713 if (!C || C->getZExtValue() != 0) break; 10714 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10715 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10716 } 10717 } 10718 return SDValue(); 10719 } 10720 10721 SDValue SITargetLowering::performSubCombine(SDNode *N, 10722 DAGCombinerInfo &DCI) const { 10723 SelectionDAG &DAG = DCI.DAG; 10724 EVT VT = N->getValueType(0); 10725 10726 if (VT != MVT::i32) 10727 return SDValue(); 10728 10729 SDLoc SL(N); 10730 SDValue LHS = N->getOperand(0); 10731 SDValue RHS = N->getOperand(1); 10732 10733 // sub x, zext (setcc) => subcarry x, 0, setcc 10734 // sub x, sext (setcc) => addcarry x, 0, setcc 10735 unsigned Opc = RHS.getOpcode(); 10736 switch (Opc) { 10737 default: break; 10738 case ISD::ZERO_EXTEND: 10739 case ISD::SIGN_EXTEND: 10740 case ISD::ANY_EXTEND: { 10741 auto Cond = RHS.getOperand(0); 10742 // If this won't be a real VOPC output, we would still need to insert an 10743 // extra instruction anyway. 10744 if (!isBoolSGPR(Cond)) 10745 break; 10746 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10747 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10748 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10749 return DAG.getNode(Opc, SL, VTList, Args); 10750 } 10751 } 10752 10753 if (LHS.getOpcode() == ISD::SUBCARRY) { 10754 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10755 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10756 if (!C || !C->isZero()) 10757 return SDValue(); 10758 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10759 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10760 } 10761 return SDValue(); 10762 } 10763 10764 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10765 DAGCombinerInfo &DCI) const { 10766 10767 if (N->getValueType(0) != MVT::i32) 10768 return SDValue(); 10769 10770 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10771 if (!C || C->getZExtValue() != 0) 10772 return SDValue(); 10773 10774 SelectionDAG &DAG = DCI.DAG; 10775 SDValue LHS = N->getOperand(0); 10776 10777 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10778 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10779 unsigned LHSOpc = LHS.getOpcode(); 10780 unsigned Opc = N->getOpcode(); 10781 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10782 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10783 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10784 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10785 } 10786 return SDValue(); 10787 } 10788 10789 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10790 DAGCombinerInfo &DCI) const { 10791 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10792 return SDValue(); 10793 10794 SelectionDAG &DAG = DCI.DAG; 10795 EVT VT = N->getValueType(0); 10796 10797 SDLoc SL(N); 10798 SDValue LHS = N->getOperand(0); 10799 SDValue RHS = N->getOperand(1); 10800 10801 // These should really be instruction patterns, but writing patterns with 10802 // source modifiers is a pain. 10803 10804 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10805 if (LHS.getOpcode() == ISD::FADD) { 10806 SDValue A = LHS.getOperand(0); 10807 if (A == LHS.getOperand(1)) { 10808 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10809 if (FusedOp != 0) { 10810 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10811 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10812 } 10813 } 10814 } 10815 10816 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10817 if (RHS.getOpcode() == ISD::FADD) { 10818 SDValue A = RHS.getOperand(0); 10819 if (A == RHS.getOperand(1)) { 10820 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10821 if (FusedOp != 0) { 10822 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10823 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10824 } 10825 } 10826 } 10827 10828 return SDValue(); 10829 } 10830 10831 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10832 DAGCombinerInfo &DCI) const { 10833 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10834 return SDValue(); 10835 10836 SelectionDAG &DAG = DCI.DAG; 10837 SDLoc SL(N); 10838 EVT VT = N->getValueType(0); 10839 assert(!VT.isVector()); 10840 10841 // Try to get the fneg to fold into the source modifier. This undoes generic 10842 // DAG combines and folds them into the mad. 10843 // 10844 // Only do this if we are not trying to support denormals. v_mad_f32 does 10845 // not support denormals ever. 10846 SDValue LHS = N->getOperand(0); 10847 SDValue RHS = N->getOperand(1); 10848 if (LHS.getOpcode() == ISD::FADD) { 10849 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10850 SDValue A = LHS.getOperand(0); 10851 if (A == LHS.getOperand(1)) { 10852 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10853 if (FusedOp != 0){ 10854 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10855 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10856 10857 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10858 } 10859 } 10860 } 10861 10862 if (RHS.getOpcode() == ISD::FADD) { 10863 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10864 10865 SDValue A = RHS.getOperand(0); 10866 if (A == RHS.getOperand(1)) { 10867 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10868 if (FusedOp != 0){ 10869 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10870 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10871 } 10872 } 10873 } 10874 10875 return SDValue(); 10876 } 10877 10878 SDValue SITargetLowering::performFMACombine(SDNode *N, 10879 DAGCombinerInfo &DCI) const { 10880 SelectionDAG &DAG = DCI.DAG; 10881 EVT VT = N->getValueType(0); 10882 SDLoc SL(N); 10883 10884 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10885 return SDValue(); 10886 10887 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10888 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10889 SDValue Op1 = N->getOperand(0); 10890 SDValue Op2 = N->getOperand(1); 10891 SDValue FMA = N->getOperand(2); 10892 10893 if (FMA.getOpcode() != ISD::FMA || 10894 Op1.getOpcode() != ISD::FP_EXTEND || 10895 Op2.getOpcode() != ISD::FP_EXTEND) 10896 return SDValue(); 10897 10898 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10899 // regardless of the denorm mode setting. Therefore, 10900 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 10901 const TargetOptions &Options = DAG.getTarget().Options; 10902 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10903 (N->getFlags().hasAllowContract() && 10904 FMA->getFlags().hasAllowContract())) { 10905 Op1 = Op1.getOperand(0); 10906 Op2 = Op2.getOperand(0); 10907 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10908 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10909 return SDValue(); 10910 10911 SDValue Vec1 = Op1.getOperand(0); 10912 SDValue Idx1 = Op1.getOperand(1); 10913 SDValue Vec2 = Op2.getOperand(0); 10914 10915 SDValue FMAOp1 = FMA.getOperand(0); 10916 SDValue FMAOp2 = FMA.getOperand(1); 10917 SDValue FMAAcc = FMA.getOperand(2); 10918 10919 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10920 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10921 return SDValue(); 10922 10923 FMAOp1 = FMAOp1.getOperand(0); 10924 FMAOp2 = FMAOp2.getOperand(0); 10925 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10926 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10927 return SDValue(); 10928 10929 SDValue Vec3 = FMAOp1.getOperand(0); 10930 SDValue Vec4 = FMAOp2.getOperand(0); 10931 SDValue Idx2 = FMAOp1.getOperand(1); 10932 10933 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10934 // Idx1 and Idx2 cannot be the same. 10935 Idx1 == Idx2) 10936 return SDValue(); 10937 10938 if (Vec1 == Vec2 || Vec3 == Vec4) 10939 return SDValue(); 10940 10941 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10942 return SDValue(); 10943 10944 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10945 (Vec1 == Vec4 && Vec2 == Vec3)) { 10946 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10947 DAG.getTargetConstant(0, SL, MVT::i1)); 10948 } 10949 } 10950 return SDValue(); 10951 } 10952 10953 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10954 DAGCombinerInfo &DCI) const { 10955 SelectionDAG &DAG = DCI.DAG; 10956 SDLoc SL(N); 10957 10958 SDValue LHS = N->getOperand(0); 10959 SDValue RHS = N->getOperand(1); 10960 EVT VT = LHS.getValueType(); 10961 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10962 10963 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10964 if (!CRHS) { 10965 CRHS = dyn_cast<ConstantSDNode>(LHS); 10966 if (CRHS) { 10967 std::swap(LHS, RHS); 10968 CC = getSetCCSwappedOperands(CC); 10969 } 10970 } 10971 10972 if (CRHS) { 10973 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10974 isBoolSGPR(LHS.getOperand(0))) { 10975 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10976 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10977 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10978 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10979 if ((CRHS->isAllOnes() && 10980 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10981 (CRHS->isZero() && 10982 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10983 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10984 DAG.getConstant(-1, SL, MVT::i1)); 10985 if ((CRHS->isAllOnes() && 10986 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10987 (CRHS->isZero() && 10988 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10989 return LHS.getOperand(0); 10990 } 10991 10992 const APInt &CRHSVal = CRHS->getAPIntValue(); 10993 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10994 LHS.getOpcode() == ISD::SELECT && 10995 isa<ConstantSDNode>(LHS.getOperand(1)) && 10996 isa<ConstantSDNode>(LHS.getOperand(2)) && 10997 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10998 isBoolSGPR(LHS.getOperand(0))) { 10999 // Given CT != FT: 11000 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11001 // setcc (select cc, CT, CF), CF, ne => cc 11002 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11003 // setcc (select cc, CT, CF), CT, eq => cc 11004 const APInt &CT = LHS.getConstantOperandAPInt(1); 11005 const APInt &CF = LHS.getConstantOperandAPInt(2); 11006 11007 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11008 (CT == CRHSVal && CC == ISD::SETNE)) 11009 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11010 DAG.getConstant(-1, SL, MVT::i1)); 11011 if ((CF == CRHSVal && CC == ISD::SETNE) || 11012 (CT == CRHSVal && CC == ISD::SETEQ)) 11013 return LHS.getOperand(0); 11014 } 11015 } 11016 11017 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11018 VT != MVT::f16)) 11019 return SDValue(); 11020 11021 // Match isinf/isfinite pattern 11022 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11023 // (fcmp one (fabs x), inf) -> (fp_class x, 11024 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11025 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11026 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11027 if (!CRHS) 11028 return SDValue(); 11029 11030 const APFloat &APF = CRHS->getValueAPF(); 11031 if (APF.isInfinity() && !APF.isNegative()) { 11032 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11033 SIInstrFlags::N_INFINITY; 11034 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11035 SIInstrFlags::P_ZERO | 11036 SIInstrFlags::N_NORMAL | 11037 SIInstrFlags::P_NORMAL | 11038 SIInstrFlags::N_SUBNORMAL | 11039 SIInstrFlags::P_SUBNORMAL; 11040 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11041 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11042 DAG.getConstant(Mask, SL, MVT::i32)); 11043 } 11044 } 11045 11046 return SDValue(); 11047 } 11048 11049 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11050 DAGCombinerInfo &DCI) const { 11051 SelectionDAG &DAG = DCI.DAG; 11052 SDLoc SL(N); 11053 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11054 11055 SDValue Src = N->getOperand(0); 11056 SDValue Shift = N->getOperand(0); 11057 11058 // TODO: Extend type shouldn't matter (assuming legal types). 11059 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11060 Shift = Shift.getOperand(0); 11061 11062 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11063 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11064 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11065 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11066 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11067 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11068 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11069 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11070 SDLoc(Shift.getOperand(0)), MVT::i32); 11071 11072 unsigned ShiftOffset = 8 * Offset; 11073 if (Shift.getOpcode() == ISD::SHL) 11074 ShiftOffset -= C->getZExtValue(); 11075 else 11076 ShiftOffset += C->getZExtValue(); 11077 11078 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11079 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11080 MVT::f32, Shifted); 11081 } 11082 } 11083 } 11084 11085 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11086 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11087 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11088 // We simplified Src. If this node is not dead, visit it again so it is 11089 // folded properly. 11090 if (N->getOpcode() != ISD::DELETED_NODE) 11091 DCI.AddToWorklist(N); 11092 return SDValue(N, 0); 11093 } 11094 11095 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11096 if (SDValue DemandedSrc = 11097 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11098 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11099 11100 return SDValue(); 11101 } 11102 11103 SDValue SITargetLowering::performClampCombine(SDNode *N, 11104 DAGCombinerInfo &DCI) const { 11105 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11106 if (!CSrc) 11107 return SDValue(); 11108 11109 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11110 const APFloat &F = CSrc->getValueAPF(); 11111 APFloat Zero = APFloat::getZero(F.getSemantics()); 11112 if (F < Zero || 11113 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11114 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11115 } 11116 11117 APFloat One(F.getSemantics(), "1.0"); 11118 if (F > One) 11119 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11120 11121 return SDValue(CSrc, 0); 11122 } 11123 11124 11125 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11126 DAGCombinerInfo &DCI) const { 11127 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11128 return SDValue(); 11129 switch (N->getOpcode()) { 11130 case ISD::ADD: 11131 return performAddCombine(N, DCI); 11132 case ISD::SUB: 11133 return performSubCombine(N, DCI); 11134 case ISD::ADDCARRY: 11135 case ISD::SUBCARRY: 11136 return performAddCarrySubCarryCombine(N, DCI); 11137 case ISD::FADD: 11138 return performFAddCombine(N, DCI); 11139 case ISD::FSUB: 11140 return performFSubCombine(N, DCI); 11141 case ISD::SETCC: 11142 return performSetCCCombine(N, DCI); 11143 case ISD::FMAXNUM: 11144 case ISD::FMINNUM: 11145 case ISD::FMAXNUM_IEEE: 11146 case ISD::FMINNUM_IEEE: 11147 case ISD::SMAX: 11148 case ISD::SMIN: 11149 case ISD::UMAX: 11150 case ISD::UMIN: 11151 case AMDGPUISD::FMIN_LEGACY: 11152 case AMDGPUISD::FMAX_LEGACY: 11153 return performMinMaxCombine(N, DCI); 11154 case ISD::FMA: 11155 return performFMACombine(N, DCI); 11156 case ISD::AND: 11157 return performAndCombine(N, DCI); 11158 case ISD::OR: 11159 return performOrCombine(N, DCI); 11160 case ISD::XOR: 11161 return performXorCombine(N, DCI); 11162 case ISD::ZERO_EXTEND: 11163 return performZeroExtendCombine(N, DCI); 11164 case ISD::SIGN_EXTEND_INREG: 11165 return performSignExtendInRegCombine(N , DCI); 11166 case AMDGPUISD::FP_CLASS: 11167 return performClassCombine(N, DCI); 11168 case ISD::FCANONICALIZE: 11169 return performFCanonicalizeCombine(N, DCI); 11170 case AMDGPUISD::RCP: 11171 return performRcpCombine(N, DCI); 11172 case AMDGPUISD::FRACT: 11173 case AMDGPUISD::RSQ: 11174 case AMDGPUISD::RCP_LEGACY: 11175 case AMDGPUISD::RCP_IFLAG: 11176 case AMDGPUISD::RSQ_CLAMP: 11177 case AMDGPUISD::LDEXP: { 11178 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11179 SDValue Src = N->getOperand(0); 11180 if (Src.isUndef()) 11181 return Src; 11182 break; 11183 } 11184 case ISD::SINT_TO_FP: 11185 case ISD::UINT_TO_FP: 11186 return performUCharToFloatCombine(N, DCI); 11187 case AMDGPUISD::CVT_F32_UBYTE0: 11188 case AMDGPUISD::CVT_F32_UBYTE1: 11189 case AMDGPUISD::CVT_F32_UBYTE2: 11190 case AMDGPUISD::CVT_F32_UBYTE3: 11191 return performCvtF32UByteNCombine(N, DCI); 11192 case AMDGPUISD::FMED3: 11193 return performFMed3Combine(N, DCI); 11194 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11195 return performCvtPkRTZCombine(N, DCI); 11196 case AMDGPUISD::CLAMP: 11197 return performClampCombine(N, DCI); 11198 case ISD::SCALAR_TO_VECTOR: { 11199 SelectionDAG &DAG = DCI.DAG; 11200 EVT VT = N->getValueType(0); 11201 11202 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11203 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11204 SDLoc SL(N); 11205 SDValue Src = N->getOperand(0); 11206 EVT EltVT = Src.getValueType(); 11207 if (EltVT == MVT::f16) 11208 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11209 11210 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11211 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11212 } 11213 11214 break; 11215 } 11216 case ISD::EXTRACT_VECTOR_ELT: 11217 return performExtractVectorEltCombine(N, DCI); 11218 case ISD::INSERT_VECTOR_ELT: 11219 return performInsertVectorEltCombine(N, DCI); 11220 case ISD::LOAD: { 11221 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11222 return Widended; 11223 LLVM_FALLTHROUGH; 11224 } 11225 default: { 11226 if (!DCI.isBeforeLegalize()) { 11227 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11228 return performMemSDNodeCombine(MemNode, DCI); 11229 } 11230 11231 break; 11232 } 11233 } 11234 11235 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11236 } 11237 11238 /// Helper function for adjustWritemask 11239 static unsigned SubIdx2Lane(unsigned Idx) { 11240 switch (Idx) { 11241 default: return ~0u; 11242 case AMDGPU::sub0: return 0; 11243 case AMDGPU::sub1: return 1; 11244 case AMDGPU::sub2: return 2; 11245 case AMDGPU::sub3: return 3; 11246 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11247 } 11248 } 11249 11250 /// Adjust the writemask of MIMG instructions 11251 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11252 SelectionDAG &DAG) const { 11253 unsigned Opcode = Node->getMachineOpcode(); 11254 11255 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11256 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11257 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11258 return Node; // not implemented for D16 11259 11260 SDNode *Users[5] = { nullptr }; 11261 unsigned Lane = 0; 11262 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11263 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11264 unsigned NewDmask = 0; 11265 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11266 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11267 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11268 Node->getConstantOperandVal(LWEIdx)) 11269 ? true 11270 : false; 11271 unsigned TFCLane = 0; 11272 bool HasChain = Node->getNumValues() > 1; 11273 11274 if (OldDmask == 0) { 11275 // These are folded out, but on the chance it happens don't assert. 11276 return Node; 11277 } 11278 11279 unsigned OldBitsSet = countPopulation(OldDmask); 11280 // Work out which is the TFE/LWE lane if that is enabled. 11281 if (UsesTFC) { 11282 TFCLane = OldBitsSet; 11283 } 11284 11285 // Try to figure out the used register components 11286 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11287 I != E; ++I) { 11288 11289 // Don't look at users of the chain. 11290 if (I.getUse().getResNo() != 0) 11291 continue; 11292 11293 // Abort if we can't understand the usage 11294 if (!I->isMachineOpcode() || 11295 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11296 return Node; 11297 11298 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11299 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11300 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11301 // set, etc. 11302 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11303 if (Lane == ~0u) 11304 return Node; 11305 11306 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11307 if (UsesTFC && Lane == TFCLane) { 11308 Users[Lane] = *I; 11309 } else { 11310 // Set which texture component corresponds to the lane. 11311 unsigned Comp; 11312 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11313 Comp = countTrailingZeros(Dmask); 11314 Dmask &= ~(1 << Comp); 11315 } 11316 11317 // Abort if we have more than one user per component. 11318 if (Users[Lane]) 11319 return Node; 11320 11321 Users[Lane] = *I; 11322 NewDmask |= 1 << Comp; 11323 } 11324 } 11325 11326 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11327 bool NoChannels = !NewDmask; 11328 if (NoChannels) { 11329 if (!UsesTFC) { 11330 // No uses of the result and not using TFC. Then do nothing. 11331 return Node; 11332 } 11333 // If the original dmask has one channel - then nothing to do 11334 if (OldBitsSet == 1) 11335 return Node; 11336 // Use an arbitrary dmask - required for the instruction to work 11337 NewDmask = 1; 11338 } 11339 // Abort if there's no change 11340 if (NewDmask == OldDmask) 11341 return Node; 11342 11343 unsigned BitsSet = countPopulation(NewDmask); 11344 11345 // Check for TFE or LWE - increase the number of channels by one to account 11346 // for the extra return value 11347 // This will need adjustment for D16 if this is also included in 11348 // adjustWriteMask (this function) but at present D16 are excluded. 11349 unsigned NewChannels = BitsSet + UsesTFC; 11350 11351 int NewOpcode = 11352 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11353 assert(NewOpcode != -1 && 11354 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11355 "failed to find equivalent MIMG op"); 11356 11357 // Adjust the writemask in the node 11358 SmallVector<SDValue, 12> Ops; 11359 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11360 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11361 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11362 11363 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11364 11365 MVT ResultVT = NewChannels == 1 ? 11366 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11367 NewChannels == 5 ? 8 : NewChannels); 11368 SDVTList NewVTList = HasChain ? 11369 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11370 11371 11372 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11373 NewVTList, Ops); 11374 11375 if (HasChain) { 11376 // Update chain. 11377 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11378 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11379 } 11380 11381 if (NewChannels == 1) { 11382 assert(Node->hasNUsesOfValue(1, 0)); 11383 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11384 SDLoc(Node), Users[Lane]->getValueType(0), 11385 SDValue(NewNode, 0)); 11386 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11387 return nullptr; 11388 } 11389 11390 // Update the users of the node with the new indices 11391 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11392 SDNode *User = Users[i]; 11393 if (!User) { 11394 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11395 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11396 if (i || !NoChannels) 11397 continue; 11398 } else { 11399 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11400 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11401 } 11402 11403 switch (Idx) { 11404 default: break; 11405 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11406 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11407 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11408 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11409 } 11410 } 11411 11412 DAG.RemoveDeadNode(Node); 11413 return nullptr; 11414 } 11415 11416 static bool isFrameIndexOp(SDValue Op) { 11417 if (Op.getOpcode() == ISD::AssertZext) 11418 Op = Op.getOperand(0); 11419 11420 return isa<FrameIndexSDNode>(Op); 11421 } 11422 11423 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11424 /// with frame index operands. 11425 /// LLVM assumes that inputs are to these instructions are registers. 11426 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11427 SelectionDAG &DAG) const { 11428 if (Node->getOpcode() == ISD::CopyToReg) { 11429 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11430 SDValue SrcVal = Node->getOperand(2); 11431 11432 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11433 // to try understanding copies to physical registers. 11434 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11435 SDLoc SL(Node); 11436 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11437 SDValue VReg = DAG.getRegister( 11438 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11439 11440 SDNode *Glued = Node->getGluedNode(); 11441 SDValue ToVReg 11442 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11443 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11444 SDValue ToResultReg 11445 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11446 VReg, ToVReg.getValue(1)); 11447 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11448 DAG.RemoveDeadNode(Node); 11449 return ToResultReg.getNode(); 11450 } 11451 } 11452 11453 SmallVector<SDValue, 8> Ops; 11454 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11455 if (!isFrameIndexOp(Node->getOperand(i))) { 11456 Ops.push_back(Node->getOperand(i)); 11457 continue; 11458 } 11459 11460 SDLoc DL(Node); 11461 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11462 Node->getOperand(i).getValueType(), 11463 Node->getOperand(i)), 0)); 11464 } 11465 11466 return DAG.UpdateNodeOperands(Node, Ops); 11467 } 11468 11469 /// Fold the instructions after selecting them. 11470 /// Returns null if users were already updated. 11471 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11472 SelectionDAG &DAG) const { 11473 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11474 unsigned Opcode = Node->getMachineOpcode(); 11475 11476 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11477 !TII->isGather4(Opcode) && 11478 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11479 return adjustWritemask(Node, DAG); 11480 } 11481 11482 if (Opcode == AMDGPU::INSERT_SUBREG || 11483 Opcode == AMDGPU::REG_SEQUENCE) { 11484 legalizeTargetIndependentNode(Node, DAG); 11485 return Node; 11486 } 11487 11488 switch (Opcode) { 11489 case AMDGPU::V_DIV_SCALE_F32_e64: 11490 case AMDGPU::V_DIV_SCALE_F64_e64: { 11491 // Satisfy the operand register constraint when one of the inputs is 11492 // undefined. Ordinarily each undef value will have its own implicit_def of 11493 // a vreg, so force these to use a single register. 11494 SDValue Src0 = Node->getOperand(1); 11495 SDValue Src1 = Node->getOperand(3); 11496 SDValue Src2 = Node->getOperand(5); 11497 11498 if ((Src0.isMachineOpcode() && 11499 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11500 (Src0 == Src1 || Src0 == Src2)) 11501 break; 11502 11503 MVT VT = Src0.getValueType().getSimpleVT(); 11504 const TargetRegisterClass *RC = 11505 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11506 11507 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11508 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11509 11510 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11511 UndefReg, Src0, SDValue()); 11512 11513 // src0 must be the same register as src1 or src2, even if the value is 11514 // undefined, so make sure we don't violate this constraint. 11515 if (Src0.isMachineOpcode() && 11516 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11517 if (Src1.isMachineOpcode() && 11518 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11519 Src0 = Src1; 11520 else if (Src2.isMachineOpcode() && 11521 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11522 Src0 = Src2; 11523 else { 11524 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11525 Src0 = UndefReg; 11526 Src1 = UndefReg; 11527 } 11528 } else 11529 break; 11530 11531 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11532 Ops[1] = Src0; 11533 Ops[3] = Src1; 11534 Ops[5] = Src2; 11535 Ops.push_back(ImpDef.getValue(1)); 11536 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11537 } 11538 default: 11539 break; 11540 } 11541 11542 return Node; 11543 } 11544 11545 // Any MIMG instructions that use tfe or lwe require an initialization of the 11546 // result register that will be written in the case of a memory access failure. 11547 // The required code is also added to tie this init code to the result of the 11548 // img instruction. 11549 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11550 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11551 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11552 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11553 MachineBasicBlock &MBB = *MI.getParent(); 11554 11555 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11556 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11557 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11558 11559 if (!TFE && !LWE) // intersect_ray 11560 return; 11561 11562 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11563 unsigned LWEVal = LWE->getImm(); 11564 unsigned D16Val = D16 ? D16->getImm() : 0; 11565 11566 if (!TFEVal && !LWEVal) 11567 return; 11568 11569 // At least one of TFE or LWE are non-zero 11570 // We have to insert a suitable initialization of the result value and 11571 // tie this to the dest of the image instruction. 11572 11573 const DebugLoc &DL = MI.getDebugLoc(); 11574 11575 int DstIdx = 11576 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11577 11578 // Calculate which dword we have to initialize to 0. 11579 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11580 11581 // check that dmask operand is found. 11582 assert(MO_Dmask && "Expected dmask operand in instruction"); 11583 11584 unsigned dmask = MO_Dmask->getImm(); 11585 // Determine the number of active lanes taking into account the 11586 // Gather4 special case 11587 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11588 11589 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11590 11591 unsigned InitIdx = 11592 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11593 11594 // Abandon attempt if the dst size isn't large enough 11595 // - this is in fact an error but this is picked up elsewhere and 11596 // reported correctly. 11597 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11598 if (DstSize < InitIdx) 11599 return; 11600 11601 // Create a register for the initialization value. 11602 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11603 unsigned NewDst = 0; // Final initialized value will be in here 11604 11605 // If PRTStrictNull feature is enabled (the default) then initialize 11606 // all the result registers to 0, otherwise just the error indication 11607 // register (VGPRn+1) 11608 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11609 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11610 11611 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11612 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11613 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11614 // Initialize dword 11615 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11616 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11617 .addImm(0); 11618 // Insert into the super-reg 11619 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11620 .addReg(PrevDst) 11621 .addReg(SubReg) 11622 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11623 11624 PrevDst = NewDst; 11625 } 11626 11627 // Add as an implicit operand 11628 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11629 11630 // Tie the just added implicit operand to the dst 11631 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11632 } 11633 11634 /// Assign the register class depending on the number of 11635 /// bits set in the writemask 11636 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11637 SDNode *Node) const { 11638 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11639 11640 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11641 11642 if (TII->isVOP3(MI.getOpcode())) { 11643 // Make sure constant bus requirements are respected. 11644 TII->legalizeOperandsVOP3(MRI, MI); 11645 11646 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11647 // This saves a chain-copy of registers and better balance register 11648 // use between vgpr and agpr as agpr tuples tend to be big. 11649 if (MI.getDesc().OpInfo) { 11650 unsigned Opc = MI.getOpcode(); 11651 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11652 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11653 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11654 if (I == -1) 11655 break; 11656 MachineOperand &Op = MI.getOperand(I); 11657 if (!Op.isReg() || !Op.getReg().isVirtual()) 11658 continue; 11659 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11660 if (!TRI->hasAGPRs(RC)) 11661 continue; 11662 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11663 if (!Src || !Src->isCopy() || 11664 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11665 continue; 11666 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11667 // All uses of agpr64 and agpr32 can also accept vgpr except for 11668 // v_accvgpr_read, but we do not produce agpr reads during selection, 11669 // so no use checks are needed. 11670 MRI.setRegClass(Op.getReg(), NewRC); 11671 } 11672 11673 // Resolve the rest of AV operands to AGPRs. 11674 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11675 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11676 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11677 if (TRI->isVectorSuperClass(RC)) { 11678 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11679 MRI.setRegClass(Src2->getReg(), NewRC); 11680 if (Src2->isTied()) 11681 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11682 } 11683 } 11684 } 11685 } 11686 11687 return; 11688 } 11689 11690 // Replace unused atomics with the no return version. 11691 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11692 if (NoRetAtomicOp != -1) { 11693 if (!Node->hasAnyUseOfValue(0)) { 11694 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11695 AMDGPU::OpName::cpol); 11696 if (CPolIdx != -1) { 11697 MachineOperand &CPol = MI.getOperand(CPolIdx); 11698 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11699 } 11700 MI.removeOperand(0); 11701 MI.setDesc(TII->get(NoRetAtomicOp)); 11702 return; 11703 } 11704 11705 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11706 // instruction, because the return type of these instructions is a vec2 of 11707 // the memory type, so it can be tied to the input operand. 11708 // This means these instructions always have a use, so we need to add a 11709 // special case to check if the atomic has only one extract_subreg use, 11710 // which itself has no uses. 11711 if ((Node->hasNUsesOfValue(1, 0) && 11712 Node->use_begin()->isMachineOpcode() && 11713 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11714 !Node->use_begin()->hasAnyUseOfValue(0))) { 11715 Register Def = MI.getOperand(0).getReg(); 11716 11717 // Change this into a noret atomic. 11718 MI.setDesc(TII->get(NoRetAtomicOp)); 11719 MI.removeOperand(0); 11720 11721 // If we only remove the def operand from the atomic instruction, the 11722 // extract_subreg will be left with a use of a vreg without a def. 11723 // So we need to insert an implicit_def to avoid machine verifier 11724 // errors. 11725 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11726 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11727 } 11728 return; 11729 } 11730 11731 if (TII->isMIMG(MI) && !MI.mayStore()) 11732 AddIMGInit(MI); 11733 } 11734 11735 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11736 uint64_t Val) { 11737 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11738 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11739 } 11740 11741 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11742 const SDLoc &DL, 11743 SDValue Ptr) const { 11744 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11745 11746 // Build the half of the subregister with the constants before building the 11747 // full 128-bit register. If we are building multiple resource descriptors, 11748 // this will allow CSEing of the 2-component register. 11749 const SDValue Ops0[] = { 11750 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11751 buildSMovImm32(DAG, DL, 0), 11752 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11753 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11754 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11755 }; 11756 11757 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11758 MVT::v2i32, Ops0), 0); 11759 11760 // Combine the constants and the pointer. 11761 const SDValue Ops1[] = { 11762 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11763 Ptr, 11764 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11765 SubRegHi, 11766 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11767 }; 11768 11769 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11770 } 11771 11772 /// Return a resource descriptor with the 'Add TID' bit enabled 11773 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11774 /// of the resource descriptor) to create an offset, which is added to 11775 /// the resource pointer. 11776 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11777 SDValue Ptr, uint32_t RsrcDword1, 11778 uint64_t RsrcDword2And3) const { 11779 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11780 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11781 if (RsrcDword1) { 11782 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11783 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11784 0); 11785 } 11786 11787 SDValue DataLo = buildSMovImm32(DAG, DL, 11788 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11789 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11790 11791 const SDValue Ops[] = { 11792 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11793 PtrLo, 11794 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11795 PtrHi, 11796 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11797 DataLo, 11798 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11799 DataHi, 11800 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11801 }; 11802 11803 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11804 } 11805 11806 //===----------------------------------------------------------------------===// 11807 // SI Inline Assembly Support 11808 //===----------------------------------------------------------------------===// 11809 11810 std::pair<unsigned, const TargetRegisterClass *> 11811 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11812 StringRef Constraint, 11813 MVT VT) const { 11814 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11815 11816 const TargetRegisterClass *RC = nullptr; 11817 if (Constraint.size() == 1) { 11818 const unsigned BitWidth = VT.getSizeInBits(); 11819 switch (Constraint[0]) { 11820 default: 11821 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11822 case 's': 11823 case 'r': 11824 switch (BitWidth) { 11825 case 16: 11826 RC = &AMDGPU::SReg_32RegClass; 11827 break; 11828 case 64: 11829 RC = &AMDGPU::SGPR_64RegClass; 11830 break; 11831 default: 11832 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11833 if (!RC) 11834 return std::make_pair(0U, nullptr); 11835 break; 11836 } 11837 break; 11838 case 'v': 11839 switch (BitWidth) { 11840 case 16: 11841 RC = &AMDGPU::VGPR_32RegClass; 11842 break; 11843 default: 11844 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11845 if (!RC) 11846 return std::make_pair(0U, nullptr); 11847 break; 11848 } 11849 break; 11850 case 'a': 11851 if (!Subtarget->hasMAIInsts()) 11852 break; 11853 switch (BitWidth) { 11854 case 16: 11855 RC = &AMDGPU::AGPR_32RegClass; 11856 break; 11857 default: 11858 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11859 if (!RC) 11860 return std::make_pair(0U, nullptr); 11861 break; 11862 } 11863 break; 11864 } 11865 // We actually support i128, i16 and f16 as inline parameters 11866 // even if they are not reported as legal 11867 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11868 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11869 return std::make_pair(0U, RC); 11870 } 11871 11872 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11873 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11874 if (RegName.consume_front("v")) { 11875 RC = &AMDGPU::VGPR_32RegClass; 11876 } else if (RegName.consume_front("s")) { 11877 RC = &AMDGPU::SGPR_32RegClass; 11878 } else if (RegName.consume_front("a")) { 11879 RC = &AMDGPU::AGPR_32RegClass; 11880 } 11881 11882 if (RC) { 11883 uint32_t Idx; 11884 if (RegName.consume_front("[")) { 11885 uint32_t End; 11886 bool Failed = RegName.consumeInteger(10, Idx); 11887 Failed |= !RegName.consume_front(":"); 11888 Failed |= RegName.consumeInteger(10, End); 11889 Failed |= !RegName.consume_back("]"); 11890 if (!Failed) { 11891 uint32_t Width = (End - Idx + 1) * 32; 11892 MCRegister Reg = RC->getRegister(Idx); 11893 if (SIRegisterInfo::isVGPRClass(RC)) 11894 RC = TRI->getVGPRClassForBitWidth(Width); 11895 else if (SIRegisterInfo::isSGPRClass(RC)) 11896 RC = TRI->getSGPRClassForBitWidth(Width); 11897 else if (SIRegisterInfo::isAGPRClass(RC)) 11898 RC = TRI->getAGPRClassForBitWidth(Width); 11899 if (RC) { 11900 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 11901 return std::make_pair(Reg, RC); 11902 } 11903 } 11904 } else { 11905 bool Failed = RegName.getAsInteger(10, Idx); 11906 if (!Failed && Idx < RC->getNumRegs()) 11907 return std::make_pair(RC->getRegister(Idx), RC); 11908 } 11909 } 11910 } 11911 11912 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11913 if (Ret.first) 11914 Ret.second = TRI->getPhysRegClass(Ret.first); 11915 11916 return Ret; 11917 } 11918 11919 static bool isImmConstraint(StringRef Constraint) { 11920 if (Constraint.size() == 1) { 11921 switch (Constraint[0]) { 11922 default: break; 11923 case 'I': 11924 case 'J': 11925 case 'A': 11926 case 'B': 11927 case 'C': 11928 return true; 11929 } 11930 } else if (Constraint == "DA" || 11931 Constraint == "DB") { 11932 return true; 11933 } 11934 return false; 11935 } 11936 11937 SITargetLowering::ConstraintType 11938 SITargetLowering::getConstraintType(StringRef Constraint) const { 11939 if (Constraint.size() == 1) { 11940 switch (Constraint[0]) { 11941 default: break; 11942 case 's': 11943 case 'v': 11944 case 'a': 11945 return C_RegisterClass; 11946 } 11947 } 11948 if (isImmConstraint(Constraint)) { 11949 return C_Other; 11950 } 11951 return TargetLowering::getConstraintType(Constraint); 11952 } 11953 11954 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11955 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11956 Val = Val & maskTrailingOnes<uint64_t>(Size); 11957 } 11958 return Val; 11959 } 11960 11961 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11962 std::string &Constraint, 11963 std::vector<SDValue> &Ops, 11964 SelectionDAG &DAG) const { 11965 if (isImmConstraint(Constraint)) { 11966 uint64_t Val; 11967 if (getAsmOperandConstVal(Op, Val) && 11968 checkAsmConstraintVal(Op, Constraint, Val)) { 11969 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11970 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11971 } 11972 } else { 11973 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11974 } 11975 } 11976 11977 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11978 unsigned Size = Op.getScalarValueSizeInBits(); 11979 if (Size > 64) 11980 return false; 11981 11982 if (Size == 16 && !Subtarget->has16BitInsts()) 11983 return false; 11984 11985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11986 Val = C->getSExtValue(); 11987 return true; 11988 } 11989 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11990 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11991 return true; 11992 } 11993 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11994 if (Size != 16 || Op.getNumOperands() != 2) 11995 return false; 11996 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11997 return false; 11998 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11999 Val = C->getSExtValue(); 12000 return true; 12001 } 12002 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12003 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12004 return true; 12005 } 12006 } 12007 12008 return false; 12009 } 12010 12011 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12012 const std::string &Constraint, 12013 uint64_t Val) const { 12014 if (Constraint.size() == 1) { 12015 switch (Constraint[0]) { 12016 case 'I': 12017 return AMDGPU::isInlinableIntLiteral(Val); 12018 case 'J': 12019 return isInt<16>(Val); 12020 case 'A': 12021 return checkAsmConstraintValA(Op, Val); 12022 case 'B': 12023 return isInt<32>(Val); 12024 case 'C': 12025 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12026 AMDGPU::isInlinableIntLiteral(Val); 12027 default: 12028 break; 12029 } 12030 } else if (Constraint.size() == 2) { 12031 if (Constraint == "DA") { 12032 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12033 int64_t LoBits = static_cast<int32_t>(Val); 12034 return checkAsmConstraintValA(Op, HiBits, 32) && 12035 checkAsmConstraintValA(Op, LoBits, 32); 12036 } 12037 if (Constraint == "DB") { 12038 return true; 12039 } 12040 } 12041 llvm_unreachable("Invalid asm constraint"); 12042 } 12043 12044 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12045 uint64_t Val, 12046 unsigned MaxSize) const { 12047 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12048 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12049 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12050 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12051 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12052 return true; 12053 } 12054 return false; 12055 } 12056 12057 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12058 switch (UnalignedClassID) { 12059 case AMDGPU::VReg_64RegClassID: 12060 return AMDGPU::VReg_64_Align2RegClassID; 12061 case AMDGPU::VReg_96RegClassID: 12062 return AMDGPU::VReg_96_Align2RegClassID; 12063 case AMDGPU::VReg_128RegClassID: 12064 return AMDGPU::VReg_128_Align2RegClassID; 12065 case AMDGPU::VReg_160RegClassID: 12066 return AMDGPU::VReg_160_Align2RegClassID; 12067 case AMDGPU::VReg_192RegClassID: 12068 return AMDGPU::VReg_192_Align2RegClassID; 12069 case AMDGPU::VReg_224RegClassID: 12070 return AMDGPU::VReg_224_Align2RegClassID; 12071 case AMDGPU::VReg_256RegClassID: 12072 return AMDGPU::VReg_256_Align2RegClassID; 12073 case AMDGPU::VReg_512RegClassID: 12074 return AMDGPU::VReg_512_Align2RegClassID; 12075 case AMDGPU::VReg_1024RegClassID: 12076 return AMDGPU::VReg_1024_Align2RegClassID; 12077 case AMDGPU::AReg_64RegClassID: 12078 return AMDGPU::AReg_64_Align2RegClassID; 12079 case AMDGPU::AReg_96RegClassID: 12080 return AMDGPU::AReg_96_Align2RegClassID; 12081 case AMDGPU::AReg_128RegClassID: 12082 return AMDGPU::AReg_128_Align2RegClassID; 12083 case AMDGPU::AReg_160RegClassID: 12084 return AMDGPU::AReg_160_Align2RegClassID; 12085 case AMDGPU::AReg_192RegClassID: 12086 return AMDGPU::AReg_192_Align2RegClassID; 12087 case AMDGPU::AReg_256RegClassID: 12088 return AMDGPU::AReg_256_Align2RegClassID; 12089 case AMDGPU::AReg_512RegClassID: 12090 return AMDGPU::AReg_512_Align2RegClassID; 12091 case AMDGPU::AReg_1024RegClassID: 12092 return AMDGPU::AReg_1024_Align2RegClassID; 12093 default: 12094 return -1; 12095 } 12096 } 12097 12098 // Figure out which registers should be reserved for stack access. Only after 12099 // the function is legalized do we know all of the non-spill stack objects or if 12100 // calls are present. 12101 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12102 MachineRegisterInfo &MRI = MF.getRegInfo(); 12103 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12104 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12105 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12106 const SIInstrInfo *TII = ST.getInstrInfo(); 12107 12108 if (Info->isEntryFunction()) { 12109 // Callable functions have fixed registers used for stack access. 12110 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12111 } 12112 12113 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12114 Info->getStackPtrOffsetReg())); 12115 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12116 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12117 12118 // We need to worry about replacing the default register with itself in case 12119 // of MIR testcases missing the MFI. 12120 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12121 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12122 12123 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12124 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12125 12126 Info->limitOccupancy(MF); 12127 12128 if (ST.isWave32() && !MF.empty()) { 12129 for (auto &MBB : MF) { 12130 for (auto &MI : MBB) { 12131 TII->fixImplicitOperands(MI); 12132 } 12133 } 12134 } 12135 12136 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12137 // classes if required. Ideally the register class constraints would differ 12138 // per-subtarget, but there's no easy way to achieve that right now. This is 12139 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12140 // from using them as the register class for legal types. 12141 if (ST.needsAlignedVGPRs()) { 12142 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12143 const Register Reg = Register::index2VirtReg(I); 12144 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12145 if (!RC) 12146 continue; 12147 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12148 if (NewClassID != -1) 12149 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12150 } 12151 } 12152 12153 TargetLoweringBase::finalizeLowering(MF); 12154 } 12155 12156 void SITargetLowering::computeKnownBitsForFrameIndex( 12157 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12158 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12159 12160 // Set the high bits to zero based on the maximum allowed scratch size per 12161 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12162 // calculation won't overflow, so assume the sign bit is never set. 12163 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12164 } 12165 12166 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12167 KnownBits &Known, unsigned Dim) { 12168 unsigned MaxValue = 12169 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12170 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12171 } 12172 12173 void SITargetLowering::computeKnownBitsForTargetInstr( 12174 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12175 const MachineRegisterInfo &MRI, unsigned Depth) const { 12176 const MachineInstr *MI = MRI.getVRegDef(R); 12177 switch (MI->getOpcode()) { 12178 case AMDGPU::G_INTRINSIC: { 12179 switch (MI->getIntrinsicID()) { 12180 case Intrinsic::amdgcn_workitem_id_x: 12181 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12182 break; 12183 case Intrinsic::amdgcn_workitem_id_y: 12184 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12185 break; 12186 case Intrinsic::amdgcn_workitem_id_z: 12187 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12188 break; 12189 case Intrinsic::amdgcn_mbcnt_lo: 12190 case Intrinsic::amdgcn_mbcnt_hi: { 12191 // These return at most the wavefront size - 1. 12192 unsigned Size = MRI.getType(R).getSizeInBits(); 12193 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12194 break; 12195 } 12196 case Intrinsic::amdgcn_groupstaticsize: { 12197 // We can report everything over the maximum size as 0. We can't report 12198 // based on the actual size because we don't know if it's accurate or not 12199 // at any given point. 12200 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12201 break; 12202 } 12203 } 12204 break; 12205 } 12206 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12207 Known.Zero.setHighBits(24); 12208 break; 12209 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12210 Known.Zero.setHighBits(16); 12211 break; 12212 } 12213 } 12214 12215 Align SITargetLowering::computeKnownAlignForTargetInstr( 12216 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12217 unsigned Depth) const { 12218 const MachineInstr *MI = MRI.getVRegDef(R); 12219 switch (MI->getOpcode()) { 12220 case AMDGPU::G_INTRINSIC: 12221 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12222 // FIXME: Can this move to generic code? What about the case where the call 12223 // site specifies a lower alignment? 12224 Intrinsic::ID IID = MI->getIntrinsicID(); 12225 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12226 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12227 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12228 return *RetAlign; 12229 return Align(1); 12230 } 12231 default: 12232 return Align(1); 12233 } 12234 } 12235 12236 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12237 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12238 const Align CacheLineAlign = Align(64); 12239 12240 // Pre-GFX10 target did not benefit from loop alignment 12241 if (!ML || DisableLoopAlignment || 12242 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12243 getSubtarget()->hasInstFwdPrefetchBug()) 12244 return PrefAlign; 12245 12246 // On GFX10 I$ is 4 x 64 bytes cache lines. 12247 // By default prefetcher keeps one cache line behind and reads two ahead. 12248 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12249 // behind and one ahead. 12250 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12251 // If loop fits 64 bytes it always spans no more than two cache lines and 12252 // does not need an alignment. 12253 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12254 // Else if loop is less or equal 192 bytes we need two lines behind. 12255 12256 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12257 const MachineBasicBlock *Header = ML->getHeader(); 12258 if (Header->getAlignment() != PrefAlign) 12259 return Header->getAlignment(); // Already processed. 12260 12261 unsigned LoopSize = 0; 12262 for (const MachineBasicBlock *MBB : ML->blocks()) { 12263 // If inner loop block is aligned assume in average half of the alignment 12264 // size to be added as nops. 12265 if (MBB != Header) 12266 LoopSize += MBB->getAlignment().value() / 2; 12267 12268 for (const MachineInstr &MI : *MBB) { 12269 LoopSize += TII->getInstSizeInBytes(MI); 12270 if (LoopSize > 192) 12271 return PrefAlign; 12272 } 12273 } 12274 12275 if (LoopSize <= 64) 12276 return PrefAlign; 12277 12278 if (LoopSize <= 128) 12279 return CacheLineAlign; 12280 12281 // If any of parent loops is surrounded by prefetch instructions do not 12282 // insert new for inner loop, which would reset parent's settings. 12283 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12284 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12285 auto I = Exit->getFirstNonDebugInstr(); 12286 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12287 return CacheLineAlign; 12288 } 12289 } 12290 12291 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12292 MachineBasicBlock *Exit = ML->getExitBlock(); 12293 12294 if (Pre && Exit) { 12295 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12296 TII->get(AMDGPU::S_INST_PREFETCH)) 12297 .addImm(1); // prefetch 2 lines behind PC 12298 12299 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12300 TII->get(AMDGPU::S_INST_PREFETCH)) 12301 .addImm(2); // prefetch 1 line behind PC 12302 } 12303 12304 return CacheLineAlign; 12305 } 12306 12307 LLVM_ATTRIBUTE_UNUSED 12308 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12309 assert(N->getOpcode() == ISD::CopyFromReg); 12310 do { 12311 // Follow the chain until we find an INLINEASM node. 12312 N = N->getOperand(0).getNode(); 12313 if (N->getOpcode() == ISD::INLINEASM || 12314 N->getOpcode() == ISD::INLINEASM_BR) 12315 return true; 12316 } while (N->getOpcode() == ISD::CopyFromReg); 12317 return false; 12318 } 12319 12320 bool SITargetLowering::isSDNodeSourceOfDivergence( 12321 const SDNode *N, FunctionLoweringInfo *FLI, 12322 LegacyDivergenceAnalysis *KDA) const { 12323 switch (N->getOpcode()) { 12324 case ISD::CopyFromReg: { 12325 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12326 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12327 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12328 Register Reg = R->getReg(); 12329 12330 // FIXME: Why does this need to consider isLiveIn? 12331 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12332 return !TRI->isSGPRReg(MRI, Reg); 12333 12334 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12335 return KDA->isDivergent(V); 12336 12337 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12338 return !TRI->isSGPRReg(MRI, Reg); 12339 } 12340 case ISD::LOAD: { 12341 const LoadSDNode *L = cast<LoadSDNode>(N); 12342 unsigned AS = L->getAddressSpace(); 12343 // A flat load may access private memory. 12344 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12345 } 12346 case ISD::CALLSEQ_END: 12347 return true; 12348 case ISD::INTRINSIC_WO_CHAIN: 12349 return AMDGPU::isIntrinsicSourceOfDivergence( 12350 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12351 case ISD::INTRINSIC_W_CHAIN: 12352 return AMDGPU::isIntrinsicSourceOfDivergence( 12353 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12354 case AMDGPUISD::ATOMIC_CMP_SWAP: 12355 case AMDGPUISD::ATOMIC_INC: 12356 case AMDGPUISD::ATOMIC_DEC: 12357 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12358 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12359 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12360 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12361 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12362 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12363 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12364 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12365 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12366 case AMDGPUISD::BUFFER_ATOMIC_AND: 12367 case AMDGPUISD::BUFFER_ATOMIC_OR: 12368 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12369 case AMDGPUISD::BUFFER_ATOMIC_INC: 12370 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12371 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12372 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12373 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12374 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12375 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12376 // Target-specific read-modify-write atomics are sources of divergence. 12377 return true; 12378 default: 12379 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12380 // Generic read-modify-write atomics are sources of divergence. 12381 return A->readMem() && A->writeMem(); 12382 } 12383 return false; 12384 } 12385 } 12386 12387 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12388 EVT VT) const { 12389 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12390 case MVT::f32: 12391 return hasFP32Denormals(DAG.getMachineFunction()); 12392 case MVT::f64: 12393 case MVT::f16: 12394 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12395 default: 12396 return false; 12397 } 12398 } 12399 12400 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12401 MachineFunction &MF) const { 12402 switch (Ty.getScalarSizeInBits()) { 12403 case 32: 12404 return hasFP32Denormals(MF); 12405 case 64: 12406 case 16: 12407 return hasFP64FP16Denormals(MF); 12408 default: 12409 return false; 12410 } 12411 } 12412 12413 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12414 const SelectionDAG &DAG, 12415 bool SNaN, 12416 unsigned Depth) const { 12417 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12418 const MachineFunction &MF = DAG.getMachineFunction(); 12419 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12420 12421 if (Info->getMode().DX10Clamp) 12422 return true; // Clamped to 0. 12423 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12424 } 12425 12426 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12427 SNaN, Depth); 12428 } 12429 12430 // Global FP atomic instructions have a hardcoded FP mode and do not support 12431 // FP32 denormals, and only support v2f16 denormals. 12432 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12433 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12434 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12435 if (&Flt == &APFloat::IEEEsingle()) 12436 return DenormMode == DenormalMode::getPreserveSign(); 12437 return DenormMode == DenormalMode::getIEEE(); 12438 } 12439 12440 TargetLowering::AtomicExpansionKind 12441 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12442 unsigned AS = RMW->getPointerAddressSpace(); 12443 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12444 return AtomicExpansionKind::NotAtomic; 12445 12446 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12447 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12448 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12449 SmallVector<StringRef> SSNs; 12450 Ctx.getSyncScopeNames(SSNs); 12451 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12452 ? "system" 12453 : SSNs[RMW->getSyncScopeID()]; 12454 ORE.emit([&]() { 12455 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12456 << "Hardware instruction generated for atomic " 12457 << RMW->getOperationName(RMW->getOperation()) 12458 << " operation at memory scope " << MemScope 12459 << " due to an unsafe request."; 12460 }); 12461 return Kind; 12462 }; 12463 12464 switch (RMW->getOperation()) { 12465 case AtomicRMWInst::FAdd: { 12466 Type *Ty = RMW->getType(); 12467 12468 // We don't have a way to support 16-bit atomics now, so just leave them 12469 // as-is. 12470 if (Ty->isHalfTy()) 12471 return AtomicExpansionKind::None; 12472 12473 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12474 return AtomicExpansionKind::CmpXChg; 12475 12476 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12477 Subtarget->hasAtomicFaddInsts()) { 12478 if (Subtarget->hasGFX940Insts()) 12479 return AtomicExpansionKind::None; 12480 12481 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12482 // floating point atomic instructions. May generate more efficient code, 12483 // but may not respect rounding and denormal modes, and may give incorrect 12484 // results for certain memory destinations. 12485 if (RMW->getFunction() 12486 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12487 .getValueAsString() != "true") 12488 return AtomicExpansionKind::CmpXChg; 12489 12490 if (Subtarget->hasGFX90AInsts()) { 12491 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12492 return AtomicExpansionKind::CmpXChg; 12493 12494 auto SSID = RMW->getSyncScopeID(); 12495 if (SSID == SyncScope::System || 12496 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12497 return AtomicExpansionKind::CmpXChg; 12498 12499 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12500 } 12501 12502 if (AS == AMDGPUAS::FLAT_ADDRESS) 12503 return AtomicExpansionKind::CmpXChg; 12504 12505 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12506 : AtomicExpansionKind::CmpXChg; 12507 } 12508 12509 // DS FP atomics do respect the denormal mode, but the rounding mode is 12510 // fixed to round-to-nearest-even. 12511 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12512 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12513 if (!Ty->isDoubleTy()) 12514 return AtomicExpansionKind::None; 12515 12516 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12517 return AtomicExpansionKind::None; 12518 12519 return RMW->getFunction() 12520 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12521 .getValueAsString() == "true" 12522 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12523 : AtomicExpansionKind::CmpXChg; 12524 } 12525 12526 return AtomicExpansionKind::CmpXChg; 12527 } 12528 default: 12529 break; 12530 } 12531 12532 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12533 } 12534 12535 TargetLowering::AtomicExpansionKind 12536 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12537 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12538 ? AtomicExpansionKind::NotAtomic 12539 : AtomicExpansionKind::None; 12540 } 12541 12542 TargetLowering::AtomicExpansionKind 12543 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12544 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12545 ? AtomicExpansionKind::NotAtomic 12546 : AtomicExpansionKind::None; 12547 } 12548 12549 TargetLowering::AtomicExpansionKind 12550 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12551 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12552 ? AtomicExpansionKind::NotAtomic 12553 : AtomicExpansionKind::None; 12554 } 12555 12556 const TargetRegisterClass * 12557 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12558 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12559 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12560 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12561 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12562 : &AMDGPU::SReg_32RegClass; 12563 if (!TRI->isSGPRClass(RC) && !isDivergent) 12564 return TRI->getEquivalentSGPRClass(RC); 12565 else if (TRI->isSGPRClass(RC) && isDivergent) 12566 return TRI->getEquivalentVGPRClass(RC); 12567 12568 return RC; 12569 } 12570 12571 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12572 // uniform values (as produced by the mask results of control flow intrinsics) 12573 // used outside of divergent blocks. The phi users need to also be treated as 12574 // always uniform. 12575 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12576 unsigned WaveSize) { 12577 // FIXME: We assume we never cast the mask results of a control flow 12578 // intrinsic. 12579 // Early exit if the type won't be consistent as a compile time hack. 12580 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12581 if (!IT || IT->getBitWidth() != WaveSize) 12582 return false; 12583 12584 if (!isa<Instruction>(V)) 12585 return false; 12586 if (!Visited.insert(V).second) 12587 return false; 12588 bool Result = false; 12589 for (auto U : V->users()) { 12590 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12591 if (V == U->getOperand(1)) { 12592 switch (Intrinsic->getIntrinsicID()) { 12593 default: 12594 Result = false; 12595 break; 12596 case Intrinsic::amdgcn_if_break: 12597 case Intrinsic::amdgcn_if: 12598 case Intrinsic::amdgcn_else: 12599 Result = true; 12600 break; 12601 } 12602 } 12603 if (V == U->getOperand(0)) { 12604 switch (Intrinsic->getIntrinsicID()) { 12605 default: 12606 Result = false; 12607 break; 12608 case Intrinsic::amdgcn_end_cf: 12609 case Intrinsic::amdgcn_loop: 12610 Result = true; 12611 break; 12612 } 12613 } 12614 } else { 12615 Result = hasCFUser(U, Visited, WaveSize); 12616 } 12617 if (Result) 12618 break; 12619 } 12620 return Result; 12621 } 12622 12623 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12624 const Value *V) const { 12625 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12626 if (CI->isInlineAsm()) { 12627 // FIXME: This cannot give a correct answer. This should only trigger in 12628 // the case where inline asm returns mixed SGPR and VGPR results, used 12629 // outside the defining block. We don't have a specific result to 12630 // consider, so this assumes if any value is SGPR, the overall register 12631 // also needs to be SGPR. 12632 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12633 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12634 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12635 for (auto &TC : TargetConstraints) { 12636 if (TC.Type == InlineAsm::isOutput) { 12637 ComputeConstraintToUse(TC, SDValue()); 12638 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12639 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12640 if (RC && SIRI->isSGPRClass(RC)) 12641 return true; 12642 } 12643 } 12644 } 12645 } 12646 SmallPtrSet<const Value *, 16> Visited; 12647 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12648 } 12649 12650 std::pair<InstructionCost, MVT> 12651 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12652 Type *Ty) const { 12653 std::pair<InstructionCost, MVT> Cost = 12654 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12655 auto Size = DL.getTypeSizeInBits(Ty); 12656 // Maximum load or store can handle 8 dwords for scalar and 4 for 12657 // vector ALU. Let's assume anything above 8 dwords is expensive 12658 // even if legal. 12659 if (Size <= 256) 12660 return Cost; 12661 12662 Cost.first += (Size + 255) / 256; 12663 return Cost; 12664 } 12665 12666 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12667 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12668 for (; I != E; ++I) { 12669 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12670 if (getBasePtrIndex(M) == I.getOperandNo()) 12671 return true; 12672 } 12673 } 12674 return false; 12675 } 12676 12677 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12678 SDValue N1) const { 12679 if (!N0.hasOneUse()) 12680 return false; 12681 // Take care of the opportunity to keep N0 uniform 12682 if (N0->isDivergent() || !N1->isDivergent()) 12683 return true; 12684 // Check if we have a good chance to form the memory access pattern with the 12685 // base and offset 12686 return (DAG.isBaseWithConstantOffset(N0) && 12687 hasMemSDNodeUser(*N0->use_begin())); 12688 } 12689 12690 MachineMemOperand::Flags 12691 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12692 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12693 if (I.getMetadata("amdgpu.noclobber")) 12694 return MONoClobber; 12695 return MachineMemOperand::MONone; 12696 } 12697