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, Custom); 741 } 742 } 743 744 if (Subtarget->hasVOP3PInsts()) { 745 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 746 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 747 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 748 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 749 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 750 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 751 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 752 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 753 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 754 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 755 756 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 757 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 758 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 759 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 760 761 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 762 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 763 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 764 765 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 766 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 767 768 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 769 770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 771 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 772 773 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 774 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 775 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom); 776 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom); 777 778 for (MVT VT : { MVT::v4i16, MVT::v8i16 }) { 779 // Split vector operations. 780 setOperationAction(ISD::SHL, VT, Custom); 781 setOperationAction(ISD::SRA, VT, Custom); 782 setOperationAction(ISD::SRL, VT, Custom); 783 setOperationAction(ISD::ADD, VT, Custom); 784 setOperationAction(ISD::SUB, VT, Custom); 785 setOperationAction(ISD::MUL, VT, Custom); 786 787 setOperationAction(ISD::SMIN, VT, Custom); 788 setOperationAction(ISD::SMAX, VT, Custom); 789 setOperationAction(ISD::UMIN, VT, Custom); 790 setOperationAction(ISD::UMAX, VT, Custom); 791 792 setOperationAction(ISD::UADDSAT, VT, Custom); 793 setOperationAction(ISD::SADDSAT, VT, Custom); 794 setOperationAction(ISD::USUBSAT, VT, Custom); 795 setOperationAction(ISD::SSUBSAT, VT, Custom); 796 } 797 798 for (MVT VT : { MVT::v4f16, MVT::v8f16 }) { 799 // Split vector operations. 800 setOperationAction(ISD::FADD, VT, Custom); 801 setOperationAction(ISD::FMUL, VT, Custom); 802 setOperationAction(ISD::FMA, VT, Custom); 803 setOperationAction(ISD::FCANONICALIZE, VT, Custom); 804 } 805 806 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 807 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 808 809 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 810 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 811 812 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 813 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 814 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 815 816 if (Subtarget->hasPackedFP32Ops()) { 817 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 818 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 819 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 820 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 821 822 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 823 setOperationAction(ISD::FADD, VT, Custom); 824 setOperationAction(ISD::FMUL, VT, Custom); 825 setOperationAction(ISD::FMA, VT, Custom); 826 } 827 } 828 } 829 830 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 831 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 832 833 if (Subtarget->has16BitInsts()) { 834 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 835 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 836 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 837 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 838 } else { 839 // Legalization hack. 840 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 841 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 842 843 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 844 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 845 } 846 847 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8, 848 MVT::v8i16, MVT::v8f16 }) { 849 setOperationAction(ISD::SELECT, VT, Custom); 850 } 851 852 setOperationAction(ISD::SMULO, MVT::i64, Custom); 853 setOperationAction(ISD::UMULO, MVT::i64, Custom); 854 855 if (Subtarget->hasMad64_32()) { 856 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 857 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 858 } 859 860 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 861 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 862 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 863 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 864 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 865 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 866 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 867 868 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 869 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 870 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 871 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 872 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 873 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 874 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 875 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 876 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 877 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 878 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 879 880 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 881 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 882 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 883 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 884 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 885 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 886 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 887 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 888 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 889 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 890 891 setTargetDAGCombine({ISD::ADD, 892 ISD::ADDCARRY, 893 ISD::SUB, 894 ISD::SUBCARRY, 895 ISD::FADD, 896 ISD::FSUB, 897 ISD::FMINNUM, 898 ISD::FMAXNUM, 899 ISD::FMINNUM_IEEE, 900 ISD::FMAXNUM_IEEE, 901 ISD::FMA, 902 ISD::SMIN, 903 ISD::SMAX, 904 ISD::UMIN, 905 ISD::UMAX, 906 ISD::SETCC, 907 ISD::AND, 908 ISD::OR, 909 ISD::XOR, 910 ISD::SINT_TO_FP, 911 ISD::UINT_TO_FP, 912 ISD::FCANONICALIZE, 913 ISD::SCALAR_TO_VECTOR, 914 ISD::ZERO_EXTEND, 915 ISD::SIGN_EXTEND_INREG, 916 ISD::EXTRACT_VECTOR_ELT, 917 ISD::INSERT_VECTOR_ELT}); 918 919 // All memory operations. Some folding on the pointer operand is done to help 920 // matching the constant offsets in the addressing modes. 921 setTargetDAGCombine({ISD::LOAD, 922 ISD::STORE, 923 ISD::ATOMIC_LOAD, 924 ISD::ATOMIC_STORE, 925 ISD::ATOMIC_CMP_SWAP, 926 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, 927 ISD::ATOMIC_SWAP, 928 ISD::ATOMIC_LOAD_ADD, 929 ISD::ATOMIC_LOAD_SUB, 930 ISD::ATOMIC_LOAD_AND, 931 ISD::ATOMIC_LOAD_OR, 932 ISD::ATOMIC_LOAD_XOR, 933 ISD::ATOMIC_LOAD_NAND, 934 ISD::ATOMIC_LOAD_MIN, 935 ISD::ATOMIC_LOAD_MAX, 936 ISD::ATOMIC_LOAD_UMIN, 937 ISD::ATOMIC_LOAD_UMAX, 938 ISD::ATOMIC_LOAD_FADD, 939 ISD::INTRINSIC_VOID, 940 ISD::INTRINSIC_W_CHAIN}); 941 942 // FIXME: In other contexts we pretend this is a per-function property. 943 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 944 945 setSchedulingPreference(Sched::RegPressure); 946 } 947 948 const GCNSubtarget *SITargetLowering::getSubtarget() const { 949 return Subtarget; 950 } 951 952 //===----------------------------------------------------------------------===// 953 // TargetLowering queries 954 //===----------------------------------------------------------------------===// 955 956 // v_mad_mix* support a conversion from f16 to f32. 957 // 958 // There is only one special case when denormals are enabled we don't currently, 959 // where this is OK to use. 960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 961 EVT DestVT, EVT SrcVT) const { 962 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 963 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 964 DestVT.getScalarType() == MVT::f32 && 965 SrcVT.getScalarType() == MVT::f16 && 966 // TODO: This probably only requires no input flushing? 967 !hasFP32Denormals(DAG.getMachineFunction()); 968 } 969 970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 971 LLT DestTy, LLT SrcTy) const { 972 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 973 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 974 DestTy.getScalarSizeInBits() == 32 && 975 SrcTy.getScalarSizeInBits() == 16 && 976 // TODO: This probably only requires no input flushing? 977 !hasFP32Denormals(*MI.getMF()); 978 } 979 980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 981 // SI has some legal vector types, but no legal vector operations. Say no 982 // shuffles are legal in order to prefer scalarizing some vector operations. 983 return false; 984 } 985 986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 987 CallingConv::ID CC, 988 EVT VT) const { 989 if (CC == CallingConv::AMDGPU_KERNEL) 990 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 991 992 if (VT.isVector()) { 993 EVT ScalarVT = VT.getScalarType(); 994 unsigned Size = ScalarVT.getSizeInBits(); 995 if (Size == 16) { 996 if (Subtarget->has16BitInsts()) 997 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 998 return VT.isInteger() ? MVT::i32 : MVT::f32; 999 } 1000 1001 if (Size < 16) 1002 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 1003 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 1004 } 1005 1006 if (VT.getSizeInBits() > 32) 1007 return MVT::i32; 1008 1009 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1010 } 1011 1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1013 CallingConv::ID CC, 1014 EVT VT) const { 1015 if (CC == CallingConv::AMDGPU_KERNEL) 1016 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1017 1018 if (VT.isVector()) { 1019 unsigned NumElts = VT.getVectorNumElements(); 1020 EVT ScalarVT = VT.getScalarType(); 1021 unsigned Size = ScalarVT.getSizeInBits(); 1022 1023 // FIXME: Should probably promote 8-bit vectors to i16. 1024 if (Size == 16 && Subtarget->has16BitInsts()) 1025 return (NumElts + 1) / 2; 1026 1027 if (Size <= 32) 1028 return NumElts; 1029 1030 if (Size > 32) 1031 return NumElts * ((Size + 31) / 32); 1032 } else if (VT.getSizeInBits() > 32) 1033 return (VT.getSizeInBits() + 31) / 32; 1034 1035 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1036 } 1037 1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 1039 LLVMContext &Context, CallingConv::ID CC, 1040 EVT VT, EVT &IntermediateVT, 1041 unsigned &NumIntermediates, MVT &RegisterVT) const { 1042 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 1043 unsigned NumElts = VT.getVectorNumElements(); 1044 EVT ScalarVT = VT.getScalarType(); 1045 unsigned Size = ScalarVT.getSizeInBits(); 1046 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1047 // support, but unless we can properly handle 3-vectors, it will be still be 1048 // inconsistent. 1049 if (Size == 16 && Subtarget->has16BitInsts()) { 1050 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1051 IntermediateVT = RegisterVT; 1052 NumIntermediates = (NumElts + 1) / 2; 1053 return NumIntermediates; 1054 } 1055 1056 if (Size == 32) { 1057 RegisterVT = ScalarVT.getSimpleVT(); 1058 IntermediateVT = RegisterVT; 1059 NumIntermediates = NumElts; 1060 return NumIntermediates; 1061 } 1062 1063 if (Size < 16 && Subtarget->has16BitInsts()) { 1064 // FIXME: Should probably form v2i16 pieces 1065 RegisterVT = MVT::i16; 1066 IntermediateVT = ScalarVT; 1067 NumIntermediates = NumElts; 1068 return NumIntermediates; 1069 } 1070 1071 1072 if (Size != 16 && Size <= 32) { 1073 RegisterVT = MVT::i32; 1074 IntermediateVT = ScalarVT; 1075 NumIntermediates = NumElts; 1076 return NumIntermediates; 1077 } 1078 1079 if (Size > 32) { 1080 RegisterVT = MVT::i32; 1081 IntermediateVT = RegisterVT; 1082 NumIntermediates = NumElts * ((Size + 31) / 32); 1083 return NumIntermediates; 1084 } 1085 } 1086 1087 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1088 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1089 } 1090 1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1092 assert(DMaskLanes != 0); 1093 1094 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1095 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1096 return EVT::getVectorVT(Ty->getContext(), 1097 EVT::getEVT(VT->getElementType()), 1098 NumElts); 1099 } 1100 1101 return EVT::getEVT(Ty); 1102 } 1103 1104 // Peek through TFE struct returns to only use the data size. 1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1106 auto *ST = dyn_cast<StructType>(Ty); 1107 if (!ST) 1108 return memVTFromImageData(Ty, DMaskLanes); 1109 1110 // Some intrinsics return an aggregate type - special case to work out the 1111 // correct memVT. 1112 // 1113 // Only limited forms of aggregate type currently expected. 1114 if (ST->getNumContainedTypes() != 2 || 1115 !ST->getContainedType(1)->isIntegerTy(32)) 1116 return EVT(); 1117 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1118 } 1119 1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1121 const CallInst &CI, 1122 MachineFunction &MF, 1123 unsigned IntrID) const { 1124 Info.flags = MachineMemOperand::MONone; 1125 if (CI.hasMetadata(LLVMContext::MD_invariant_load)) 1126 Info.flags |= MachineMemOperand::MOInvariant; 1127 1128 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1129 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1130 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1131 (Intrinsic::ID)IntrID); 1132 if (Attr.hasFnAttr(Attribute::ReadNone)) 1133 return false; 1134 1135 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1136 1137 if (RsrcIntr->IsImage) { 1138 Info.ptrVal = 1139 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1140 Info.align.reset(); 1141 } else { 1142 Info.ptrVal = 1143 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1144 } 1145 1146 Info.flags |= MachineMemOperand::MODereferenceable; 1147 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1148 unsigned DMaskLanes = 4; 1149 1150 if (RsrcIntr->IsImage) { 1151 const AMDGPU::ImageDimIntrinsicInfo *Intr 1152 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1153 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1154 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1155 1156 if (!BaseOpcode->Gather4) { 1157 // If this isn't a gather, we may have excess loaded elements in the 1158 // IR type. Check the dmask for the real number of elements loaded. 1159 unsigned DMask 1160 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1161 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1162 } 1163 1164 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1165 } else 1166 Info.memVT = EVT::getEVT(CI.getType()); 1167 1168 // FIXME: What does alignment mean for an image? 1169 Info.opc = ISD::INTRINSIC_W_CHAIN; 1170 Info.flags |= MachineMemOperand::MOLoad; 1171 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1172 Info.opc = ISD::INTRINSIC_VOID; 1173 1174 Type *DataTy = CI.getArgOperand(0)->getType(); 1175 if (RsrcIntr->IsImage) { 1176 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1177 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1178 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1179 } else 1180 Info.memVT = EVT::getEVT(DataTy); 1181 1182 Info.flags |= MachineMemOperand::MOStore; 1183 } else { 1184 // Atomic 1185 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1186 ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1188 Info.flags |= MachineMemOperand::MOLoad | 1189 MachineMemOperand::MOStore | 1190 MachineMemOperand::MODereferenceable; 1191 1192 // XXX - Should this be volatile without known ordering? 1193 Info.flags |= MachineMemOperand::MOVolatile; 1194 } 1195 return true; 1196 } 1197 1198 switch (IntrID) { 1199 case Intrinsic::amdgcn_atomic_inc: 1200 case Intrinsic::amdgcn_atomic_dec: 1201 case Intrinsic::amdgcn_ds_ordered_add: 1202 case Intrinsic::amdgcn_ds_ordered_swap: 1203 case Intrinsic::amdgcn_ds_fadd: 1204 case Intrinsic::amdgcn_ds_fmin: 1205 case Intrinsic::amdgcn_ds_fmax: { 1206 Info.opc = ISD::INTRINSIC_W_CHAIN; 1207 Info.memVT = MVT::getVT(CI.getType()); 1208 Info.ptrVal = CI.getOperand(0); 1209 Info.align.reset(); 1210 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1211 1212 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1213 if (!Vol->isZero()) 1214 Info.flags |= MachineMemOperand::MOVolatile; 1215 1216 return true; 1217 } 1218 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1219 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1220 1221 Info.opc = ISD::INTRINSIC_W_CHAIN; 1222 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1223 Info.ptrVal = 1224 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1225 Info.align.reset(); 1226 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1227 1228 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1229 if (!Vol || !Vol->isZero()) 1230 Info.flags |= MachineMemOperand::MOVolatile; 1231 1232 return true; 1233 } 1234 case Intrinsic::amdgcn_ds_append: 1235 case Intrinsic::amdgcn_ds_consume: { 1236 Info.opc = ISD::INTRINSIC_W_CHAIN; 1237 Info.memVT = MVT::getVT(CI.getType()); 1238 Info.ptrVal = CI.getOperand(0); 1239 Info.align.reset(); 1240 Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1241 1242 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1243 if (!Vol->isZero()) 1244 Info.flags |= MachineMemOperand::MOVolatile; 1245 1246 return true; 1247 } 1248 case Intrinsic::amdgcn_global_atomic_csub: { 1249 Info.opc = ISD::INTRINSIC_W_CHAIN; 1250 Info.memVT = MVT::getVT(CI.getType()); 1251 Info.ptrVal = CI.getOperand(0); 1252 Info.align.reset(); 1253 Info.flags |= MachineMemOperand::MOLoad | 1254 MachineMemOperand::MOStore | 1255 MachineMemOperand::MOVolatile; 1256 return true; 1257 } 1258 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1259 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1260 Info.opc = ISD::INTRINSIC_W_CHAIN; 1261 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1262 Info.ptrVal = 1263 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1264 Info.align.reset(); 1265 Info.flags |= MachineMemOperand::MOLoad | 1266 MachineMemOperand::MODereferenceable; 1267 return true; 1268 } 1269 case Intrinsic::amdgcn_global_atomic_fadd: 1270 case Intrinsic::amdgcn_global_atomic_fmin: 1271 case Intrinsic::amdgcn_global_atomic_fmax: 1272 case Intrinsic::amdgcn_flat_atomic_fadd: 1273 case Intrinsic::amdgcn_flat_atomic_fmin: 1274 case Intrinsic::amdgcn_flat_atomic_fmax: 1275 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1276 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: { 1277 Info.opc = ISD::INTRINSIC_W_CHAIN; 1278 Info.memVT = MVT::getVT(CI.getType()); 1279 Info.ptrVal = CI.getOperand(0); 1280 Info.align.reset(); 1281 Info.flags |= MachineMemOperand::MOLoad | 1282 MachineMemOperand::MOStore | 1283 MachineMemOperand::MODereferenceable | 1284 MachineMemOperand::MOVolatile; 1285 return true; 1286 } 1287 case Intrinsic::amdgcn_ds_gws_init: 1288 case Intrinsic::amdgcn_ds_gws_barrier: 1289 case Intrinsic::amdgcn_ds_gws_sema_v: 1290 case Intrinsic::amdgcn_ds_gws_sema_br: 1291 case Intrinsic::amdgcn_ds_gws_sema_p: 1292 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1293 Info.opc = ISD::INTRINSIC_VOID; 1294 1295 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1296 Info.ptrVal = 1297 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1298 1299 // This is an abstract access, but we need to specify a type and size. 1300 Info.memVT = MVT::i32; 1301 Info.size = 4; 1302 Info.align = Align(4); 1303 1304 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1305 Info.flags |= MachineMemOperand::MOLoad; 1306 else 1307 Info.flags |= MachineMemOperand::MOStore; 1308 return true; 1309 } 1310 default: 1311 return false; 1312 } 1313 } 1314 1315 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1316 SmallVectorImpl<Value*> &Ops, 1317 Type *&AccessTy) const { 1318 switch (II->getIntrinsicID()) { 1319 case Intrinsic::amdgcn_atomic_inc: 1320 case Intrinsic::amdgcn_atomic_dec: 1321 case Intrinsic::amdgcn_ds_ordered_add: 1322 case Intrinsic::amdgcn_ds_ordered_swap: 1323 case Intrinsic::amdgcn_ds_append: 1324 case Intrinsic::amdgcn_ds_consume: 1325 case Intrinsic::amdgcn_ds_fadd: 1326 case Intrinsic::amdgcn_ds_fmin: 1327 case Intrinsic::amdgcn_ds_fmax: 1328 case Intrinsic::amdgcn_global_atomic_fadd: 1329 case Intrinsic::amdgcn_flat_atomic_fadd: 1330 case Intrinsic::amdgcn_flat_atomic_fmin: 1331 case Intrinsic::amdgcn_flat_atomic_fmax: 1332 case Intrinsic::amdgcn_global_atomic_fadd_v2bf16: 1333 case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: 1334 case Intrinsic::amdgcn_global_atomic_csub: { 1335 Value *Ptr = II->getArgOperand(0); 1336 AccessTy = II->getType(); 1337 Ops.push_back(Ptr); 1338 return true; 1339 } 1340 default: 1341 return false; 1342 } 1343 } 1344 1345 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1346 if (!Subtarget->hasFlatInstOffsets()) { 1347 // Flat instructions do not have offsets, and only have the register 1348 // address. 1349 return AM.BaseOffs == 0 && AM.Scale == 0; 1350 } 1351 1352 return AM.Scale == 0 && 1353 (AM.BaseOffs == 0 || 1354 Subtarget->getInstrInfo()->isLegalFLATOffset( 1355 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1356 } 1357 1358 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1359 if (Subtarget->hasFlatGlobalInsts()) 1360 return AM.Scale == 0 && 1361 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1362 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1363 SIInstrFlags::FlatGlobal)); 1364 1365 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1366 // Assume the we will use FLAT for all global memory accesses 1367 // on VI. 1368 // FIXME: This assumption is currently wrong. On VI we still use 1369 // MUBUF instructions for the r + i addressing mode. As currently 1370 // implemented, the MUBUF instructions only work on buffer < 4GB. 1371 // It may be possible to support > 4GB buffers with MUBUF instructions, 1372 // by setting the stride value in the resource descriptor which would 1373 // increase the size limit to (stride * 4GB). However, this is risky, 1374 // because it has never been validated. 1375 return isLegalFlatAddressingMode(AM); 1376 } 1377 1378 return isLegalMUBUFAddressingMode(AM); 1379 } 1380 1381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1382 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1383 // additionally can do r + r + i with addr64. 32-bit has more addressing 1384 // mode options. Depending on the resource constant, it can also do 1385 // (i64 r0) + (i32 r1) * (i14 i). 1386 // 1387 // Private arrays end up using a scratch buffer most of the time, so also 1388 // assume those use MUBUF instructions. Scratch loads / stores are currently 1389 // implemented as mubuf instructions with offen bit set, so slightly 1390 // different than the normal addr64. 1391 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1392 return false; 1393 1394 // FIXME: Since we can split immediate into soffset and immediate offset, 1395 // would it make sense to allow any immediate? 1396 1397 switch (AM.Scale) { 1398 case 0: // r + i or just i, depending on HasBaseReg. 1399 return true; 1400 case 1: 1401 return true; // We have r + r or r + i. 1402 case 2: 1403 if (AM.HasBaseReg) { 1404 // Reject 2 * r + r. 1405 return false; 1406 } 1407 1408 // Allow 2 * r as r + r 1409 // Or 2 * r + i is allowed as r + r + i. 1410 return true; 1411 default: // Don't allow n * r 1412 return false; 1413 } 1414 } 1415 1416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1417 const AddrMode &AM, Type *Ty, 1418 unsigned AS, Instruction *I) const { 1419 // No global is ever allowed as a base. 1420 if (AM.BaseGV) 1421 return false; 1422 1423 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1424 return isLegalGlobalAddressingMode(AM); 1425 1426 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1427 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1428 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1429 // If the offset isn't a multiple of 4, it probably isn't going to be 1430 // correctly aligned. 1431 // FIXME: Can we get the real alignment here? 1432 if (AM.BaseOffs % 4 != 0) 1433 return isLegalMUBUFAddressingMode(AM); 1434 1435 // There are no SMRD extloads, so if we have to do a small type access we 1436 // will use a MUBUF load. 1437 // FIXME?: We also need to do this if unaligned, but we don't know the 1438 // alignment here. 1439 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1440 return isLegalGlobalAddressingMode(AM); 1441 1442 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1443 // SMRD instructions have an 8-bit, dword offset on SI. 1444 if (!isUInt<8>(AM.BaseOffs / 4)) 1445 return false; 1446 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1447 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1448 // in 8-bits, it can use a smaller encoding. 1449 if (!isUInt<32>(AM.BaseOffs / 4)) 1450 return false; 1451 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1452 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1453 if (!isUInt<20>(AM.BaseOffs)) 1454 return false; 1455 } else 1456 llvm_unreachable("unhandled generation"); 1457 1458 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1459 return true; 1460 1461 if (AM.Scale == 1 && AM.HasBaseReg) 1462 return true; 1463 1464 return false; 1465 1466 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1467 return isLegalMUBUFAddressingMode(AM); 1468 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1469 AS == AMDGPUAS::REGION_ADDRESS) { 1470 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1471 // field. 1472 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1473 // an 8-bit dword offset but we don't know the alignment here. 1474 if (!isUInt<16>(AM.BaseOffs)) 1475 return false; 1476 1477 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1478 return true; 1479 1480 if (AM.Scale == 1 && AM.HasBaseReg) 1481 return true; 1482 1483 return false; 1484 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1485 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1486 // For an unknown address space, this usually means that this is for some 1487 // reason being used for pure arithmetic, and not based on some addressing 1488 // computation. We don't have instructions that compute pointers with any 1489 // addressing modes, so treat them as having no offset like flat 1490 // instructions. 1491 return isLegalFlatAddressingMode(AM); 1492 } 1493 1494 // Assume a user alias of global for unknown address spaces. 1495 return isLegalGlobalAddressingMode(AM); 1496 } 1497 1498 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1499 const MachineFunction &MF) const { 1500 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1501 return (MemVT.getSizeInBits() <= 4 * 32); 1502 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1503 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1504 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1505 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1506 return (MemVT.getSizeInBits() <= 2 * 32); 1507 } 1508 return true; 1509 } 1510 1511 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1512 unsigned Size, unsigned AddrSpace, Align Alignment, 1513 MachineMemOperand::Flags Flags, bool *IsFast) const { 1514 if (IsFast) 1515 *IsFast = false; 1516 1517 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1518 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1519 // Check if alignment requirements for ds_read/write instructions are 1520 // disabled. 1521 if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4)) 1522 return false; 1523 1524 Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment. 1525 if (Subtarget->hasLDSMisalignedBug() && Size > 32 && 1526 Alignment < RequiredAlignment) 1527 return false; 1528 1529 // Either, the alignment requirements are "enabled", or there is an 1530 // unaligned LDS access related hardware bug though alignment requirements 1531 // are "disabled". In either case, we need to check for proper alignment 1532 // requirements. 1533 // 1534 switch (Size) { 1535 case 64: 1536 // SI has a hardware bug in the LDS / GDS bounds checking: if the base 1537 // address is negative, then the instruction is incorrectly treated as 1538 // out-of-bounds even if base + offsets is in bounds. Split vectorized 1539 // loads here to avoid emitting ds_read2_b32. We may re-combine the 1540 // load later in the SILoadStoreOptimizer. 1541 if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8)) 1542 return false; 1543 1544 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1545 // can do a 4 byte aligned, 8 byte access in a single operation using 1546 // ds_read2/write2_b32 with adjacent offsets. 1547 RequiredAlignment = Align(4); 1548 1549 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1550 // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/ 1551 // ds_write2_b32 depending on the alignment. In either case with either 1552 // alignment there is no faster way of doing this. 1553 if (IsFast) 1554 *IsFast = true; 1555 return true; 1556 } 1557 1558 break; 1559 case 96: 1560 if (!Subtarget->hasDS96AndDS128()) 1561 return false; 1562 1563 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1564 // gfx8 and older. 1565 1566 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1567 // Naturally aligned access is fastest. However, also report it is Fast 1568 // if memory is aligned less than DWORD. A narrow load or store will be 1569 // be equally slow as a single ds_read_b96/ds_write_b96, but there will 1570 // be more of them, so overall we will pay less penalty issuing a single 1571 // instruction. 1572 if (IsFast) 1573 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1574 return true; 1575 } 1576 1577 break; 1578 case 128: 1579 if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128()) 1580 return false; 1581 1582 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1583 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1584 // single operation using ds_read2/write2_b64. 1585 RequiredAlignment = Align(8); 1586 1587 if (Subtarget->hasUnalignedDSAccessEnabled()) { 1588 // Naturally aligned access is fastest. However, also report it is Fast 1589 // if memory is aligned less than DWORD. A narrow load or store will be 1590 // be equally slow as a single ds_read_b128/ds_write_b128, but there 1591 // will be more of them, so overall we will pay less penalty issuing a 1592 // single instruction. 1593 if (IsFast) 1594 *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4); 1595 return true; 1596 } 1597 1598 break; 1599 default: 1600 if (Size > 32) 1601 return false; 1602 1603 break; 1604 } 1605 1606 if (IsFast) 1607 *IsFast = Alignment >= RequiredAlignment; 1608 1609 return Alignment >= RequiredAlignment || 1610 Subtarget->hasUnalignedDSAccessEnabled(); 1611 } 1612 1613 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1614 bool AlignedBy4 = Alignment >= Align(4); 1615 if (IsFast) 1616 *IsFast = AlignedBy4; 1617 1618 return AlignedBy4 || 1619 Subtarget->enableFlatScratch() || 1620 Subtarget->hasUnalignedScratchAccess(); 1621 } 1622 1623 // FIXME: We have to be conservative here and assume that flat operations 1624 // will access scratch. If we had access to the IR function, then we 1625 // could determine if any private memory was used in the function. 1626 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1627 !Subtarget->hasUnalignedScratchAccess()) { 1628 bool AlignedBy4 = Alignment >= Align(4); 1629 if (IsFast) 1630 *IsFast = AlignedBy4; 1631 1632 return AlignedBy4; 1633 } 1634 1635 if (Subtarget->hasUnalignedBufferAccessEnabled()) { 1636 // If we have a uniform constant load, it still requires using a slow 1637 // buffer instruction if unaligned. 1638 if (IsFast) { 1639 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1640 // 2-byte alignment is worse than 1 unless doing a 2-byte access. 1641 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1642 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1643 Alignment >= Align(4) : Alignment != Align(2); 1644 } 1645 1646 return true; 1647 } 1648 1649 // Smaller than dword value must be aligned. 1650 if (Size < 32) 1651 return false; 1652 1653 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1654 // byte-address are ignored, thus forcing Dword alignment. 1655 // This applies to private, global, and constant memory. 1656 if (IsFast) 1657 *IsFast = true; 1658 1659 return Size >= 32 && Alignment >= Align(4); 1660 } 1661 1662 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1663 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1664 bool *IsFast) const { 1665 bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1666 Alignment, Flags, IsFast); 1667 1668 if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() && 1669 (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1670 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1671 // Lie it is fast if +unaligned-access-mode is passed so that DS accesses 1672 // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a 1673 // misaligned data which is faster than a pair of ds_read_b*/ds_write_b* 1674 // which would be equally misaligned. 1675 // This is only used by the common passes, selection always calls the 1676 // allowsMisalignedMemoryAccessesImpl version. 1677 *IsFast = true; 1678 } 1679 1680 return Allow; 1681 } 1682 1683 EVT SITargetLowering::getOptimalMemOpType( 1684 const MemOp &Op, const AttributeList &FuncAttributes) const { 1685 // FIXME: Should account for address space here. 1686 1687 // The default fallback uses the private pointer size as a guess for a type to 1688 // use. Make sure we switch these to 64-bit accesses. 1689 1690 if (Op.size() >= 16 && 1691 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1692 return MVT::v4i32; 1693 1694 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1695 return MVT::v2i32; 1696 1697 // Use the default. 1698 return MVT::Other; 1699 } 1700 1701 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1702 const MemSDNode *MemNode = cast<MemSDNode>(N); 1703 return MemNode->getMemOperand()->getFlags() & MONoClobber; 1704 } 1705 1706 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1707 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1708 AS == AMDGPUAS::PRIVATE_ADDRESS; 1709 } 1710 1711 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1712 unsigned DestAS) const { 1713 // Flat -> private/local is a simple truncate. 1714 // Flat -> global is no-op 1715 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1716 return true; 1717 1718 const GCNTargetMachine &TM = 1719 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1720 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1721 } 1722 1723 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1724 const MemSDNode *MemNode = cast<MemSDNode>(N); 1725 1726 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1727 } 1728 1729 TargetLoweringBase::LegalizeTypeAction 1730 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1731 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1732 VT.getScalarType().bitsLE(MVT::i16)) 1733 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1734 return TargetLoweringBase::getPreferredVectorAction(VT); 1735 } 1736 1737 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1738 Type *Ty) const { 1739 // FIXME: Could be smarter if called for vector constants. 1740 return true; 1741 } 1742 1743 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1744 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1745 switch (Op) { 1746 case ISD::LOAD: 1747 case ISD::STORE: 1748 1749 // These operations are done with 32-bit instructions anyway. 1750 case ISD::AND: 1751 case ISD::OR: 1752 case ISD::XOR: 1753 case ISD::SELECT: 1754 // TODO: Extensions? 1755 return true; 1756 default: 1757 return false; 1758 } 1759 } 1760 1761 // SimplifySetCC uses this function to determine whether or not it should 1762 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1763 if (VT == MVT::i1 && Op == ISD::SETCC) 1764 return false; 1765 1766 return TargetLowering::isTypeDesirableForOp(Op, VT); 1767 } 1768 1769 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1770 const SDLoc &SL, 1771 SDValue Chain, 1772 uint64_t Offset) const { 1773 const DataLayout &DL = DAG.getDataLayout(); 1774 MachineFunction &MF = DAG.getMachineFunction(); 1775 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1776 1777 const ArgDescriptor *InputPtrReg; 1778 const TargetRegisterClass *RC; 1779 LLT ArgTy; 1780 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1781 1782 std::tie(InputPtrReg, RC, ArgTy) = 1783 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1784 1785 // We may not have the kernarg segment argument if we have no kernel 1786 // arguments. 1787 if (!InputPtrReg) 1788 return DAG.getConstant(0, SL, PtrVT); 1789 1790 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1791 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1792 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1793 1794 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1795 } 1796 1797 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1798 const SDLoc &SL) const { 1799 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1800 FIRST_IMPLICIT); 1801 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1802 } 1803 1804 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1805 const SDLoc &SL, SDValue Val, 1806 bool Signed, 1807 const ISD::InputArg *Arg) const { 1808 // First, if it is a widened vector, narrow it. 1809 if (VT.isVector() && 1810 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1811 EVT NarrowedVT = 1812 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1813 VT.getVectorNumElements()); 1814 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1815 DAG.getConstant(0, SL, MVT::i32)); 1816 } 1817 1818 // Then convert the vector elements or scalar value. 1819 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1820 VT.bitsLT(MemVT)) { 1821 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1822 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1823 } 1824 1825 if (MemVT.isFloatingPoint()) 1826 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1827 else if (Signed) 1828 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1829 else 1830 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1831 1832 return Val; 1833 } 1834 1835 SDValue SITargetLowering::lowerKernargMemParameter( 1836 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1837 uint64_t Offset, Align Alignment, bool Signed, 1838 const ISD::InputArg *Arg) const { 1839 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1840 1841 // Try to avoid using an extload by loading earlier than the argument address, 1842 // and extracting the relevant bits. The load should hopefully be merged with 1843 // the previous argument. 1844 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1845 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1846 int64_t AlignDownOffset = alignDown(Offset, 4); 1847 int64_t OffsetDiff = Offset - AlignDownOffset; 1848 1849 EVT IntVT = MemVT.changeTypeToInteger(); 1850 1851 // TODO: If we passed in the base kernel offset we could have a better 1852 // alignment than 4, but we don't really need it. 1853 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1854 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1855 MachineMemOperand::MODereferenceable | 1856 MachineMemOperand::MOInvariant); 1857 1858 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1859 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1860 1861 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1862 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1863 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1864 1865 1866 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1867 } 1868 1869 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1870 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1871 MachineMemOperand::MODereferenceable | 1872 MachineMemOperand::MOInvariant); 1873 1874 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1875 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1876 } 1877 1878 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1879 const SDLoc &SL, SDValue Chain, 1880 const ISD::InputArg &Arg) const { 1881 MachineFunction &MF = DAG.getMachineFunction(); 1882 MachineFrameInfo &MFI = MF.getFrameInfo(); 1883 1884 if (Arg.Flags.isByVal()) { 1885 unsigned Size = Arg.Flags.getByValSize(); 1886 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1887 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1888 } 1889 1890 unsigned ArgOffset = VA.getLocMemOffset(); 1891 unsigned ArgSize = VA.getValVT().getStoreSize(); 1892 1893 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1894 1895 // Create load nodes to retrieve arguments from the stack. 1896 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1897 SDValue ArgValue; 1898 1899 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1900 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1901 MVT MemVT = VA.getValVT(); 1902 1903 switch (VA.getLocInfo()) { 1904 default: 1905 break; 1906 case CCValAssign::BCvt: 1907 MemVT = VA.getLocVT(); 1908 break; 1909 case CCValAssign::SExt: 1910 ExtType = ISD::SEXTLOAD; 1911 break; 1912 case CCValAssign::ZExt: 1913 ExtType = ISD::ZEXTLOAD; 1914 break; 1915 case CCValAssign::AExt: 1916 ExtType = ISD::EXTLOAD; 1917 break; 1918 } 1919 1920 ArgValue = DAG.getExtLoad( 1921 ExtType, SL, VA.getLocVT(), Chain, FIN, 1922 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1923 MemVT); 1924 return ArgValue; 1925 } 1926 1927 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1928 const SIMachineFunctionInfo &MFI, 1929 EVT VT, 1930 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1931 const ArgDescriptor *Reg; 1932 const TargetRegisterClass *RC; 1933 LLT Ty; 1934 1935 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1936 if (!Reg) { 1937 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1938 // It's possible for a kernarg intrinsic call to appear in a kernel with 1939 // no allocated segment, in which case we do not add the user sgpr 1940 // argument, so just return null. 1941 return DAG.getConstant(0, SDLoc(), VT); 1942 } 1943 1944 // It's undefined behavior if a function marked with the amdgpu-no-* 1945 // attributes uses the corresponding intrinsic. 1946 return DAG.getUNDEF(VT); 1947 } 1948 1949 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1950 } 1951 1952 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1953 CallingConv::ID CallConv, 1954 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1955 FunctionType *FType, 1956 SIMachineFunctionInfo *Info) { 1957 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1958 const ISD::InputArg *Arg = &Ins[I]; 1959 1960 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1961 "vector type argument should have been split"); 1962 1963 // First check if it's a PS input addr. 1964 if (CallConv == CallingConv::AMDGPU_PS && 1965 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1966 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1967 1968 // Inconveniently only the first part of the split is marked as isSplit, 1969 // so skip to the end. We only want to increment PSInputNum once for the 1970 // entire split argument. 1971 if (Arg->Flags.isSplit()) { 1972 while (!Arg->Flags.isSplitEnd()) { 1973 assert((!Arg->VT.isVector() || 1974 Arg->VT.getScalarSizeInBits() == 16) && 1975 "unexpected vector split in ps argument type"); 1976 if (!SkipArg) 1977 Splits.push_back(*Arg); 1978 Arg = &Ins[++I]; 1979 } 1980 } 1981 1982 if (SkipArg) { 1983 // We can safely skip PS inputs. 1984 Skipped.set(Arg->getOrigArgIndex()); 1985 ++PSInputNum; 1986 continue; 1987 } 1988 1989 Info->markPSInputAllocated(PSInputNum); 1990 if (Arg->Used) 1991 Info->markPSInputEnabled(PSInputNum); 1992 1993 ++PSInputNum; 1994 } 1995 1996 Splits.push_back(*Arg); 1997 } 1998 } 1999 2000 // Allocate special inputs passed in VGPRs. 2001 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 2002 MachineFunction &MF, 2003 const SIRegisterInfo &TRI, 2004 SIMachineFunctionInfo &Info) const { 2005 const LLT S32 = LLT::scalar(32); 2006 MachineRegisterInfo &MRI = MF.getRegInfo(); 2007 2008 if (Info.hasWorkItemIDX()) { 2009 Register Reg = AMDGPU::VGPR0; 2010 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2011 2012 CCInfo.AllocateReg(Reg); 2013 unsigned Mask = (Subtarget->hasPackedTID() && 2014 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 2015 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2016 } 2017 2018 if (Info.hasWorkItemIDY()) { 2019 assert(Info.hasWorkItemIDX()); 2020 if (Subtarget->hasPackedTID()) { 2021 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2022 0x3ff << 10)); 2023 } else { 2024 unsigned Reg = AMDGPU::VGPR1; 2025 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2026 2027 CCInfo.AllocateReg(Reg); 2028 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 2029 } 2030 } 2031 2032 if (Info.hasWorkItemIDZ()) { 2033 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 2034 if (Subtarget->hasPackedTID()) { 2035 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 2036 0x3ff << 20)); 2037 } else { 2038 unsigned Reg = AMDGPU::VGPR2; 2039 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 2040 2041 CCInfo.AllocateReg(Reg); 2042 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 2043 } 2044 } 2045 } 2046 2047 // Try to allocate a VGPR at the end of the argument list, or if no argument 2048 // VGPRs are left allocating a stack slot. 2049 // If \p Mask is is given it indicates bitfield position in the register. 2050 // If \p Arg is given use it with new ]p Mask instead of allocating new. 2051 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 2052 ArgDescriptor Arg = ArgDescriptor()) { 2053 if (Arg.isSet()) 2054 return ArgDescriptor::createArg(Arg, Mask); 2055 2056 ArrayRef<MCPhysReg> ArgVGPRs 2057 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 2058 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 2059 if (RegIdx == ArgVGPRs.size()) { 2060 // Spill to stack required. 2061 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 2062 2063 return ArgDescriptor::createStack(Offset, Mask); 2064 } 2065 2066 unsigned Reg = ArgVGPRs[RegIdx]; 2067 Reg = CCInfo.AllocateReg(Reg); 2068 assert(Reg != AMDGPU::NoRegister); 2069 2070 MachineFunction &MF = CCInfo.getMachineFunction(); 2071 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 2072 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 2073 return ArgDescriptor::createRegister(Reg, Mask); 2074 } 2075 2076 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 2077 const TargetRegisterClass *RC, 2078 unsigned NumArgRegs) { 2079 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 2080 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 2081 if (RegIdx == ArgSGPRs.size()) 2082 report_fatal_error("ran out of SGPRs for arguments"); 2083 2084 unsigned Reg = ArgSGPRs[RegIdx]; 2085 Reg = CCInfo.AllocateReg(Reg); 2086 assert(Reg != AMDGPU::NoRegister); 2087 2088 MachineFunction &MF = CCInfo.getMachineFunction(); 2089 MF.addLiveIn(Reg, RC); 2090 return ArgDescriptor::createRegister(Reg); 2091 } 2092 2093 // If this has a fixed position, we still should allocate the register in the 2094 // CCInfo state. Technically we could get away with this for values passed 2095 // outside of the normal argument range. 2096 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 2097 const TargetRegisterClass *RC, 2098 MCRegister Reg) { 2099 Reg = CCInfo.AllocateReg(Reg); 2100 assert(Reg != AMDGPU::NoRegister); 2101 MachineFunction &MF = CCInfo.getMachineFunction(); 2102 MF.addLiveIn(Reg, RC); 2103 } 2104 2105 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2106 if (Arg) { 2107 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2108 Arg.getRegister()); 2109 } else 2110 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2111 } 2112 2113 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2114 if (Arg) { 2115 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2116 Arg.getRegister()); 2117 } else 2118 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2119 } 2120 2121 /// Allocate implicit function VGPR arguments at the end of allocated user 2122 /// arguments. 2123 void SITargetLowering::allocateSpecialInputVGPRs( 2124 CCState &CCInfo, MachineFunction &MF, 2125 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2126 const unsigned Mask = 0x3ff; 2127 ArgDescriptor Arg; 2128 2129 if (Info.hasWorkItemIDX()) { 2130 Arg = allocateVGPR32Input(CCInfo, Mask); 2131 Info.setWorkItemIDX(Arg); 2132 } 2133 2134 if (Info.hasWorkItemIDY()) { 2135 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2136 Info.setWorkItemIDY(Arg); 2137 } 2138 2139 if (Info.hasWorkItemIDZ()) 2140 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2141 } 2142 2143 /// Allocate implicit function VGPR arguments in fixed registers. 2144 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2145 CCState &CCInfo, MachineFunction &MF, 2146 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2147 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2148 if (!Reg) 2149 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2150 2151 const unsigned Mask = 0x3ff; 2152 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2153 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2154 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2155 } 2156 2157 void SITargetLowering::allocateSpecialInputSGPRs( 2158 CCState &CCInfo, 2159 MachineFunction &MF, 2160 const SIRegisterInfo &TRI, 2161 SIMachineFunctionInfo &Info) const { 2162 auto &ArgInfo = Info.getArgInfo(); 2163 2164 // TODO: Unify handling with private memory pointers. 2165 if (Info.hasDispatchPtr()) 2166 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2167 2168 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) 2169 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2170 2171 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2172 // constant offset from the kernarg segment. 2173 if (Info.hasImplicitArgPtr()) 2174 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2175 2176 if (Info.hasDispatchID()) 2177 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2178 2179 // flat_scratch_init is not applicable for non-kernel functions. 2180 2181 if (Info.hasWorkGroupIDX()) 2182 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2183 2184 if (Info.hasWorkGroupIDY()) 2185 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2186 2187 if (Info.hasWorkGroupIDZ()) 2188 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2189 } 2190 2191 // Allocate special inputs passed in user SGPRs. 2192 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2193 MachineFunction &MF, 2194 const SIRegisterInfo &TRI, 2195 SIMachineFunctionInfo &Info) const { 2196 if (Info.hasImplicitBufferPtr()) { 2197 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2198 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2199 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2200 } 2201 2202 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2203 if (Info.hasPrivateSegmentBuffer()) { 2204 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2205 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2206 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2207 } 2208 2209 if (Info.hasDispatchPtr()) { 2210 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2211 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2212 CCInfo.AllocateReg(DispatchPtrReg); 2213 } 2214 2215 if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) { 2216 Register QueuePtrReg = Info.addQueuePtr(TRI); 2217 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2218 CCInfo.AllocateReg(QueuePtrReg); 2219 } 2220 2221 if (Info.hasKernargSegmentPtr()) { 2222 MachineRegisterInfo &MRI = MF.getRegInfo(); 2223 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2224 CCInfo.AllocateReg(InputPtrReg); 2225 2226 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2227 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2228 } 2229 2230 if (Info.hasDispatchID()) { 2231 Register DispatchIDReg = Info.addDispatchID(TRI); 2232 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2233 CCInfo.AllocateReg(DispatchIDReg); 2234 } 2235 2236 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2237 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2238 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2239 CCInfo.AllocateReg(FlatScratchInitReg); 2240 } 2241 2242 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2243 // these from the dispatch pointer. 2244 } 2245 2246 // Allocate special input registers that are initialized per-wave. 2247 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2248 MachineFunction &MF, 2249 SIMachineFunctionInfo &Info, 2250 CallingConv::ID CallConv, 2251 bool IsShader) const { 2252 if (Info.hasWorkGroupIDX()) { 2253 Register Reg = Info.addWorkGroupIDX(); 2254 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2255 CCInfo.AllocateReg(Reg); 2256 } 2257 2258 if (Info.hasWorkGroupIDY()) { 2259 Register Reg = Info.addWorkGroupIDY(); 2260 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2261 CCInfo.AllocateReg(Reg); 2262 } 2263 2264 if (Info.hasWorkGroupIDZ()) { 2265 Register Reg = Info.addWorkGroupIDZ(); 2266 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2267 CCInfo.AllocateReg(Reg); 2268 } 2269 2270 if (Info.hasWorkGroupInfo()) { 2271 Register Reg = Info.addWorkGroupInfo(); 2272 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2273 CCInfo.AllocateReg(Reg); 2274 } 2275 2276 if (Info.hasPrivateSegmentWaveByteOffset()) { 2277 // Scratch wave offset passed in system SGPR. 2278 unsigned PrivateSegmentWaveByteOffsetReg; 2279 2280 if (IsShader) { 2281 PrivateSegmentWaveByteOffsetReg = 2282 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2283 2284 // This is true if the scratch wave byte offset doesn't have a fixed 2285 // location. 2286 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2287 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2288 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2289 } 2290 } else 2291 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2292 2293 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2294 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2295 } 2296 } 2297 2298 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2299 MachineFunction &MF, 2300 const SIRegisterInfo &TRI, 2301 SIMachineFunctionInfo &Info) { 2302 // Now that we've figured out where the scratch register inputs are, see if 2303 // should reserve the arguments and use them directly. 2304 MachineFrameInfo &MFI = MF.getFrameInfo(); 2305 bool HasStackObjects = MFI.hasStackObjects(); 2306 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2307 2308 // Record that we know we have non-spill stack objects so we don't need to 2309 // check all stack objects later. 2310 if (HasStackObjects) 2311 Info.setHasNonSpillStackObjects(true); 2312 2313 // Everything live out of a block is spilled with fast regalloc, so it's 2314 // almost certain that spilling will be required. 2315 if (TM.getOptLevel() == CodeGenOpt::None) 2316 HasStackObjects = true; 2317 2318 // For now assume stack access is needed in any callee functions, so we need 2319 // the scratch registers to pass in. 2320 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2321 2322 if (!ST.enableFlatScratch()) { 2323 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2324 // If we have stack objects, we unquestionably need the private buffer 2325 // resource. For the Code Object V2 ABI, this will be the first 4 user 2326 // SGPR inputs. We can reserve those and use them directly. 2327 2328 Register PrivateSegmentBufferReg = 2329 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2330 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2331 } else { 2332 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2333 // We tentatively reserve the last registers (skipping the last registers 2334 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2335 // we'll replace these with the ones immediately after those which were 2336 // really allocated. In the prologue copies will be inserted from the 2337 // argument to these reserved registers. 2338 2339 // Without HSA, relocations are used for the scratch pointer and the 2340 // buffer resource setup is always inserted in the prologue. Scratch wave 2341 // offset is still in an input SGPR. 2342 Info.setScratchRSrcReg(ReservedBufferReg); 2343 } 2344 } 2345 2346 MachineRegisterInfo &MRI = MF.getRegInfo(); 2347 2348 // For entry functions we have to set up the stack pointer if we use it, 2349 // whereas non-entry functions get this "for free". This means there is no 2350 // intrinsic advantage to using S32 over S34 in cases where we do not have 2351 // calls but do need a frame pointer (i.e. if we are requested to have one 2352 // because frame pointer elimination is disabled). To keep things simple we 2353 // only ever use S32 as the call ABI stack pointer, and so using it does not 2354 // imply we need a separate frame pointer. 2355 // 2356 // Try to use s32 as the SP, but move it if it would interfere with input 2357 // arguments. This won't work with calls though. 2358 // 2359 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2360 // registers. 2361 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2362 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2363 } else { 2364 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2365 2366 if (MFI.hasCalls()) 2367 report_fatal_error("call in graphics shader with too many input SGPRs"); 2368 2369 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2370 if (!MRI.isLiveIn(Reg)) { 2371 Info.setStackPtrOffsetReg(Reg); 2372 break; 2373 } 2374 } 2375 2376 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2377 report_fatal_error("failed to find register for SP"); 2378 } 2379 2380 // hasFP should be accurate for entry functions even before the frame is 2381 // finalized, because it does not rely on the known stack size, only 2382 // properties like whether variable sized objects are present. 2383 if (ST.getFrameLowering()->hasFP(MF)) { 2384 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2385 } 2386 } 2387 2388 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2389 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2390 return !Info->isEntryFunction(); 2391 } 2392 2393 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2394 2395 } 2396 2397 void SITargetLowering::insertCopiesSplitCSR( 2398 MachineBasicBlock *Entry, 2399 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2400 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2401 2402 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2403 if (!IStart) 2404 return; 2405 2406 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2407 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2408 MachineBasicBlock::iterator MBBI = Entry->begin(); 2409 for (const MCPhysReg *I = IStart; *I; ++I) { 2410 const TargetRegisterClass *RC = nullptr; 2411 if (AMDGPU::SReg_64RegClass.contains(*I)) 2412 RC = &AMDGPU::SGPR_64RegClass; 2413 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2414 RC = &AMDGPU::SGPR_32RegClass; 2415 else 2416 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2417 2418 Register NewVR = MRI->createVirtualRegister(RC); 2419 // Create copy from CSR to a virtual register. 2420 Entry->addLiveIn(*I); 2421 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2422 .addReg(*I); 2423 2424 // Insert the copy-back instructions right before the terminator. 2425 for (auto *Exit : Exits) 2426 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2427 TII->get(TargetOpcode::COPY), *I) 2428 .addReg(NewVR); 2429 } 2430 } 2431 2432 SDValue SITargetLowering::LowerFormalArguments( 2433 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2434 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2435 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2436 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2437 2438 MachineFunction &MF = DAG.getMachineFunction(); 2439 const Function &Fn = MF.getFunction(); 2440 FunctionType *FType = MF.getFunction().getFunctionType(); 2441 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2442 2443 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2444 DiagnosticInfoUnsupported NoGraphicsHSA( 2445 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2446 DAG.getContext()->diagnose(NoGraphicsHSA); 2447 return DAG.getEntryNode(); 2448 } 2449 2450 Info->allocateModuleLDSGlobal(Fn); 2451 2452 SmallVector<ISD::InputArg, 16> Splits; 2453 SmallVector<CCValAssign, 16> ArgLocs; 2454 BitVector Skipped(Ins.size()); 2455 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2456 *DAG.getContext()); 2457 2458 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2459 bool IsKernel = AMDGPU::isKernel(CallConv); 2460 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2461 2462 if (IsGraphics) { 2463 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2464 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2465 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2466 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2467 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2468 !Info->hasWorkItemIDZ()); 2469 } 2470 2471 if (CallConv == CallingConv::AMDGPU_PS) { 2472 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2473 2474 // At least one interpolation mode must be enabled or else the GPU will 2475 // hang. 2476 // 2477 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2478 // set PSInputAddr, the user wants to enable some bits after the compilation 2479 // based on run-time states. Since we can't know what the final PSInputEna 2480 // will look like, so we shouldn't do anything here and the user should take 2481 // responsibility for the correct programming. 2482 // 2483 // Otherwise, the following restrictions apply: 2484 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2485 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2486 // enabled too. 2487 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2488 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2489 CCInfo.AllocateReg(AMDGPU::VGPR0); 2490 CCInfo.AllocateReg(AMDGPU::VGPR1); 2491 Info->markPSInputAllocated(0); 2492 Info->markPSInputEnabled(0); 2493 } 2494 if (Subtarget->isAmdPalOS()) { 2495 // For isAmdPalOS, the user does not enable some bits after compilation 2496 // based on run-time states; the register values being generated here are 2497 // the final ones set in hardware. Therefore we need to apply the 2498 // workaround to PSInputAddr and PSInputEnable together. (The case where 2499 // a bit is set in PSInputAddr but not PSInputEnable is where the 2500 // frontend set up an input arg for a particular interpolation mode, but 2501 // nothing uses that input arg. Really we should have an earlier pass 2502 // that removes such an arg.) 2503 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2504 if ((PsInputBits & 0x7F) == 0 || 2505 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2506 Info->markPSInputEnabled( 2507 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2508 } 2509 } else if (IsKernel) { 2510 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2511 } else { 2512 Splits.append(Ins.begin(), Ins.end()); 2513 } 2514 2515 if (IsEntryFunc) { 2516 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2517 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2518 } else if (!IsGraphics) { 2519 // For the fixed ABI, pass workitem IDs in the last argument register. 2520 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2521 } 2522 2523 if (IsKernel) { 2524 analyzeFormalArgumentsCompute(CCInfo, Ins); 2525 } else { 2526 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2527 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2528 } 2529 2530 SmallVector<SDValue, 16> Chains; 2531 2532 // FIXME: This is the minimum kernel argument alignment. We should improve 2533 // this to the maximum alignment of the arguments. 2534 // 2535 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2536 // kern arg offset. 2537 const Align KernelArgBaseAlign = Align(16); 2538 2539 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2540 const ISD::InputArg &Arg = Ins[i]; 2541 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2542 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2543 continue; 2544 } 2545 2546 CCValAssign &VA = ArgLocs[ArgIdx++]; 2547 MVT VT = VA.getLocVT(); 2548 2549 if (IsEntryFunc && VA.isMemLoc()) { 2550 VT = Ins[i].VT; 2551 EVT MemVT = VA.getLocVT(); 2552 2553 const uint64_t Offset = VA.getLocMemOffset(); 2554 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2555 2556 if (Arg.Flags.isByRef()) { 2557 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2558 2559 const GCNTargetMachine &TM = 2560 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2561 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2562 Arg.Flags.getPointerAddrSpace())) { 2563 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2564 Arg.Flags.getPointerAddrSpace()); 2565 } 2566 2567 InVals.push_back(Ptr); 2568 continue; 2569 } 2570 2571 SDValue Arg = lowerKernargMemParameter( 2572 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2573 Chains.push_back(Arg.getValue(1)); 2574 2575 auto *ParamTy = 2576 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2577 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2578 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2579 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2580 // On SI local pointers are just offsets into LDS, so they are always 2581 // less than 16-bits. On CI and newer they could potentially be 2582 // real pointers, so we can't guarantee their size. 2583 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2584 DAG.getValueType(MVT::i16)); 2585 } 2586 2587 InVals.push_back(Arg); 2588 continue; 2589 } else if (!IsEntryFunc && VA.isMemLoc()) { 2590 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2591 InVals.push_back(Val); 2592 if (!Arg.Flags.isByVal()) 2593 Chains.push_back(Val.getValue(1)); 2594 continue; 2595 } 2596 2597 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2598 2599 Register Reg = VA.getLocReg(); 2600 const TargetRegisterClass *RC = nullptr; 2601 if (AMDGPU::VGPR_32RegClass.contains(Reg)) 2602 RC = &AMDGPU::VGPR_32RegClass; 2603 else if (AMDGPU::SGPR_32RegClass.contains(Reg)) 2604 RC = &AMDGPU::SGPR_32RegClass; 2605 else 2606 llvm_unreachable("Unexpected register class in LowerFormalArguments!"); 2607 EVT ValVT = VA.getValVT(); 2608 2609 Reg = MF.addLiveIn(Reg, RC); 2610 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2611 2612 if (Arg.Flags.isSRet()) { 2613 // The return object should be reasonably addressable. 2614 2615 // FIXME: This helps when the return is a real sret. If it is a 2616 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2617 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2618 unsigned NumBits 2619 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2620 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2621 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2622 } 2623 2624 // If this is an 8 or 16-bit value, it is really passed promoted 2625 // to 32 bits. Insert an assert[sz]ext to capture this, then 2626 // truncate to the right size. 2627 switch (VA.getLocInfo()) { 2628 case CCValAssign::Full: 2629 break; 2630 case CCValAssign::BCvt: 2631 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2632 break; 2633 case CCValAssign::SExt: 2634 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2635 DAG.getValueType(ValVT)); 2636 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2637 break; 2638 case CCValAssign::ZExt: 2639 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2640 DAG.getValueType(ValVT)); 2641 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2642 break; 2643 case CCValAssign::AExt: 2644 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2645 break; 2646 default: 2647 llvm_unreachable("Unknown loc info!"); 2648 } 2649 2650 InVals.push_back(Val); 2651 } 2652 2653 // Start adding system SGPRs. 2654 if (IsEntryFunc) { 2655 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2656 } else { 2657 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2658 if (!IsGraphics) 2659 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2660 } 2661 2662 auto &ArgUsageInfo = 2663 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2664 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2665 2666 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2667 Info->setBytesInStackArgArea(StackArgSize); 2668 2669 return Chains.empty() ? Chain : 2670 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2671 } 2672 2673 // TODO: If return values can't fit in registers, we should return as many as 2674 // possible in registers before passing on stack. 2675 bool SITargetLowering::CanLowerReturn( 2676 CallingConv::ID CallConv, 2677 MachineFunction &MF, bool IsVarArg, 2678 const SmallVectorImpl<ISD::OutputArg> &Outs, 2679 LLVMContext &Context) const { 2680 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2681 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2682 // for shaders. Vector types should be explicitly handled by CC. 2683 if (AMDGPU::isEntryFunctionCC(CallConv)) 2684 return true; 2685 2686 SmallVector<CCValAssign, 16> RVLocs; 2687 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2688 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2689 } 2690 2691 SDValue 2692 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2693 bool isVarArg, 2694 const SmallVectorImpl<ISD::OutputArg> &Outs, 2695 const SmallVectorImpl<SDValue> &OutVals, 2696 const SDLoc &DL, SelectionDAG &DAG) const { 2697 MachineFunction &MF = DAG.getMachineFunction(); 2698 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2699 2700 if (AMDGPU::isKernel(CallConv)) { 2701 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2702 OutVals, DL, DAG); 2703 } 2704 2705 bool IsShader = AMDGPU::isShader(CallConv); 2706 2707 Info->setIfReturnsVoid(Outs.empty()); 2708 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2709 2710 // CCValAssign - represent the assignment of the return value to a location. 2711 SmallVector<CCValAssign, 48> RVLocs; 2712 SmallVector<ISD::OutputArg, 48> Splits; 2713 2714 // CCState - Info about the registers and stack slots. 2715 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2716 *DAG.getContext()); 2717 2718 // Analyze outgoing return values. 2719 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2720 2721 SDValue Flag; 2722 SmallVector<SDValue, 48> RetOps; 2723 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2724 2725 // Copy the result values into the output registers. 2726 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2727 ++I, ++RealRVLocIdx) { 2728 CCValAssign &VA = RVLocs[I]; 2729 assert(VA.isRegLoc() && "Can only return in registers!"); 2730 // TODO: Partially return in registers if return values don't fit. 2731 SDValue Arg = OutVals[RealRVLocIdx]; 2732 2733 // Copied from other backends. 2734 switch (VA.getLocInfo()) { 2735 case CCValAssign::Full: 2736 break; 2737 case CCValAssign::BCvt: 2738 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2739 break; 2740 case CCValAssign::SExt: 2741 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2742 break; 2743 case CCValAssign::ZExt: 2744 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2745 break; 2746 case CCValAssign::AExt: 2747 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2748 break; 2749 default: 2750 llvm_unreachable("Unknown loc info!"); 2751 } 2752 2753 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2754 Flag = Chain.getValue(1); 2755 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2756 } 2757 2758 // FIXME: Does sret work properly? 2759 if (!Info->isEntryFunction()) { 2760 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2761 const MCPhysReg *I = 2762 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2763 if (I) { 2764 for (; *I; ++I) { 2765 if (AMDGPU::SReg_64RegClass.contains(*I)) 2766 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2767 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2768 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2769 else 2770 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2771 } 2772 } 2773 } 2774 2775 // Update chain and glue. 2776 RetOps[0] = Chain; 2777 if (Flag.getNode()) 2778 RetOps.push_back(Flag); 2779 2780 unsigned Opc = AMDGPUISD::ENDPGM; 2781 if (!IsWaveEnd) 2782 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2783 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2784 } 2785 2786 SDValue SITargetLowering::LowerCallResult( 2787 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2788 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2789 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2790 SDValue ThisVal) const { 2791 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2792 2793 // Assign locations to each value returned by this call. 2794 SmallVector<CCValAssign, 16> RVLocs; 2795 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2796 *DAG.getContext()); 2797 CCInfo.AnalyzeCallResult(Ins, RetCC); 2798 2799 // Copy all of the result registers out of their specified physreg. 2800 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2801 CCValAssign VA = RVLocs[i]; 2802 SDValue Val; 2803 2804 if (VA.isRegLoc()) { 2805 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2806 Chain = Val.getValue(1); 2807 InFlag = Val.getValue(2); 2808 } else if (VA.isMemLoc()) { 2809 report_fatal_error("TODO: return values in memory"); 2810 } else 2811 llvm_unreachable("unknown argument location type"); 2812 2813 switch (VA.getLocInfo()) { 2814 case CCValAssign::Full: 2815 break; 2816 case CCValAssign::BCvt: 2817 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2818 break; 2819 case CCValAssign::ZExt: 2820 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2821 DAG.getValueType(VA.getValVT())); 2822 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2823 break; 2824 case CCValAssign::SExt: 2825 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2826 DAG.getValueType(VA.getValVT())); 2827 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2828 break; 2829 case CCValAssign::AExt: 2830 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2831 break; 2832 default: 2833 llvm_unreachable("Unknown loc info!"); 2834 } 2835 2836 InVals.push_back(Val); 2837 } 2838 2839 return Chain; 2840 } 2841 2842 // Add code to pass special inputs required depending on used features separate 2843 // from the explicit user arguments present in the IR. 2844 void SITargetLowering::passSpecialInputs( 2845 CallLoweringInfo &CLI, 2846 CCState &CCInfo, 2847 const SIMachineFunctionInfo &Info, 2848 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2849 SmallVectorImpl<SDValue> &MemOpChains, 2850 SDValue Chain) const { 2851 // If we don't have a call site, this was a call inserted by 2852 // legalization. These can never use special inputs. 2853 if (!CLI.CB) 2854 return; 2855 2856 SelectionDAG &DAG = CLI.DAG; 2857 const SDLoc &DL = CLI.DL; 2858 const Function &F = DAG.getMachineFunction().getFunction(); 2859 2860 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2861 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2862 2863 const AMDGPUFunctionArgInfo *CalleeArgInfo 2864 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2865 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2866 auto &ArgUsageInfo = 2867 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2868 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2869 } 2870 2871 // TODO: Unify with private memory register handling. This is complicated by 2872 // the fact that at least in kernels, the input argument is not necessarily 2873 // in the same location as the input. 2874 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2875 StringLiteral> ImplicitAttrs[] = { 2876 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2877 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2878 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2879 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2880 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2881 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2882 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2883 }; 2884 2885 for (auto Attr : ImplicitAttrs) { 2886 const ArgDescriptor *OutgoingArg; 2887 const TargetRegisterClass *ArgRC; 2888 LLT ArgTy; 2889 2890 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2891 2892 // If the callee does not use the attribute value, skip copying the value. 2893 if (CLI.CB->hasFnAttr(Attr.second)) 2894 continue; 2895 2896 std::tie(OutgoingArg, ArgRC, ArgTy) = 2897 CalleeArgInfo->getPreloadedValue(InputID); 2898 if (!OutgoingArg) 2899 continue; 2900 2901 const ArgDescriptor *IncomingArg; 2902 const TargetRegisterClass *IncomingArgRC; 2903 LLT Ty; 2904 std::tie(IncomingArg, IncomingArgRC, Ty) = 2905 CallerArgInfo.getPreloadedValue(InputID); 2906 assert(IncomingArgRC == ArgRC); 2907 2908 // All special arguments are ints for now. 2909 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2910 SDValue InputReg; 2911 2912 if (IncomingArg) { 2913 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2914 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2915 // The implicit arg ptr is special because it doesn't have a corresponding 2916 // input for kernels, and is computed from the kernarg segment pointer. 2917 InputReg = getImplicitArgPtr(DAG, DL); 2918 } else { 2919 // We may have proven the input wasn't needed, although the ABI is 2920 // requiring it. We just need to allocate the register appropriately. 2921 InputReg = DAG.getUNDEF(ArgVT); 2922 } 2923 2924 if (OutgoingArg->isRegister()) { 2925 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2926 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2927 report_fatal_error("failed to allocate implicit input argument"); 2928 } else { 2929 unsigned SpecialArgOffset = 2930 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2931 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2932 SpecialArgOffset); 2933 MemOpChains.push_back(ArgStore); 2934 } 2935 } 2936 2937 // Pack workitem IDs into a single register or pass it as is if already 2938 // packed. 2939 const ArgDescriptor *OutgoingArg; 2940 const TargetRegisterClass *ArgRC; 2941 LLT Ty; 2942 2943 std::tie(OutgoingArg, ArgRC, Ty) = 2944 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2945 if (!OutgoingArg) 2946 std::tie(OutgoingArg, ArgRC, Ty) = 2947 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2948 if (!OutgoingArg) 2949 std::tie(OutgoingArg, ArgRC, Ty) = 2950 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2951 if (!OutgoingArg) 2952 return; 2953 2954 const ArgDescriptor *IncomingArgX = std::get<0>( 2955 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2956 const ArgDescriptor *IncomingArgY = std::get<0>( 2957 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2958 const ArgDescriptor *IncomingArgZ = std::get<0>( 2959 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2960 2961 SDValue InputReg; 2962 SDLoc SL; 2963 2964 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2965 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2966 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2967 2968 // If incoming ids are not packed we need to pack them. 2969 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2970 NeedWorkItemIDX) { 2971 if (Subtarget->getMaxWorkitemID(F, 0) != 0) { 2972 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2973 } else { 2974 InputReg = DAG.getConstant(0, DL, MVT::i32); 2975 } 2976 } 2977 2978 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2979 NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) { 2980 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2981 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2982 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2983 InputReg = InputReg.getNode() ? 2984 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2985 } 2986 2987 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2988 NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) { 2989 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2990 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2991 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2992 InputReg = InputReg.getNode() ? 2993 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2994 } 2995 2996 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2997 if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) { 2998 // We're in a situation where the outgoing function requires the workitem 2999 // ID, but the calling function does not have it (e.g a graphics function 3000 // calling a C calling convention function). This is illegal, but we need 3001 // to produce something. 3002 InputReg = DAG.getUNDEF(MVT::i32); 3003 } else { 3004 // Workitem ids are already packed, any of present incoming arguments 3005 // will carry all required fields. 3006 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 3007 IncomingArgX ? *IncomingArgX : 3008 IncomingArgY ? *IncomingArgY : 3009 *IncomingArgZ, ~0u); 3010 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 3011 } 3012 } 3013 3014 if (OutgoingArg->isRegister()) { 3015 if (InputReg) 3016 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 3017 3018 CCInfo.AllocateReg(OutgoingArg->getRegister()); 3019 } else { 3020 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 3021 if (InputReg) { 3022 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 3023 SpecialArgOffset); 3024 MemOpChains.push_back(ArgStore); 3025 } 3026 } 3027 } 3028 3029 static bool canGuaranteeTCO(CallingConv::ID CC) { 3030 return CC == CallingConv::Fast; 3031 } 3032 3033 /// Return true if we might ever do TCO for calls with this calling convention. 3034 static bool mayTailCallThisCC(CallingConv::ID CC) { 3035 switch (CC) { 3036 case CallingConv::C: 3037 case CallingConv::AMDGPU_Gfx: 3038 return true; 3039 default: 3040 return canGuaranteeTCO(CC); 3041 } 3042 } 3043 3044 bool SITargetLowering::isEligibleForTailCallOptimization( 3045 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 3046 const SmallVectorImpl<ISD::OutputArg> &Outs, 3047 const SmallVectorImpl<SDValue> &OutVals, 3048 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3049 if (!mayTailCallThisCC(CalleeCC)) 3050 return false; 3051 3052 // For a divergent call target, we need to do a waterfall loop over the 3053 // possible callees which precludes us from using a simple jump. 3054 if (Callee->isDivergent()) 3055 return false; 3056 3057 MachineFunction &MF = DAG.getMachineFunction(); 3058 const Function &CallerF = MF.getFunction(); 3059 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3060 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3061 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3062 3063 // Kernels aren't callable, and don't have a live in return address so it 3064 // doesn't make sense to do a tail call with entry functions. 3065 if (!CallerPreserved) 3066 return false; 3067 3068 bool CCMatch = CallerCC == CalleeCC; 3069 3070 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 3071 if (canGuaranteeTCO(CalleeCC) && CCMatch) 3072 return true; 3073 return false; 3074 } 3075 3076 // TODO: Can we handle var args? 3077 if (IsVarArg) 3078 return false; 3079 3080 for (const Argument &Arg : CallerF.args()) { 3081 if (Arg.hasByValAttr()) 3082 return false; 3083 } 3084 3085 LLVMContext &Ctx = *DAG.getContext(); 3086 3087 // Check that the call results are passed in the same way. 3088 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 3089 CCAssignFnForCall(CalleeCC, IsVarArg), 3090 CCAssignFnForCall(CallerCC, IsVarArg))) 3091 return false; 3092 3093 // The callee has to preserve all registers the caller needs to preserve. 3094 if (!CCMatch) { 3095 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3096 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3097 return false; 3098 } 3099 3100 // Nothing more to check if the callee is taking no arguments. 3101 if (Outs.empty()) 3102 return true; 3103 3104 SmallVector<CCValAssign, 16> ArgLocs; 3105 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3106 3107 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3108 3109 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3110 // If the stack arguments for this call do not fit into our own save area then 3111 // the call cannot be made tail. 3112 // TODO: Is this really necessary? 3113 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3114 return false; 3115 3116 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3117 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3118 } 3119 3120 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3121 if (!CI->isTailCall()) 3122 return false; 3123 3124 const Function *ParentFn = CI->getParent()->getParent(); 3125 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3126 return false; 3127 return true; 3128 } 3129 3130 // The wave scratch offset register is used as the global base pointer. 3131 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3132 SmallVectorImpl<SDValue> &InVals) const { 3133 SelectionDAG &DAG = CLI.DAG; 3134 const SDLoc &DL = CLI.DL; 3135 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3136 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3137 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3138 SDValue Chain = CLI.Chain; 3139 SDValue Callee = CLI.Callee; 3140 bool &IsTailCall = CLI.IsTailCall; 3141 CallingConv::ID CallConv = CLI.CallConv; 3142 bool IsVarArg = CLI.IsVarArg; 3143 bool IsSibCall = false; 3144 bool IsThisReturn = false; 3145 MachineFunction &MF = DAG.getMachineFunction(); 3146 3147 if (Callee.isUndef() || isNullConstant(Callee)) { 3148 if (!CLI.IsTailCall) { 3149 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3150 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3151 } 3152 3153 return Chain; 3154 } 3155 3156 if (IsVarArg) { 3157 return lowerUnhandledCall(CLI, InVals, 3158 "unsupported call to variadic function "); 3159 } 3160 3161 if (!CLI.CB) 3162 report_fatal_error("unsupported libcall legalization"); 3163 3164 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3165 return lowerUnhandledCall(CLI, InVals, 3166 "unsupported required tail call to function "); 3167 } 3168 3169 if (AMDGPU::isShader(CallConv)) { 3170 // Note the issue is with the CC of the called function, not of the call 3171 // itself. 3172 return lowerUnhandledCall(CLI, InVals, 3173 "unsupported call to a shader function "); 3174 } 3175 3176 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3177 CallConv != CallingConv::AMDGPU_Gfx) { 3178 // Only allow calls with specific calling conventions. 3179 return lowerUnhandledCall(CLI, InVals, 3180 "unsupported calling convention for call from " 3181 "graphics shader of function "); 3182 } 3183 3184 if (IsTailCall) { 3185 IsTailCall = isEligibleForTailCallOptimization( 3186 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3187 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3188 report_fatal_error("failed to perform tail call elimination on a call " 3189 "site marked musttail"); 3190 } 3191 3192 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3193 3194 // A sibling call is one where we're under the usual C ABI and not planning 3195 // to change that but can still do a tail call: 3196 if (!TailCallOpt && IsTailCall) 3197 IsSibCall = true; 3198 3199 if (IsTailCall) 3200 ++NumTailCalls; 3201 } 3202 3203 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3204 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3205 SmallVector<SDValue, 8> MemOpChains; 3206 3207 // Analyze operands of the call, assigning locations to each operand. 3208 SmallVector<CCValAssign, 16> ArgLocs; 3209 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3210 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3211 3212 if (CallConv != CallingConv::AMDGPU_Gfx) { 3213 // With a fixed ABI, allocate fixed registers before user arguments. 3214 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3215 } 3216 3217 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3218 3219 // Get a count of how many bytes are to be pushed on the stack. 3220 unsigned NumBytes = CCInfo.getNextStackOffset(); 3221 3222 if (IsSibCall) { 3223 // Since we're not changing the ABI to make this a tail call, the memory 3224 // operands are already available in the caller's incoming argument space. 3225 NumBytes = 0; 3226 } 3227 3228 // FPDiff is the byte offset of the call's argument area from the callee's. 3229 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3230 // by this amount for a tail call. In a sibling call it must be 0 because the 3231 // caller will deallocate the entire stack and the callee still expects its 3232 // arguments to begin at SP+0. Completely unused for non-tail calls. 3233 int32_t FPDiff = 0; 3234 MachineFrameInfo &MFI = MF.getFrameInfo(); 3235 3236 // Adjust the stack pointer for the new arguments... 3237 // These operations are automatically eliminated by the prolog/epilog pass 3238 if (!IsSibCall) { 3239 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3240 3241 if (!Subtarget->enableFlatScratch()) { 3242 SmallVector<SDValue, 4> CopyFromChains; 3243 3244 // In the HSA case, this should be an identity copy. 3245 SDValue ScratchRSrcReg 3246 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3247 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3248 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3249 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3250 } 3251 } 3252 3253 MVT PtrVT = MVT::i32; 3254 3255 // Walk the register/memloc assignments, inserting copies/loads. 3256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3257 CCValAssign &VA = ArgLocs[i]; 3258 SDValue Arg = OutVals[i]; 3259 3260 // Promote the value if needed. 3261 switch (VA.getLocInfo()) { 3262 case CCValAssign::Full: 3263 break; 3264 case CCValAssign::BCvt: 3265 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3266 break; 3267 case CCValAssign::ZExt: 3268 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3269 break; 3270 case CCValAssign::SExt: 3271 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3272 break; 3273 case CCValAssign::AExt: 3274 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3275 break; 3276 case CCValAssign::FPExt: 3277 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3278 break; 3279 default: 3280 llvm_unreachable("Unknown loc info!"); 3281 } 3282 3283 if (VA.isRegLoc()) { 3284 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3285 } else { 3286 assert(VA.isMemLoc()); 3287 3288 SDValue DstAddr; 3289 MachinePointerInfo DstInfo; 3290 3291 unsigned LocMemOffset = VA.getLocMemOffset(); 3292 int32_t Offset = LocMemOffset; 3293 3294 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3295 MaybeAlign Alignment; 3296 3297 if (IsTailCall) { 3298 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3299 unsigned OpSize = Flags.isByVal() ? 3300 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3301 3302 // FIXME: We can have better than the minimum byval required alignment. 3303 Alignment = 3304 Flags.isByVal() 3305 ? Flags.getNonZeroByValAlign() 3306 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3307 3308 Offset = Offset + FPDiff; 3309 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3310 3311 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3312 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3313 3314 // Make sure any stack arguments overlapping with where we're storing 3315 // are loaded before this eventual operation. Otherwise they'll be 3316 // clobbered. 3317 3318 // FIXME: Why is this really necessary? This seems to just result in a 3319 // lot of code to copy the stack and write them back to the same 3320 // locations, which are supposed to be immutable? 3321 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3322 } else { 3323 // Stores to the argument stack area are relative to the stack pointer. 3324 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3325 MVT::i32); 3326 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3327 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3328 Alignment = 3329 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3330 } 3331 3332 if (Outs[i].Flags.isByVal()) { 3333 SDValue SizeNode = 3334 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3335 SDValue Cpy = 3336 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3337 Outs[i].Flags.getNonZeroByValAlign(), 3338 /*isVol = */ false, /*AlwaysInline = */ true, 3339 /*isTailCall = */ false, DstInfo, 3340 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3341 3342 MemOpChains.push_back(Cpy); 3343 } else { 3344 SDValue Store = 3345 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3346 MemOpChains.push_back(Store); 3347 } 3348 } 3349 } 3350 3351 if (!MemOpChains.empty()) 3352 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3353 3354 // Build a sequence of copy-to-reg nodes chained together with token chain 3355 // and flag operands which copy the outgoing args into the appropriate regs. 3356 SDValue InFlag; 3357 for (auto &RegToPass : RegsToPass) { 3358 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3359 RegToPass.second, InFlag); 3360 InFlag = Chain.getValue(1); 3361 } 3362 3363 3364 // We don't usually want to end the call-sequence here because we would tidy 3365 // the frame up *after* the call, however in the ABI-changing tail-call case 3366 // we've carefully laid out the parameters so that when sp is reset they'll be 3367 // in the correct location. 3368 if (IsTailCall && !IsSibCall) { 3369 Chain = DAG.getCALLSEQ_END(Chain, 3370 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3371 DAG.getTargetConstant(0, DL, MVT::i32), 3372 InFlag, DL); 3373 InFlag = Chain.getValue(1); 3374 } 3375 3376 std::vector<SDValue> Ops; 3377 Ops.push_back(Chain); 3378 Ops.push_back(Callee); 3379 // Add a redundant copy of the callee global which will not be legalized, as 3380 // we need direct access to the callee later. 3381 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3382 const GlobalValue *GV = GSD->getGlobal(); 3383 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3384 } else { 3385 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3386 } 3387 3388 if (IsTailCall) { 3389 // Each tail call may have to adjust the stack by a different amount, so 3390 // this information must travel along with the operation for eventual 3391 // consumption by emitEpilogue. 3392 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3393 } 3394 3395 // Add argument registers to the end of the list so that they are known live 3396 // into the call. 3397 for (auto &RegToPass : RegsToPass) { 3398 Ops.push_back(DAG.getRegister(RegToPass.first, 3399 RegToPass.second.getValueType())); 3400 } 3401 3402 // Add a register mask operand representing the call-preserved registers. 3403 3404 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3405 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3406 assert(Mask && "Missing call preserved mask for calling convention"); 3407 Ops.push_back(DAG.getRegisterMask(Mask)); 3408 3409 if (InFlag.getNode()) 3410 Ops.push_back(InFlag); 3411 3412 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3413 3414 // If we're doing a tall call, use a TC_RETURN here rather than an 3415 // actual call instruction. 3416 if (IsTailCall) { 3417 MFI.setHasTailCall(); 3418 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3419 } 3420 3421 // Returns a chain and a flag for retval copy to use. 3422 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3423 Chain = Call.getValue(0); 3424 InFlag = Call.getValue(1); 3425 3426 uint64_t CalleePopBytes = NumBytes; 3427 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3428 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3429 InFlag, DL); 3430 if (!Ins.empty()) 3431 InFlag = Chain.getValue(1); 3432 3433 // Handle result values, copying them out of physregs into vregs that we 3434 // return. 3435 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3436 InVals, IsThisReturn, 3437 IsThisReturn ? OutVals[0] : SDValue()); 3438 } 3439 3440 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3441 // except for applying the wave size scale to the increment amount. 3442 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3443 SDValue Op, SelectionDAG &DAG) const { 3444 const MachineFunction &MF = DAG.getMachineFunction(); 3445 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3446 3447 SDLoc dl(Op); 3448 EVT VT = Op.getValueType(); 3449 SDValue Tmp1 = Op; 3450 SDValue Tmp2 = Op.getValue(1); 3451 SDValue Tmp3 = Op.getOperand(2); 3452 SDValue Chain = Tmp1.getOperand(0); 3453 3454 Register SPReg = Info->getStackPtrOffsetReg(); 3455 3456 // Chain the dynamic stack allocation so that it doesn't modify the stack 3457 // pointer when other instructions are using the stack. 3458 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3459 3460 SDValue Size = Tmp2.getOperand(1); 3461 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3462 Chain = SP.getValue(1); 3463 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3464 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3465 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3466 unsigned Opc = 3467 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3468 ISD::ADD : ISD::SUB; 3469 3470 SDValue ScaledSize = DAG.getNode( 3471 ISD::SHL, dl, VT, Size, 3472 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3473 3474 Align StackAlign = TFL->getStackAlign(); 3475 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3476 if (Alignment && *Alignment > StackAlign) { 3477 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3478 DAG.getConstant(-(uint64_t)Alignment->value() 3479 << ST.getWavefrontSizeLog2(), 3480 dl, VT)); 3481 } 3482 3483 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3484 Tmp2 = DAG.getCALLSEQ_END( 3485 Chain, DAG.getIntPtrConstant(0, dl, true), 3486 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3487 3488 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3489 } 3490 3491 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3492 SelectionDAG &DAG) const { 3493 // We only handle constant sizes here to allow non-entry block, static sized 3494 // allocas. A truly dynamic value is more difficult to support because we 3495 // don't know if the size value is uniform or not. If the size isn't uniform, 3496 // we would need to do a wave reduction to get the maximum size to know how 3497 // much to increment the uniform stack pointer. 3498 SDValue Size = Op.getOperand(1); 3499 if (isa<ConstantSDNode>(Size)) 3500 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3501 3502 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3503 } 3504 3505 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3506 const MachineFunction &MF) const { 3507 Register Reg = StringSwitch<Register>(RegName) 3508 .Case("m0", AMDGPU::M0) 3509 .Case("exec", AMDGPU::EXEC) 3510 .Case("exec_lo", AMDGPU::EXEC_LO) 3511 .Case("exec_hi", AMDGPU::EXEC_HI) 3512 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3513 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3514 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3515 .Default(Register()); 3516 3517 if (Reg == AMDGPU::NoRegister) { 3518 report_fatal_error(Twine("invalid register name \"" 3519 + StringRef(RegName) + "\".")); 3520 3521 } 3522 3523 if (!Subtarget->hasFlatScrRegister() && 3524 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3525 report_fatal_error(Twine("invalid register \"" 3526 + StringRef(RegName) + "\" for subtarget.")); 3527 } 3528 3529 switch (Reg) { 3530 case AMDGPU::M0: 3531 case AMDGPU::EXEC_LO: 3532 case AMDGPU::EXEC_HI: 3533 case AMDGPU::FLAT_SCR_LO: 3534 case AMDGPU::FLAT_SCR_HI: 3535 if (VT.getSizeInBits() == 32) 3536 return Reg; 3537 break; 3538 case AMDGPU::EXEC: 3539 case AMDGPU::FLAT_SCR: 3540 if (VT.getSizeInBits() == 64) 3541 return Reg; 3542 break; 3543 default: 3544 llvm_unreachable("missing register type checking"); 3545 } 3546 3547 report_fatal_error(Twine("invalid type for register \"" 3548 + StringRef(RegName) + "\".")); 3549 } 3550 3551 // If kill is not the last instruction, split the block so kill is always a 3552 // proper terminator. 3553 MachineBasicBlock * 3554 SITargetLowering::splitKillBlock(MachineInstr &MI, 3555 MachineBasicBlock *BB) const { 3556 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3557 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3558 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3559 return SplitBB; 3560 } 3561 3562 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3563 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3564 // be the first instruction in the remainder block. 3565 // 3566 /// \returns { LoopBody, Remainder } 3567 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3568 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3569 MachineFunction *MF = MBB.getParent(); 3570 MachineBasicBlock::iterator I(&MI); 3571 3572 // To insert the loop we need to split the block. Move everything after this 3573 // point to a new block, and insert a new empty block between the two. 3574 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3575 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3576 MachineFunction::iterator MBBI(MBB); 3577 ++MBBI; 3578 3579 MF->insert(MBBI, LoopBB); 3580 MF->insert(MBBI, RemainderBB); 3581 3582 LoopBB->addSuccessor(LoopBB); 3583 LoopBB->addSuccessor(RemainderBB); 3584 3585 // Move the rest of the block into a new block. 3586 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3587 3588 if (InstInLoop) { 3589 auto Next = std::next(I); 3590 3591 // Move instruction to loop body. 3592 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3593 3594 // Move the rest of the block. 3595 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3596 } else { 3597 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3598 } 3599 3600 MBB.addSuccessor(LoopBB); 3601 3602 return std::make_pair(LoopBB, RemainderBB); 3603 } 3604 3605 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3606 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3607 MachineBasicBlock *MBB = MI.getParent(); 3608 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3609 auto I = MI.getIterator(); 3610 auto E = std::next(I); 3611 3612 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3613 .addImm(0); 3614 3615 MIBundleBuilder Bundler(*MBB, I, E); 3616 finalizeBundle(*MBB, Bundler.begin()); 3617 } 3618 3619 MachineBasicBlock * 3620 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3621 MachineBasicBlock *BB) const { 3622 const DebugLoc &DL = MI.getDebugLoc(); 3623 3624 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3625 3626 MachineBasicBlock *LoopBB; 3627 MachineBasicBlock *RemainderBB; 3628 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3629 3630 // Apparently kill flags are only valid if the def is in the same block? 3631 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3632 Src->setIsKill(false); 3633 3634 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3635 3636 MachineBasicBlock::iterator I = LoopBB->end(); 3637 3638 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3639 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3640 3641 // Clear TRAP_STS.MEM_VIOL 3642 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3643 .addImm(0) 3644 .addImm(EncodedReg); 3645 3646 bundleInstWithWaitcnt(MI); 3647 3648 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3649 3650 // Load and check TRAP_STS.MEM_VIOL 3651 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3652 .addImm(EncodedReg); 3653 3654 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3655 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3656 .addReg(Reg, RegState::Kill) 3657 .addImm(0); 3658 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3659 .addMBB(LoopBB); 3660 3661 return RemainderBB; 3662 } 3663 3664 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3665 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3666 // will only do one iteration. In the worst case, this will loop 64 times. 3667 // 3668 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3669 static MachineBasicBlock::iterator 3670 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3671 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3672 const DebugLoc &DL, const MachineOperand &Idx, 3673 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3674 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3675 Register &SGPRIdxReg) { 3676 3677 MachineFunction *MF = OrigBB.getParent(); 3678 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3679 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3680 MachineBasicBlock::iterator I = LoopBB.begin(); 3681 3682 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3683 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3684 Register NewExec = MRI.createVirtualRegister(BoolRC); 3685 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3686 Register CondReg = MRI.createVirtualRegister(BoolRC); 3687 3688 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3689 .addReg(InitReg) 3690 .addMBB(&OrigBB) 3691 .addReg(ResultReg) 3692 .addMBB(&LoopBB); 3693 3694 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3695 .addReg(InitSaveExecReg) 3696 .addMBB(&OrigBB) 3697 .addReg(NewExec) 3698 .addMBB(&LoopBB); 3699 3700 // Read the next variant <- also loop target. 3701 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3702 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3703 3704 // Compare the just read M0 value to all possible Idx values. 3705 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3706 .addReg(CurrentIdxReg) 3707 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3708 3709 // Update EXEC, save the original EXEC value to VCC. 3710 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3711 : AMDGPU::S_AND_SAVEEXEC_B64), 3712 NewExec) 3713 .addReg(CondReg, RegState::Kill); 3714 3715 MRI.setSimpleHint(NewExec, CondReg); 3716 3717 if (UseGPRIdxMode) { 3718 if (Offset == 0) { 3719 SGPRIdxReg = CurrentIdxReg; 3720 } else { 3721 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3722 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3723 .addReg(CurrentIdxReg, RegState::Kill) 3724 .addImm(Offset); 3725 } 3726 } else { 3727 // Move index from VCC into M0 3728 if (Offset == 0) { 3729 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3730 .addReg(CurrentIdxReg, RegState::Kill); 3731 } else { 3732 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3733 .addReg(CurrentIdxReg, RegState::Kill) 3734 .addImm(Offset); 3735 } 3736 } 3737 3738 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3739 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3740 MachineInstr *InsertPt = 3741 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3742 : AMDGPU::S_XOR_B64_term), Exec) 3743 .addReg(Exec) 3744 .addReg(NewExec); 3745 3746 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3747 // s_cbranch_scc0? 3748 3749 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3750 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3751 .addMBB(&LoopBB); 3752 3753 return InsertPt->getIterator(); 3754 } 3755 3756 // This has slightly sub-optimal regalloc when the source vector is killed by 3757 // the read. The register allocator does not understand that the kill is 3758 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3759 // subregister from it, using 1 more VGPR than necessary. This was saved when 3760 // this was expanded after register allocation. 3761 static MachineBasicBlock::iterator 3762 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3763 unsigned InitResultReg, unsigned PhiReg, int Offset, 3764 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3765 MachineFunction *MF = MBB.getParent(); 3766 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3767 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3768 MachineRegisterInfo &MRI = MF->getRegInfo(); 3769 const DebugLoc &DL = MI.getDebugLoc(); 3770 MachineBasicBlock::iterator I(&MI); 3771 3772 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3773 Register DstReg = MI.getOperand(0).getReg(); 3774 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3775 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3776 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3777 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3778 3779 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3780 3781 // Save the EXEC mask 3782 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3783 .addReg(Exec); 3784 3785 MachineBasicBlock *LoopBB; 3786 MachineBasicBlock *RemainderBB; 3787 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3788 3789 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3790 3791 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3792 InitResultReg, DstReg, PhiReg, TmpExec, 3793 Offset, UseGPRIdxMode, SGPRIdxReg); 3794 3795 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3796 MachineFunction::iterator MBBI(LoopBB); 3797 ++MBBI; 3798 MF->insert(MBBI, LandingPad); 3799 LoopBB->removeSuccessor(RemainderBB); 3800 LandingPad->addSuccessor(RemainderBB); 3801 LoopBB->addSuccessor(LandingPad); 3802 MachineBasicBlock::iterator First = LandingPad->begin(); 3803 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3804 .addReg(SaveExec); 3805 3806 return InsPt; 3807 } 3808 3809 // Returns subreg index, offset 3810 static std::pair<unsigned, int> 3811 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3812 const TargetRegisterClass *SuperRC, 3813 unsigned VecReg, 3814 int Offset) { 3815 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3816 3817 // Skip out of bounds offsets, or else we would end up using an undefined 3818 // register. 3819 if (Offset >= NumElts || Offset < 0) 3820 return std::make_pair(AMDGPU::sub0, Offset); 3821 3822 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3823 } 3824 3825 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3826 MachineRegisterInfo &MRI, MachineInstr &MI, 3827 int Offset) { 3828 MachineBasicBlock *MBB = MI.getParent(); 3829 const DebugLoc &DL = MI.getDebugLoc(); 3830 MachineBasicBlock::iterator I(&MI); 3831 3832 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3833 3834 assert(Idx->getReg() != AMDGPU::NoRegister); 3835 3836 if (Offset == 0) { 3837 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3838 } else { 3839 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3840 .add(*Idx) 3841 .addImm(Offset); 3842 } 3843 } 3844 3845 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3846 MachineRegisterInfo &MRI, MachineInstr &MI, 3847 int Offset) { 3848 MachineBasicBlock *MBB = MI.getParent(); 3849 const DebugLoc &DL = MI.getDebugLoc(); 3850 MachineBasicBlock::iterator I(&MI); 3851 3852 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3853 3854 if (Offset == 0) 3855 return Idx->getReg(); 3856 3857 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3858 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3859 .add(*Idx) 3860 .addImm(Offset); 3861 return Tmp; 3862 } 3863 3864 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3865 MachineBasicBlock &MBB, 3866 const GCNSubtarget &ST) { 3867 const SIInstrInfo *TII = ST.getInstrInfo(); 3868 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3869 MachineFunction *MF = MBB.getParent(); 3870 MachineRegisterInfo &MRI = MF->getRegInfo(); 3871 3872 Register Dst = MI.getOperand(0).getReg(); 3873 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3874 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3875 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3876 3877 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3878 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3879 3880 unsigned SubReg; 3881 std::tie(SubReg, Offset) 3882 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3883 3884 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3885 3886 // Check for a SGPR index. 3887 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3888 MachineBasicBlock::iterator I(&MI); 3889 const DebugLoc &DL = MI.getDebugLoc(); 3890 3891 if (UseGPRIdxMode) { 3892 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3893 // to avoid interfering with other uses, so probably requires a new 3894 // optimization pass. 3895 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3896 3897 const MCInstrDesc &GPRIDXDesc = 3898 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3899 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3900 .addReg(SrcReg) 3901 .addReg(Idx) 3902 .addImm(SubReg); 3903 } else { 3904 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3905 3906 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3907 .addReg(SrcReg, 0, SubReg) 3908 .addReg(SrcReg, RegState::Implicit); 3909 } 3910 3911 MI.eraseFromParent(); 3912 3913 return &MBB; 3914 } 3915 3916 // Control flow needs to be inserted if indexing with a VGPR. 3917 const DebugLoc &DL = MI.getDebugLoc(); 3918 MachineBasicBlock::iterator I(&MI); 3919 3920 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3921 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3922 3923 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3924 3925 Register SGPRIdxReg; 3926 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3927 UseGPRIdxMode, SGPRIdxReg); 3928 3929 MachineBasicBlock *LoopBB = InsPt->getParent(); 3930 3931 if (UseGPRIdxMode) { 3932 const MCInstrDesc &GPRIDXDesc = 3933 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3934 3935 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3936 .addReg(SrcReg) 3937 .addReg(SGPRIdxReg) 3938 .addImm(SubReg); 3939 } else { 3940 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3941 .addReg(SrcReg, 0, SubReg) 3942 .addReg(SrcReg, RegState::Implicit); 3943 } 3944 3945 MI.eraseFromParent(); 3946 3947 return LoopBB; 3948 } 3949 3950 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3951 MachineBasicBlock &MBB, 3952 const GCNSubtarget &ST) { 3953 const SIInstrInfo *TII = ST.getInstrInfo(); 3954 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3955 MachineFunction *MF = MBB.getParent(); 3956 MachineRegisterInfo &MRI = MF->getRegInfo(); 3957 3958 Register Dst = MI.getOperand(0).getReg(); 3959 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3960 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3961 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3962 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3963 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3964 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3965 3966 // This can be an immediate, but will be folded later. 3967 assert(Val->getReg()); 3968 3969 unsigned SubReg; 3970 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3971 SrcVec->getReg(), 3972 Offset); 3973 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3974 3975 if (Idx->getReg() == AMDGPU::NoRegister) { 3976 MachineBasicBlock::iterator I(&MI); 3977 const DebugLoc &DL = MI.getDebugLoc(); 3978 3979 assert(Offset == 0); 3980 3981 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3982 .add(*SrcVec) 3983 .add(*Val) 3984 .addImm(SubReg); 3985 3986 MI.eraseFromParent(); 3987 return &MBB; 3988 } 3989 3990 // Check for a SGPR index. 3991 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3992 MachineBasicBlock::iterator I(&MI); 3993 const DebugLoc &DL = MI.getDebugLoc(); 3994 3995 if (UseGPRIdxMode) { 3996 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3997 3998 const MCInstrDesc &GPRIDXDesc = 3999 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4000 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 4001 .addReg(SrcVec->getReg()) 4002 .add(*Val) 4003 .addReg(Idx) 4004 .addImm(SubReg); 4005 } else { 4006 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 4007 4008 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4009 TRI.getRegSizeInBits(*VecRC), 32, false); 4010 BuildMI(MBB, I, DL, MovRelDesc, Dst) 4011 .addReg(SrcVec->getReg()) 4012 .add(*Val) 4013 .addImm(SubReg); 4014 } 4015 MI.eraseFromParent(); 4016 return &MBB; 4017 } 4018 4019 // Control flow needs to be inserted if indexing with a VGPR. 4020 if (Val->isReg()) 4021 MRI.clearKillFlags(Val->getReg()); 4022 4023 const DebugLoc &DL = MI.getDebugLoc(); 4024 4025 Register PhiReg = MRI.createVirtualRegister(VecRC); 4026 4027 Register SGPRIdxReg; 4028 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 4029 UseGPRIdxMode, SGPRIdxReg); 4030 MachineBasicBlock *LoopBB = InsPt->getParent(); 4031 4032 if (UseGPRIdxMode) { 4033 const MCInstrDesc &GPRIDXDesc = 4034 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 4035 4036 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 4037 .addReg(PhiReg) 4038 .add(*Val) 4039 .addReg(SGPRIdxReg) 4040 .addImm(AMDGPU::sub0); 4041 } else { 4042 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 4043 TRI.getRegSizeInBits(*VecRC), 32, false); 4044 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 4045 .addReg(PhiReg) 4046 .add(*Val) 4047 .addImm(AMDGPU::sub0); 4048 } 4049 4050 MI.eraseFromParent(); 4051 return LoopBB; 4052 } 4053 4054 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 4055 MachineInstr &MI, MachineBasicBlock *BB) const { 4056 4057 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4058 MachineFunction *MF = BB->getParent(); 4059 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 4060 4061 switch (MI.getOpcode()) { 4062 case AMDGPU::S_UADDO_PSEUDO: 4063 case AMDGPU::S_USUBO_PSEUDO: { 4064 const DebugLoc &DL = MI.getDebugLoc(); 4065 MachineOperand &Dest0 = MI.getOperand(0); 4066 MachineOperand &Dest1 = MI.getOperand(1); 4067 MachineOperand &Src0 = MI.getOperand(2); 4068 MachineOperand &Src1 = MI.getOperand(3); 4069 4070 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 4071 ? AMDGPU::S_ADD_I32 4072 : AMDGPU::S_SUB_I32; 4073 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 4074 4075 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 4076 .addImm(1) 4077 .addImm(0); 4078 4079 MI.eraseFromParent(); 4080 return BB; 4081 } 4082 case AMDGPU::S_ADD_U64_PSEUDO: 4083 case AMDGPU::S_SUB_U64_PSEUDO: { 4084 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4085 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4086 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4087 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4088 const DebugLoc &DL = MI.getDebugLoc(); 4089 4090 MachineOperand &Dest = MI.getOperand(0); 4091 MachineOperand &Src0 = MI.getOperand(1); 4092 MachineOperand &Src1 = MI.getOperand(2); 4093 4094 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4095 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4096 4097 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4098 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4099 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4100 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4101 4102 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4103 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4104 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4105 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4106 4107 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4108 4109 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4110 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4111 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4112 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4113 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4114 .addReg(DestSub0) 4115 .addImm(AMDGPU::sub0) 4116 .addReg(DestSub1) 4117 .addImm(AMDGPU::sub1); 4118 MI.eraseFromParent(); 4119 return BB; 4120 } 4121 case AMDGPU::V_ADD_U64_PSEUDO: 4122 case AMDGPU::V_SUB_U64_PSEUDO: { 4123 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4124 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4125 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4126 const DebugLoc &DL = MI.getDebugLoc(); 4127 4128 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4129 4130 MachineOperand &Dest = MI.getOperand(0); 4131 MachineOperand &Src0 = MI.getOperand(1); 4132 MachineOperand &Src1 = MI.getOperand(2); 4133 4134 if (IsAdd && ST.hasLshlAddB64()) { 4135 auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64), 4136 Dest.getReg()) 4137 .add(Src0) 4138 .addImm(0) 4139 .add(Src1); 4140 TII->legalizeOperands(*Add); 4141 MI.eraseFromParent(); 4142 return BB; 4143 } 4144 4145 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4146 4147 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4148 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4149 4150 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4151 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4152 4153 const TargetRegisterClass *Src0RC = Src0.isReg() 4154 ? MRI.getRegClass(Src0.getReg()) 4155 : &AMDGPU::VReg_64RegClass; 4156 const TargetRegisterClass *Src1RC = Src1.isReg() 4157 ? MRI.getRegClass(Src1.getReg()) 4158 : &AMDGPU::VReg_64RegClass; 4159 4160 const TargetRegisterClass *Src0SubRC = 4161 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4162 const TargetRegisterClass *Src1SubRC = 4163 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4164 4165 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4166 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4167 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4168 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4169 4170 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4171 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4172 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4173 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4174 4175 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4176 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4177 .addReg(CarryReg, RegState::Define) 4178 .add(SrcReg0Sub0) 4179 .add(SrcReg1Sub0) 4180 .addImm(0); // clamp bit 4181 4182 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4183 MachineInstr *HiHalf = 4184 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4185 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4186 .add(SrcReg0Sub1) 4187 .add(SrcReg1Sub1) 4188 .addReg(CarryReg, RegState::Kill) 4189 .addImm(0); // clamp bit 4190 4191 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4192 .addReg(DestSub0) 4193 .addImm(AMDGPU::sub0) 4194 .addReg(DestSub1) 4195 .addImm(AMDGPU::sub1); 4196 TII->legalizeOperands(*LoHalf); 4197 TII->legalizeOperands(*HiHalf); 4198 MI.eraseFromParent(); 4199 return BB; 4200 } 4201 case AMDGPU::S_ADD_CO_PSEUDO: 4202 case AMDGPU::S_SUB_CO_PSEUDO: { 4203 // This pseudo has a chance to be selected 4204 // only from uniform add/subcarry node. All the VGPR operands 4205 // therefore assumed to be splat vectors. 4206 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4207 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4208 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4209 MachineBasicBlock::iterator MII = MI; 4210 const DebugLoc &DL = MI.getDebugLoc(); 4211 MachineOperand &Dest = MI.getOperand(0); 4212 MachineOperand &CarryDest = MI.getOperand(1); 4213 MachineOperand &Src0 = MI.getOperand(2); 4214 MachineOperand &Src1 = MI.getOperand(3); 4215 MachineOperand &Src2 = MI.getOperand(4); 4216 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4217 ? AMDGPU::S_ADDC_U32 4218 : AMDGPU::S_SUBB_U32; 4219 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4220 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4221 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4222 .addReg(Src0.getReg()); 4223 Src0.setReg(RegOp0); 4224 } 4225 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4226 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4227 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4228 .addReg(Src1.getReg()); 4229 Src1.setReg(RegOp1); 4230 } 4231 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4232 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4233 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4234 .addReg(Src2.getReg()); 4235 Src2.setReg(RegOp2); 4236 } 4237 4238 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4239 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4240 assert(WaveSize == 64 || WaveSize == 32); 4241 4242 if (WaveSize == 64) { 4243 if (ST.hasScalarCompareEq64()) { 4244 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4245 .addReg(Src2.getReg()) 4246 .addImm(0); 4247 } else { 4248 const TargetRegisterClass *SubRC = 4249 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4250 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4251 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4252 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4253 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4254 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4255 4256 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4257 .add(Src2Sub0) 4258 .add(Src2Sub1); 4259 4260 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4261 .addReg(Src2_32, RegState::Kill) 4262 .addImm(0); 4263 } 4264 } else { 4265 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4266 .addReg(Src2.getReg()) 4267 .addImm(0); 4268 } 4269 4270 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4271 4272 unsigned SelOpc = 4273 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4274 4275 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4276 .addImm(-1) 4277 .addImm(0); 4278 4279 MI.eraseFromParent(); 4280 return BB; 4281 } 4282 case AMDGPU::SI_INIT_M0: { 4283 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4284 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4285 .add(MI.getOperand(0)); 4286 MI.eraseFromParent(); 4287 return BB; 4288 } 4289 case AMDGPU::GET_GROUPSTATICSIZE: { 4290 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4291 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4292 DebugLoc DL = MI.getDebugLoc(); 4293 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4294 .add(MI.getOperand(0)) 4295 .addImm(MFI->getLDSSize()); 4296 MI.eraseFromParent(); 4297 return BB; 4298 } 4299 case AMDGPU::SI_INDIRECT_SRC_V1: 4300 case AMDGPU::SI_INDIRECT_SRC_V2: 4301 case AMDGPU::SI_INDIRECT_SRC_V4: 4302 case AMDGPU::SI_INDIRECT_SRC_V8: 4303 case AMDGPU::SI_INDIRECT_SRC_V16: 4304 case AMDGPU::SI_INDIRECT_SRC_V32: 4305 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4306 case AMDGPU::SI_INDIRECT_DST_V1: 4307 case AMDGPU::SI_INDIRECT_DST_V2: 4308 case AMDGPU::SI_INDIRECT_DST_V4: 4309 case AMDGPU::SI_INDIRECT_DST_V8: 4310 case AMDGPU::SI_INDIRECT_DST_V16: 4311 case AMDGPU::SI_INDIRECT_DST_V32: 4312 return emitIndirectDst(MI, *BB, *getSubtarget()); 4313 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4314 case AMDGPU::SI_KILL_I1_PSEUDO: 4315 return splitKillBlock(MI, BB); 4316 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4317 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4318 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4319 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4320 4321 Register Dst = MI.getOperand(0).getReg(); 4322 Register Src0 = MI.getOperand(1).getReg(); 4323 Register Src1 = MI.getOperand(2).getReg(); 4324 const DebugLoc &DL = MI.getDebugLoc(); 4325 Register SrcCond = MI.getOperand(3).getReg(); 4326 4327 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4328 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4329 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4330 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4331 4332 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4333 .addReg(SrcCond); 4334 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4335 .addImm(0) 4336 .addReg(Src0, 0, AMDGPU::sub0) 4337 .addImm(0) 4338 .addReg(Src1, 0, AMDGPU::sub0) 4339 .addReg(SrcCondCopy); 4340 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4341 .addImm(0) 4342 .addReg(Src0, 0, AMDGPU::sub1) 4343 .addImm(0) 4344 .addReg(Src1, 0, AMDGPU::sub1) 4345 .addReg(SrcCondCopy); 4346 4347 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4348 .addReg(DstLo) 4349 .addImm(AMDGPU::sub0) 4350 .addReg(DstHi) 4351 .addImm(AMDGPU::sub1); 4352 MI.eraseFromParent(); 4353 return BB; 4354 } 4355 case AMDGPU::SI_BR_UNDEF: { 4356 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4357 const DebugLoc &DL = MI.getDebugLoc(); 4358 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4359 .add(MI.getOperand(0)); 4360 Br->getOperand(1).setIsUndef(true); // read undef SCC 4361 MI.eraseFromParent(); 4362 return BB; 4363 } 4364 case AMDGPU::ADJCALLSTACKUP: 4365 case AMDGPU::ADJCALLSTACKDOWN: { 4366 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4367 MachineInstrBuilder MIB(*MF, &MI); 4368 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4369 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4370 return BB; 4371 } 4372 case AMDGPU::SI_CALL_ISEL: { 4373 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4374 const DebugLoc &DL = MI.getDebugLoc(); 4375 4376 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4377 4378 MachineInstrBuilder MIB; 4379 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4380 4381 for (const MachineOperand &MO : MI.operands()) 4382 MIB.add(MO); 4383 4384 MIB.cloneMemRefs(MI); 4385 MI.eraseFromParent(); 4386 return BB; 4387 } 4388 case AMDGPU::V_ADD_CO_U32_e32: 4389 case AMDGPU::V_SUB_CO_U32_e32: 4390 case AMDGPU::V_SUBREV_CO_U32_e32: { 4391 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4392 const DebugLoc &DL = MI.getDebugLoc(); 4393 unsigned Opc = MI.getOpcode(); 4394 4395 bool NeedClampOperand = false; 4396 if (TII->pseudoToMCOpcode(Opc) == -1) { 4397 Opc = AMDGPU::getVOPe64(Opc); 4398 NeedClampOperand = true; 4399 } 4400 4401 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4402 if (TII->isVOP3(*I)) { 4403 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4404 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4405 I.addReg(TRI->getVCC(), RegState::Define); 4406 } 4407 I.add(MI.getOperand(1)) 4408 .add(MI.getOperand(2)); 4409 if (NeedClampOperand) 4410 I.addImm(0); // clamp bit for e64 encoding 4411 4412 TII->legalizeOperands(*I); 4413 4414 MI.eraseFromParent(); 4415 return BB; 4416 } 4417 case AMDGPU::V_ADDC_U32_e32: 4418 case AMDGPU::V_SUBB_U32_e32: 4419 case AMDGPU::V_SUBBREV_U32_e32: 4420 // These instructions have an implicit use of vcc which counts towards the 4421 // constant bus limit. 4422 TII->legalizeOperands(MI); 4423 return BB; 4424 case AMDGPU::DS_GWS_INIT: 4425 case AMDGPU::DS_GWS_SEMA_BR: 4426 case AMDGPU::DS_GWS_BARRIER: 4427 if (Subtarget->needsAlignedVGPRs()) { 4428 // Add implicit aligned super-reg to force alignment on the data operand. 4429 const DebugLoc &DL = MI.getDebugLoc(); 4430 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4431 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4432 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4433 Register DataReg = Op->getReg(); 4434 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4435 Register Undef = MRI.createVirtualRegister( 4436 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4437 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4438 Register NewVR = 4439 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4440 : &AMDGPU::VReg_64_Align2RegClass); 4441 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4442 .addReg(DataReg, 0, Op->getSubReg()) 4443 .addImm(AMDGPU::sub0) 4444 .addReg(Undef) 4445 .addImm(AMDGPU::sub1); 4446 Op->setReg(NewVR); 4447 Op->setSubReg(AMDGPU::sub0); 4448 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4449 } 4450 LLVM_FALLTHROUGH; 4451 case AMDGPU::DS_GWS_SEMA_V: 4452 case AMDGPU::DS_GWS_SEMA_P: 4453 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4454 // A s_waitcnt 0 is required to be the instruction immediately following. 4455 if (getSubtarget()->hasGWSAutoReplay()) { 4456 bundleInstWithWaitcnt(MI); 4457 return BB; 4458 } 4459 4460 return emitGWSMemViolTestLoop(MI, BB); 4461 case AMDGPU::S_SETREG_B32: { 4462 // Try to optimize cases that only set the denormal mode or rounding mode. 4463 // 4464 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4465 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4466 // instead. 4467 // 4468 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4469 // allow you to have a no side effect instruction in the output of a 4470 // sideeffecting pattern. 4471 unsigned ID, Offset, Width; 4472 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4473 if (ID != AMDGPU::Hwreg::ID_MODE) 4474 return BB; 4475 4476 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4477 const unsigned SetMask = WidthMask << Offset; 4478 4479 if (getSubtarget()->hasDenormModeInst()) { 4480 unsigned SetDenormOp = 0; 4481 unsigned SetRoundOp = 0; 4482 4483 // The dedicated instructions can only set the whole denorm or round mode 4484 // at once, not a subset of bits in either. 4485 if (SetMask == 4486 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4487 // If this fully sets both the round and denorm mode, emit the two 4488 // dedicated instructions for these. 4489 SetRoundOp = AMDGPU::S_ROUND_MODE; 4490 SetDenormOp = AMDGPU::S_DENORM_MODE; 4491 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4492 SetRoundOp = AMDGPU::S_ROUND_MODE; 4493 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4494 SetDenormOp = AMDGPU::S_DENORM_MODE; 4495 } 4496 4497 if (SetRoundOp || SetDenormOp) { 4498 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4499 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4500 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4501 unsigned ImmVal = Def->getOperand(1).getImm(); 4502 if (SetRoundOp) { 4503 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4504 .addImm(ImmVal & 0xf); 4505 4506 // If we also have the denorm mode, get just the denorm mode bits. 4507 ImmVal >>= 4; 4508 } 4509 4510 if (SetDenormOp) { 4511 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4512 .addImm(ImmVal & 0xf); 4513 } 4514 4515 MI.eraseFromParent(); 4516 return BB; 4517 } 4518 } 4519 } 4520 4521 // If only FP bits are touched, used the no side effects pseudo. 4522 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4523 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4524 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4525 4526 return BB; 4527 } 4528 default: 4529 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4530 } 4531 } 4532 4533 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4534 return isTypeLegal(VT.getScalarType()); 4535 } 4536 4537 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4538 // This currently forces unfolding various combinations of fsub into fma with 4539 // free fneg'd operands. As long as we have fast FMA (controlled by 4540 // isFMAFasterThanFMulAndFAdd), we should perform these. 4541 4542 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4543 // most of these combines appear to be cycle neutral but save on instruction 4544 // count / code size. 4545 return true; 4546 } 4547 4548 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4549 4550 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4551 EVT VT) const { 4552 if (!VT.isVector()) { 4553 return MVT::i1; 4554 } 4555 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4556 } 4557 4558 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4559 // TODO: Should i16 be used always if legal? For now it would force VALU 4560 // shifts. 4561 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4562 } 4563 4564 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4565 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4566 ? Ty.changeElementSize(16) 4567 : Ty.changeElementSize(32); 4568 } 4569 4570 // Answering this is somewhat tricky and depends on the specific device which 4571 // have different rates for fma or all f64 operations. 4572 // 4573 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4574 // regardless of which device (although the number of cycles differs between 4575 // devices), so it is always profitable for f64. 4576 // 4577 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4578 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4579 // which we can always do even without fused FP ops since it returns the same 4580 // result as the separate operations and since it is always full 4581 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4582 // however does not support denormals, so we do report fma as faster if we have 4583 // a fast fma device and require denormals. 4584 // 4585 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4586 EVT VT) const { 4587 VT = VT.getScalarType(); 4588 4589 switch (VT.getSimpleVT().SimpleTy) { 4590 case MVT::f32: { 4591 // If mad is not available this depends only on if f32 fma is full rate. 4592 if (!Subtarget->hasMadMacF32Insts()) 4593 return Subtarget->hasFastFMAF32(); 4594 4595 // Otherwise f32 mad is always full rate and returns the same result as 4596 // the separate operations so should be preferred over fma. 4597 // However does not support denormals. 4598 if (hasFP32Denormals(MF)) 4599 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4600 4601 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4602 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4603 } 4604 case MVT::f64: 4605 return true; 4606 case MVT::f16: 4607 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4608 default: 4609 break; 4610 } 4611 4612 return false; 4613 } 4614 4615 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4616 LLT Ty) const { 4617 switch (Ty.getScalarSizeInBits()) { 4618 case 16: 4619 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4620 case 32: 4621 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4622 case 64: 4623 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4624 default: 4625 break; 4626 } 4627 4628 return false; 4629 } 4630 4631 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4632 if (!Ty.isScalar()) 4633 return false; 4634 4635 if (Ty.getScalarSizeInBits() == 16) 4636 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4637 if (Ty.getScalarSizeInBits() == 32) 4638 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4639 4640 return false; 4641 } 4642 4643 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4644 const SDNode *N) const { 4645 // TODO: Check future ftz flag 4646 // v_mad_f32/v_mac_f32 do not support denormals. 4647 EVT VT = N->getValueType(0); 4648 if (VT == MVT::f32) 4649 return Subtarget->hasMadMacF32Insts() && 4650 !hasFP32Denormals(DAG.getMachineFunction()); 4651 if (VT == MVT::f16) { 4652 return Subtarget->hasMadF16() && 4653 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4654 } 4655 4656 return false; 4657 } 4658 4659 //===----------------------------------------------------------------------===// 4660 // Custom DAG Lowering Operations 4661 //===----------------------------------------------------------------------===// 4662 4663 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4664 // wider vector type is legal. 4665 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4666 SelectionDAG &DAG) const { 4667 unsigned Opc = Op.getOpcode(); 4668 EVT VT = Op.getValueType(); 4669 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4670 4671 SDValue Lo, Hi; 4672 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4673 4674 SDLoc SL(Op); 4675 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4676 Op->getFlags()); 4677 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4678 Op->getFlags()); 4679 4680 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4681 } 4682 4683 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4684 // wider vector type is legal. 4685 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4686 SelectionDAG &DAG) const { 4687 unsigned Opc = Op.getOpcode(); 4688 EVT VT = Op.getValueType(); 4689 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4690 VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 || 4691 VT == MVT::v16f32 || VT == MVT::v32f32); 4692 4693 SDValue Lo0, Hi0; 4694 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4695 SDValue Lo1, Hi1; 4696 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4697 4698 SDLoc SL(Op); 4699 4700 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4701 Op->getFlags()); 4702 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4703 Op->getFlags()); 4704 4705 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4706 } 4707 4708 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4709 SelectionDAG &DAG) const { 4710 unsigned Opc = Op.getOpcode(); 4711 EVT VT = Op.getValueType(); 4712 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 || 4713 VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 || 4714 VT == MVT::v16f32 || VT == MVT::v32f32); 4715 4716 SDValue Lo0, Hi0; 4717 SDValue Op0 = Op.getOperand(0); 4718 std::tie(Lo0, Hi0) = Op0.getValueType().isVector() 4719 ? DAG.SplitVectorOperand(Op.getNode(), 0) 4720 : std::make_pair(Op0, Op0); 4721 SDValue Lo1, Hi1; 4722 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4723 SDValue Lo2, Hi2; 4724 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4725 4726 SDLoc SL(Op); 4727 auto ResVT = DAG.GetSplitDestVTs(VT); 4728 4729 SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2, 4730 Op->getFlags()); 4731 SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2, 4732 Op->getFlags()); 4733 4734 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4735 } 4736 4737 4738 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4739 switch (Op.getOpcode()) { 4740 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4741 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4742 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4743 case ISD::LOAD: { 4744 SDValue Result = LowerLOAD(Op, DAG); 4745 assert((!Result.getNode() || 4746 Result.getNode()->getNumValues() == 2) && 4747 "Load should return a value and a chain"); 4748 return Result; 4749 } 4750 4751 case ISD::FSIN: 4752 case ISD::FCOS: 4753 return LowerTrig(Op, DAG); 4754 case ISD::SELECT: return LowerSELECT(Op, DAG); 4755 case ISD::FDIV: return LowerFDIV(Op, DAG); 4756 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4757 case ISD::STORE: return LowerSTORE(Op, DAG); 4758 case ISD::GlobalAddress: { 4759 MachineFunction &MF = DAG.getMachineFunction(); 4760 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4761 return LowerGlobalAddress(MFI, Op, DAG); 4762 } 4763 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4764 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4765 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4766 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4767 case ISD::INSERT_SUBVECTOR: 4768 return lowerINSERT_SUBVECTOR(Op, DAG); 4769 case ISD::INSERT_VECTOR_ELT: 4770 return lowerINSERT_VECTOR_ELT(Op, DAG); 4771 case ISD::EXTRACT_VECTOR_ELT: 4772 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4773 case ISD::VECTOR_SHUFFLE: 4774 return lowerVECTOR_SHUFFLE(Op, DAG); 4775 case ISD::SCALAR_TO_VECTOR: 4776 return lowerSCALAR_TO_VECTOR(Op, DAG); 4777 case ISD::BUILD_VECTOR: 4778 return lowerBUILD_VECTOR(Op, DAG); 4779 case ISD::FP_ROUND: 4780 return lowerFP_ROUND(Op, DAG); 4781 case ISD::FPTRUNC_ROUND: { 4782 unsigned Opc; 4783 SDLoc DL(Op); 4784 4785 if (Op.getOperand(0)->getValueType(0) != MVT::f32) 4786 return SDValue(); 4787 4788 // Get the rounding mode from the last operand 4789 int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4790 if (RoundMode == (int)RoundingMode::TowardPositive) 4791 Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD; 4792 else if (RoundMode == (int)RoundingMode::TowardNegative) 4793 Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD; 4794 else 4795 return SDValue(); 4796 4797 return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0)); 4798 } 4799 case ISD::TRAP: 4800 return lowerTRAP(Op, DAG); 4801 case ISD::DEBUGTRAP: 4802 return lowerDEBUGTRAP(Op, DAG); 4803 case ISD::FABS: 4804 case ISD::FNEG: 4805 case ISD::FCANONICALIZE: 4806 case ISD::BSWAP: 4807 return splitUnaryVectorOp(Op, DAG); 4808 case ISD::FMINNUM: 4809 case ISD::FMAXNUM: 4810 return lowerFMINNUM_FMAXNUM(Op, DAG); 4811 case ISD::FMA: 4812 return splitTernaryVectorOp(Op, DAG); 4813 case ISD::FP_TO_SINT: 4814 case ISD::FP_TO_UINT: 4815 return LowerFP_TO_INT(Op, DAG); 4816 case ISD::SHL: 4817 case ISD::SRA: 4818 case ISD::SRL: 4819 case ISD::ADD: 4820 case ISD::SUB: 4821 case ISD::MUL: 4822 case ISD::SMIN: 4823 case ISD::SMAX: 4824 case ISD::UMIN: 4825 case ISD::UMAX: 4826 case ISD::FADD: 4827 case ISD::FMUL: 4828 case ISD::FMINNUM_IEEE: 4829 case ISD::FMAXNUM_IEEE: 4830 case ISD::UADDSAT: 4831 case ISD::USUBSAT: 4832 case ISD::SADDSAT: 4833 case ISD::SSUBSAT: 4834 return splitBinaryVectorOp(Op, DAG); 4835 case ISD::SMULO: 4836 case ISD::UMULO: 4837 return lowerXMULO(Op, DAG); 4838 case ISD::SMUL_LOHI: 4839 case ISD::UMUL_LOHI: 4840 return lowerXMUL_LOHI(Op, DAG); 4841 case ISD::DYNAMIC_STACKALLOC: 4842 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4843 } 4844 return SDValue(); 4845 } 4846 4847 // Used for D16: Casts the result of an instruction into the right vector, 4848 // packs values if loads return unpacked values. 4849 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4850 const SDLoc &DL, 4851 SelectionDAG &DAG, bool Unpacked) { 4852 if (!LoadVT.isVector()) 4853 return Result; 4854 4855 // Cast back to the original packed type or to a larger type that is a 4856 // multiple of 32 bit for D16. Widening the return type is a required for 4857 // legalization. 4858 EVT FittingLoadVT = LoadVT; 4859 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4860 FittingLoadVT = 4861 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4862 LoadVT.getVectorNumElements() + 1); 4863 } 4864 4865 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4866 // Truncate to v2i16/v4i16. 4867 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4868 4869 // Workaround legalizer not scalarizing truncate after vector op 4870 // legalization but not creating intermediate vector trunc. 4871 SmallVector<SDValue, 4> Elts; 4872 DAG.ExtractVectorElements(Result, Elts); 4873 for (SDValue &Elt : Elts) 4874 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4875 4876 // Pad illegal v1i16/v3fi6 to v4i16 4877 if ((LoadVT.getVectorNumElements() % 2) == 1) 4878 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4879 4880 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4881 4882 // Bitcast to original type (v2f16/v4f16). 4883 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4884 } 4885 4886 // Cast back to the original packed type. 4887 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4888 } 4889 4890 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4891 MemSDNode *M, 4892 SelectionDAG &DAG, 4893 ArrayRef<SDValue> Ops, 4894 bool IsIntrinsic) const { 4895 SDLoc DL(M); 4896 4897 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4898 EVT LoadVT = M->getValueType(0); 4899 4900 EVT EquivLoadVT = LoadVT; 4901 if (LoadVT.isVector()) { 4902 if (Unpacked) { 4903 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4904 LoadVT.getVectorNumElements()); 4905 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4906 // Widen v3f16 to legal type 4907 EquivLoadVT = 4908 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4909 LoadVT.getVectorNumElements() + 1); 4910 } 4911 } 4912 4913 // Change from v4f16/v2f16 to EquivLoadVT. 4914 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4915 4916 SDValue Load 4917 = DAG.getMemIntrinsicNode( 4918 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4919 VTList, Ops, M->getMemoryVT(), 4920 M->getMemOperand()); 4921 4922 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4923 4924 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4925 } 4926 4927 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4928 SelectionDAG &DAG, 4929 ArrayRef<SDValue> Ops) const { 4930 SDLoc DL(M); 4931 EVT LoadVT = M->getValueType(0); 4932 EVT EltType = LoadVT.getScalarType(); 4933 EVT IntVT = LoadVT.changeTypeToInteger(); 4934 4935 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4936 4937 unsigned Opc = 4938 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4939 4940 if (IsD16) { 4941 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4942 } 4943 4944 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4945 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4946 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4947 4948 if (isTypeLegal(LoadVT)) { 4949 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4950 M->getMemOperand(), DAG); 4951 } 4952 4953 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4954 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4955 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4956 M->getMemOperand(), DAG); 4957 return DAG.getMergeValues( 4958 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4959 DL); 4960 } 4961 4962 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4963 SDNode *N, SelectionDAG &DAG) { 4964 EVT VT = N->getValueType(0); 4965 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4966 unsigned CondCode = CD->getZExtValue(); 4967 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4968 return DAG.getUNDEF(VT); 4969 4970 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4971 4972 SDValue LHS = N->getOperand(1); 4973 SDValue RHS = N->getOperand(2); 4974 4975 SDLoc DL(N); 4976 4977 EVT CmpVT = LHS.getValueType(); 4978 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4979 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4980 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4981 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4982 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4983 } 4984 4985 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4986 4987 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4988 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4989 4990 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4991 DAG.getCondCode(CCOpcode)); 4992 if (VT.bitsEq(CCVT)) 4993 return SetCC; 4994 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4995 } 4996 4997 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4998 SDNode *N, SelectionDAG &DAG) { 4999 EVT VT = N->getValueType(0); 5000 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 5001 5002 unsigned CondCode = CD->getZExtValue(); 5003 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 5004 return DAG.getUNDEF(VT); 5005 5006 SDValue Src0 = N->getOperand(1); 5007 SDValue Src1 = N->getOperand(2); 5008 EVT CmpVT = Src0.getValueType(); 5009 SDLoc SL(N); 5010 5011 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 5012 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5013 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5014 } 5015 5016 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 5017 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 5018 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 5019 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 5020 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 5021 Src1, DAG.getCondCode(CCOpcode)); 5022 if (VT.bitsEq(CCVT)) 5023 return SetCC; 5024 return DAG.getZExtOrTrunc(SetCC, SL, VT); 5025 } 5026 5027 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 5028 SelectionDAG &DAG) { 5029 EVT VT = N->getValueType(0); 5030 SDValue Src = N->getOperand(1); 5031 SDLoc SL(N); 5032 5033 if (Src.getOpcode() == ISD::SETCC) { 5034 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 5035 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 5036 Src.getOperand(1), Src.getOperand(2)); 5037 } 5038 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 5039 // (ballot 0) -> 0 5040 if (Arg->isZero()) 5041 return DAG.getConstant(0, SL, VT); 5042 5043 // (ballot 1) -> EXEC/EXEC_LO 5044 if (Arg->isOne()) { 5045 Register Exec; 5046 if (VT.getScalarSizeInBits() == 32) 5047 Exec = AMDGPU::EXEC_LO; 5048 else if (VT.getScalarSizeInBits() == 64) 5049 Exec = AMDGPU::EXEC; 5050 else 5051 return SDValue(); 5052 5053 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 5054 } 5055 } 5056 5057 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 5058 // ISD::SETNE) 5059 return DAG.getNode( 5060 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 5061 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 5062 } 5063 5064 void SITargetLowering::ReplaceNodeResults(SDNode *N, 5065 SmallVectorImpl<SDValue> &Results, 5066 SelectionDAG &DAG) const { 5067 switch (N->getOpcode()) { 5068 case ISD::INSERT_VECTOR_ELT: { 5069 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 5070 Results.push_back(Res); 5071 return; 5072 } 5073 case ISD::EXTRACT_VECTOR_ELT: { 5074 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 5075 Results.push_back(Res); 5076 return; 5077 } 5078 case ISD::INTRINSIC_WO_CHAIN: { 5079 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5080 switch (IID) { 5081 case Intrinsic::amdgcn_cvt_pkrtz: { 5082 SDValue Src0 = N->getOperand(1); 5083 SDValue Src1 = N->getOperand(2); 5084 SDLoc SL(N); 5085 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 5086 Src0, Src1); 5087 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 5088 return; 5089 } 5090 case Intrinsic::amdgcn_cvt_pknorm_i16: 5091 case Intrinsic::amdgcn_cvt_pknorm_u16: 5092 case Intrinsic::amdgcn_cvt_pk_i16: 5093 case Intrinsic::amdgcn_cvt_pk_u16: { 5094 SDValue Src0 = N->getOperand(1); 5095 SDValue Src1 = N->getOperand(2); 5096 SDLoc SL(N); 5097 unsigned Opcode; 5098 5099 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 5100 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5101 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 5102 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5103 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 5104 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5105 else 5106 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5107 5108 EVT VT = N->getValueType(0); 5109 if (isTypeLegal(VT)) 5110 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 5111 else { 5112 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 5113 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 5114 } 5115 return; 5116 } 5117 } 5118 break; 5119 } 5120 case ISD::INTRINSIC_W_CHAIN: { 5121 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5122 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5123 // FIXME: Hacky 5124 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5125 Results.push_back(Res.getOperand(I)); 5126 } 5127 } else { 5128 Results.push_back(Res); 5129 Results.push_back(Res.getValue(1)); 5130 } 5131 return; 5132 } 5133 5134 break; 5135 } 5136 case ISD::SELECT: { 5137 SDLoc SL(N); 5138 EVT VT = N->getValueType(0); 5139 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5140 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5141 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5142 5143 EVT SelectVT = NewVT; 5144 if (NewVT.bitsLT(MVT::i32)) { 5145 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5146 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5147 SelectVT = MVT::i32; 5148 } 5149 5150 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5151 N->getOperand(0), LHS, RHS); 5152 5153 if (NewVT != SelectVT) 5154 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5155 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5156 return; 5157 } 5158 case ISD::FNEG: { 5159 if (N->getValueType(0) != MVT::v2f16) 5160 break; 5161 5162 SDLoc SL(N); 5163 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5164 5165 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5166 BC, 5167 DAG.getConstant(0x80008000, SL, MVT::i32)); 5168 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5169 return; 5170 } 5171 case ISD::FABS: { 5172 if (N->getValueType(0) != MVT::v2f16) 5173 break; 5174 5175 SDLoc SL(N); 5176 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5177 5178 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5179 BC, 5180 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5181 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5182 return; 5183 } 5184 default: 5185 break; 5186 } 5187 } 5188 5189 /// Helper function for LowerBRCOND 5190 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5191 5192 SDNode *Parent = Value.getNode(); 5193 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5194 I != E; ++I) { 5195 5196 if (I.getUse().get() != Value) 5197 continue; 5198 5199 if (I->getOpcode() == Opcode) 5200 return *I; 5201 } 5202 return nullptr; 5203 } 5204 5205 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5206 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5207 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5208 case Intrinsic::amdgcn_if: 5209 return AMDGPUISD::IF; 5210 case Intrinsic::amdgcn_else: 5211 return AMDGPUISD::ELSE; 5212 case Intrinsic::amdgcn_loop: 5213 return AMDGPUISD::LOOP; 5214 case Intrinsic::amdgcn_end_cf: 5215 llvm_unreachable("should not occur"); 5216 default: 5217 return 0; 5218 } 5219 } 5220 5221 // break, if_break, else_break are all only used as inputs to loop, not 5222 // directly as branch conditions. 5223 return 0; 5224 } 5225 5226 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5227 const Triple &TT = getTargetMachine().getTargetTriple(); 5228 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5229 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5230 AMDGPU::shouldEmitConstantsToTextSection(TT); 5231 } 5232 5233 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5234 // FIXME: Either avoid relying on address space here or change the default 5235 // address space for functions to avoid the explicit check. 5236 return (GV->getValueType()->isFunctionTy() || 5237 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5238 !shouldEmitFixup(GV) && 5239 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5240 } 5241 5242 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5243 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5244 } 5245 5246 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5247 if (!GV->hasExternalLinkage()) 5248 return true; 5249 5250 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5251 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5252 } 5253 5254 /// This transforms the control flow intrinsics to get the branch destination as 5255 /// last parameter, also switches branch target with BR if the need arise 5256 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5257 SelectionDAG &DAG) const { 5258 SDLoc DL(BRCOND); 5259 5260 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5261 SDValue Target = BRCOND.getOperand(2); 5262 SDNode *BR = nullptr; 5263 SDNode *SetCC = nullptr; 5264 5265 if (Intr->getOpcode() == ISD::SETCC) { 5266 // As long as we negate the condition everything is fine 5267 SetCC = Intr; 5268 Intr = SetCC->getOperand(0).getNode(); 5269 5270 } else { 5271 // Get the target from BR if we don't negate the condition 5272 BR = findUser(BRCOND, ISD::BR); 5273 assert(BR && "brcond missing unconditional branch user"); 5274 Target = BR->getOperand(1); 5275 } 5276 5277 unsigned CFNode = isCFIntrinsic(Intr); 5278 if (CFNode == 0) { 5279 // This is a uniform branch so we don't need to legalize. 5280 return BRCOND; 5281 } 5282 5283 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5284 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5285 5286 assert(!SetCC || 5287 (SetCC->getConstantOperandVal(1) == 1 && 5288 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5289 ISD::SETNE)); 5290 5291 // operands of the new intrinsic call 5292 SmallVector<SDValue, 4> Ops; 5293 if (HaveChain) 5294 Ops.push_back(BRCOND.getOperand(0)); 5295 5296 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5297 Ops.push_back(Target); 5298 5299 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5300 5301 // build the new intrinsic call 5302 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5303 5304 if (!HaveChain) { 5305 SDValue Ops[] = { 5306 SDValue(Result, 0), 5307 BRCOND.getOperand(0) 5308 }; 5309 5310 Result = DAG.getMergeValues(Ops, DL).getNode(); 5311 } 5312 5313 if (BR) { 5314 // Give the branch instruction our target 5315 SDValue Ops[] = { 5316 BR->getOperand(0), 5317 BRCOND.getOperand(2) 5318 }; 5319 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5320 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5321 } 5322 5323 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5324 5325 // Copy the intrinsic results to registers 5326 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5327 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5328 if (!CopyToReg) 5329 continue; 5330 5331 Chain = DAG.getCopyToReg( 5332 Chain, DL, 5333 CopyToReg->getOperand(1), 5334 SDValue(Result, i - 1), 5335 SDValue()); 5336 5337 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5338 } 5339 5340 // Remove the old intrinsic from the chain 5341 DAG.ReplaceAllUsesOfValueWith( 5342 SDValue(Intr, Intr->getNumValues() - 1), 5343 Intr->getOperand(0)); 5344 5345 return Chain; 5346 } 5347 5348 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5349 SelectionDAG &DAG) const { 5350 MVT VT = Op.getSimpleValueType(); 5351 SDLoc DL(Op); 5352 // Checking the depth 5353 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5354 return DAG.getConstant(0, DL, VT); 5355 5356 MachineFunction &MF = DAG.getMachineFunction(); 5357 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5358 // Check for kernel and shader functions 5359 if (Info->isEntryFunction()) 5360 return DAG.getConstant(0, DL, VT); 5361 5362 MachineFrameInfo &MFI = MF.getFrameInfo(); 5363 // There is a call to @llvm.returnaddress in this function 5364 MFI.setReturnAddressIsTaken(true); 5365 5366 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5367 // Get the return address reg and mark it as an implicit live-in 5368 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5369 5370 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5371 } 5372 5373 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5374 SDValue Op, 5375 const SDLoc &DL, 5376 EVT VT) const { 5377 return Op.getValueType().bitsLE(VT) ? 5378 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5379 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5380 DAG.getTargetConstant(0, DL, MVT::i32)); 5381 } 5382 5383 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5384 assert(Op.getValueType() == MVT::f16 && 5385 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5386 5387 SDValue Src = Op.getOperand(0); 5388 EVT SrcVT = Src.getValueType(); 5389 if (SrcVT != MVT::f64) 5390 return Op; 5391 5392 SDLoc DL(Op); 5393 5394 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5395 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5396 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5397 } 5398 5399 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5400 SelectionDAG &DAG) const { 5401 EVT VT = Op.getValueType(); 5402 const MachineFunction &MF = DAG.getMachineFunction(); 5403 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5404 bool IsIEEEMode = Info->getMode().IEEE; 5405 5406 // FIXME: Assert during selection that this is only selected for 5407 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5408 // mode functions, but this happens to be OK since it's only done in cases 5409 // where there is known no sNaN. 5410 if (IsIEEEMode) 5411 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5412 5413 if (VT == MVT::v4f16 || VT == MVT::v8f16) 5414 return splitBinaryVectorOp(Op, DAG); 5415 return Op; 5416 } 5417 5418 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5419 EVT VT = Op.getValueType(); 5420 SDLoc SL(Op); 5421 SDValue LHS = Op.getOperand(0); 5422 SDValue RHS = Op.getOperand(1); 5423 bool isSigned = Op.getOpcode() == ISD::SMULO; 5424 5425 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5426 const APInt &C = RHSC->getAPIntValue(); 5427 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5428 if (C.isPowerOf2()) { 5429 // smulo(x, signed_min) is same as umulo(x, signed_min). 5430 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5431 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5432 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5433 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5434 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5435 SL, VT, Result, ShiftAmt), 5436 LHS, ISD::SETNE); 5437 return DAG.getMergeValues({ Result, Overflow }, SL); 5438 } 5439 } 5440 5441 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5442 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5443 SL, VT, LHS, RHS); 5444 5445 SDValue Sign = isSigned 5446 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5447 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5448 : DAG.getConstant(0, SL, VT); 5449 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5450 5451 return DAG.getMergeValues({ Result, Overflow }, SL); 5452 } 5453 5454 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5455 if (Op->isDivergent()) { 5456 // Select to V_MAD_[IU]64_[IU]32. 5457 return Op; 5458 } 5459 if (Subtarget->hasSMulHi()) { 5460 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5461 return SDValue(); 5462 } 5463 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5464 // calculate the high part, so we might as well do the whole thing with 5465 // V_MAD_[IU]64_[IU]32. 5466 return Op; 5467 } 5468 5469 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5470 if (!Subtarget->isTrapHandlerEnabled() || 5471 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5472 return lowerTrapEndpgm(Op, DAG); 5473 5474 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5475 switch (*HsaAbiVer) { 5476 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5477 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5478 return lowerTrapHsaQueuePtr(Op, DAG); 5479 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5480 case ELF::ELFABIVERSION_AMDGPU_HSA_V5: 5481 return Subtarget->supportsGetDoorbellID() ? 5482 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5483 } 5484 } 5485 5486 llvm_unreachable("Unknown trap handler"); 5487 } 5488 5489 SDValue SITargetLowering::lowerTrapEndpgm( 5490 SDValue Op, SelectionDAG &DAG) const { 5491 SDLoc SL(Op); 5492 SDValue Chain = Op.getOperand(0); 5493 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5494 } 5495 5496 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT, 5497 const SDLoc &DL, Align Alignment, ImplicitParameter Param) const { 5498 MachineFunction &MF = DAG.getMachineFunction(); 5499 uint64_t Offset = getImplicitParameterOffset(MF, Param); 5500 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset); 5501 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5502 return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment, 5503 MachineMemOperand::MODereferenceable | 5504 MachineMemOperand::MOInvariant); 5505 } 5506 5507 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5508 SDValue Op, SelectionDAG &DAG) const { 5509 SDLoc SL(Op); 5510 SDValue Chain = Op.getOperand(0); 5511 5512 SDValue QueuePtr; 5513 // For code object version 5, QueuePtr is passed through implicit kernarg. 5514 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5515 QueuePtr = 5516 loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR); 5517 } else { 5518 MachineFunction &MF = DAG.getMachineFunction(); 5519 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5520 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5521 5522 if (UserSGPR == AMDGPU::NoRegister) { 5523 // We probably are in a function incorrectly marked with 5524 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the 5525 // trap, so just use a null pointer. 5526 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5527 } else { 5528 QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR, 5529 MVT::i64); 5530 } 5531 } 5532 5533 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5534 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5535 QueuePtr, SDValue()); 5536 5537 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5538 SDValue Ops[] = { 5539 ToReg, 5540 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5541 SGPR01, 5542 ToReg.getValue(1) 5543 }; 5544 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5545 } 5546 5547 SDValue SITargetLowering::lowerTrapHsa( 5548 SDValue Op, SelectionDAG &DAG) const { 5549 SDLoc SL(Op); 5550 SDValue Chain = Op.getOperand(0); 5551 5552 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5553 SDValue Ops[] = { 5554 Chain, 5555 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5556 }; 5557 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5558 } 5559 5560 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5561 SDLoc SL(Op); 5562 SDValue Chain = Op.getOperand(0); 5563 MachineFunction &MF = DAG.getMachineFunction(); 5564 5565 if (!Subtarget->isTrapHandlerEnabled() || 5566 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5567 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5568 "debugtrap handler not supported", 5569 Op.getDebugLoc(), 5570 DS_Warning); 5571 LLVMContext &Ctx = MF.getFunction().getContext(); 5572 Ctx.diagnose(NoTrap); 5573 return Chain; 5574 } 5575 5576 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5577 SDValue Ops[] = { 5578 Chain, 5579 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5580 }; 5581 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5582 } 5583 5584 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5585 SelectionDAG &DAG) const { 5586 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5587 if (Subtarget->hasApertureRegs()) { 5588 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5589 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5590 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5591 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5592 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5593 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5594 unsigned Encoding = 5595 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5596 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5597 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5598 5599 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5600 SDValue ApertureReg = SDValue( 5601 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5602 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5603 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5604 } 5605 5606 // For code object version 5, private_base and shared_base are passed through 5607 // implicit kernargs. 5608 if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) { 5609 ImplicitParameter Param = 5610 (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE; 5611 return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param); 5612 } 5613 5614 MachineFunction &MF = DAG.getMachineFunction(); 5615 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5616 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5617 if (UserSGPR == AMDGPU::NoRegister) { 5618 // We probably are in a function incorrectly marked with 5619 // amdgpu-no-queue-ptr. This is undefined. 5620 return DAG.getUNDEF(MVT::i32); 5621 } 5622 5623 SDValue QueuePtr = CreateLiveInRegister( 5624 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5625 5626 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5627 // private_segment_aperture_base_hi. 5628 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5629 5630 SDValue Ptr = 5631 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5632 5633 // TODO: Use custom target PseudoSourceValue. 5634 // TODO: We should use the value from the IR intrinsic call, but it might not 5635 // be available and how do we get it? 5636 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5637 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5638 commonAlignment(Align(64), StructOffset), 5639 MachineMemOperand::MODereferenceable | 5640 MachineMemOperand::MOInvariant); 5641 } 5642 5643 /// Return true if the value is a known valid address, such that a null check is 5644 /// not necessary. 5645 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5646 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5647 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5648 isa<BasicBlockSDNode>(Val)) 5649 return true; 5650 5651 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5652 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5653 5654 // TODO: Search through arithmetic, handle arguments and loads 5655 // marked nonnull. 5656 return false; 5657 } 5658 5659 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5660 SelectionDAG &DAG) const { 5661 SDLoc SL(Op); 5662 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5663 5664 SDValue Src = ASC->getOperand(0); 5665 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5666 unsigned SrcAS = ASC->getSrcAddressSpace(); 5667 5668 const AMDGPUTargetMachine &TM = 5669 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5670 5671 // flat -> local/private 5672 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5673 unsigned DestAS = ASC->getDestAddressSpace(); 5674 5675 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5676 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5677 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5678 5679 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5680 return Ptr; 5681 5682 unsigned NullVal = TM.getNullPointerValue(DestAS); 5683 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5684 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5685 5686 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5687 SegmentNullPtr); 5688 } 5689 } 5690 5691 // local/private -> flat 5692 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5693 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5694 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5695 5696 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5697 SDValue CvtPtr = 5698 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5699 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5700 5701 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5702 return CvtPtr; 5703 5704 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5705 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5706 5707 SDValue NonNull 5708 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5709 5710 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5711 FlatNullPtr); 5712 } 5713 } 5714 5715 if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5716 Op.getValueType() == MVT::i64) { 5717 const SIMachineFunctionInfo *Info = 5718 DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 5719 SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32); 5720 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi); 5721 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 5722 } 5723 5724 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5725 Src.getValueType() == MVT::i64) 5726 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5727 5728 // global <-> flat are no-ops and never emitted. 5729 5730 const MachineFunction &MF = DAG.getMachineFunction(); 5731 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5732 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5733 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5734 5735 return DAG.getUNDEF(ASC->getValueType(0)); 5736 } 5737 5738 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5739 // the small vector and inserting them into the big vector. That is better than 5740 // the default expansion of doing it via a stack slot. Even though the use of 5741 // the stack slot would be optimized away afterwards, the stack slot itself 5742 // remains. 5743 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5744 SelectionDAG &DAG) const { 5745 SDValue Vec = Op.getOperand(0); 5746 SDValue Ins = Op.getOperand(1); 5747 SDValue Idx = Op.getOperand(2); 5748 EVT VecVT = Vec.getValueType(); 5749 EVT InsVT = Ins.getValueType(); 5750 EVT EltVT = VecVT.getVectorElementType(); 5751 unsigned InsNumElts = InsVT.getVectorNumElements(); 5752 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5753 SDLoc SL(Op); 5754 5755 for (unsigned I = 0; I != InsNumElts; ++I) { 5756 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5757 DAG.getConstant(I, SL, MVT::i32)); 5758 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5759 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5760 } 5761 return Vec; 5762 } 5763 5764 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5765 SelectionDAG &DAG) const { 5766 SDValue Vec = Op.getOperand(0); 5767 SDValue InsVal = Op.getOperand(1); 5768 SDValue Idx = Op.getOperand(2); 5769 EVT VecVT = Vec.getValueType(); 5770 EVT EltVT = VecVT.getVectorElementType(); 5771 unsigned VecSize = VecVT.getSizeInBits(); 5772 unsigned EltSize = EltVT.getSizeInBits(); 5773 SDLoc SL(Op); 5774 5775 // Specially handle the case of v4i16 with static indexing. 5776 unsigned NumElts = VecVT.getVectorNumElements(); 5777 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5778 if (NumElts == 4 && EltSize == 16 && KIdx) { 5779 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5780 5781 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5782 DAG.getConstant(0, SL, MVT::i32)); 5783 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5784 DAG.getConstant(1, SL, MVT::i32)); 5785 5786 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5787 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5788 5789 unsigned Idx = KIdx->getZExtValue(); 5790 bool InsertLo = Idx < 2; 5791 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5792 InsertLo ? LoVec : HiVec, 5793 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5794 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5795 5796 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5797 5798 SDValue Concat = InsertLo ? 5799 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5800 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5801 5802 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5803 } 5804 5805 // Static indexing does not lower to stack access, and hence there is no need 5806 // for special custom lowering to avoid stack access. 5807 if (isa<ConstantSDNode>(Idx)) 5808 return SDValue(); 5809 5810 // Avoid stack access for dynamic indexing by custom lowering to 5811 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5812 5813 assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits"); 5814 5815 MVT IntVT = MVT::getIntegerVT(VecSize); 5816 5817 // Convert vector index to bit-index and get the required bit mask. 5818 assert(isPowerOf2_32(EltSize)); 5819 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5820 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5821 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5822 DAG.getConstant(0xffff, SL, IntVT), 5823 ScaledIdx); 5824 5825 // 1. Create a congruent vector with the target value in each element. 5826 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5827 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5828 5829 // 2. Mask off all other indicies except the required index within (1). 5830 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5831 5832 // 3. Mask off the required index within the target vector. 5833 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5834 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5835 DAG.getNOT(SL, BFM, IntVT), BCVec); 5836 5837 // 4. Get (2) and (3) ORed into the target vector. 5838 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5839 5840 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5841 } 5842 5843 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5844 SelectionDAG &DAG) const { 5845 SDLoc SL(Op); 5846 5847 EVT ResultVT = Op.getValueType(); 5848 SDValue Vec = Op.getOperand(0); 5849 SDValue Idx = Op.getOperand(1); 5850 EVT VecVT = Vec.getValueType(); 5851 unsigned VecSize = VecVT.getSizeInBits(); 5852 EVT EltVT = VecVT.getVectorElementType(); 5853 5854 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5855 5856 // Make sure we do any optimizations that will make it easier to fold 5857 // source modifiers before obscuring it with bit operations. 5858 5859 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5860 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5861 return Combined; 5862 5863 if (VecSize == 128) { 5864 SDValue Lo, Hi; 5865 EVT LoVT, HiVT; 5866 SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec); 5867 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5868 Lo = 5869 DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5870 V2, DAG.getConstant(0, SL, MVT::i32))); 5871 Hi = 5872 DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, 5873 V2, DAG.getConstant(1, SL, MVT::i32))); 5874 EVT IdxVT = Idx.getValueType(); 5875 unsigned NElem = VecVT.getVectorNumElements(); 5876 assert(isPowerOf2_32(NElem)); 5877 SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT); 5878 SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask); 5879 SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT); 5880 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx); 5881 } 5882 5883 assert(VecSize <= 64); 5884 5885 MVT IntVT = MVT::getIntegerVT(VecSize); 5886 5887 // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly. 5888 SDValue VecBC = peekThroughBitcasts(Vec); 5889 if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) { 5890 SDValue Src = VecBC.getOperand(0); 5891 Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src); 5892 Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT); 5893 } 5894 5895 unsigned EltSize = EltVT.getSizeInBits(); 5896 assert(isPowerOf2_32(EltSize)); 5897 5898 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5899 5900 // Convert vector index to bit-index (* EltSize) 5901 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5902 5903 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5904 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5905 5906 if (ResultVT == MVT::f16) { 5907 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5908 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5909 } 5910 5911 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5912 } 5913 5914 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5915 assert(Elt % 2 == 0); 5916 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5917 } 5918 5919 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5920 SelectionDAG &DAG) const { 5921 SDLoc SL(Op); 5922 EVT ResultVT = Op.getValueType(); 5923 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5924 5925 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5926 EVT EltVT = PackVT.getVectorElementType(); 5927 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5928 5929 // vector_shuffle <0,1,6,7> lhs, rhs 5930 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5931 // 5932 // vector_shuffle <6,7,2,3> lhs, rhs 5933 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5934 // 5935 // vector_shuffle <6,7,0,1> lhs, rhs 5936 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5937 5938 // Avoid scalarizing when both halves are reading from consecutive elements. 5939 SmallVector<SDValue, 4> Pieces; 5940 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5941 if (elementPairIsContiguous(SVN->getMask(), I)) { 5942 const int Idx = SVN->getMaskElt(I); 5943 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5944 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5945 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5946 PackVT, SVN->getOperand(VecIdx), 5947 DAG.getConstant(EltIdx, SL, MVT::i32)); 5948 Pieces.push_back(SubVec); 5949 } else { 5950 const int Idx0 = SVN->getMaskElt(I); 5951 const int Idx1 = SVN->getMaskElt(I + 1); 5952 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5953 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5954 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5955 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5956 5957 SDValue Vec0 = SVN->getOperand(VecIdx0); 5958 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5959 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5960 5961 SDValue Vec1 = SVN->getOperand(VecIdx1); 5962 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5963 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5964 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5965 } 5966 } 5967 5968 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5969 } 5970 5971 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op, 5972 SelectionDAG &DAG) const { 5973 SDValue SVal = Op.getOperand(0); 5974 EVT ResultVT = Op.getValueType(); 5975 EVT SValVT = SVal.getValueType(); 5976 SDValue UndefVal = DAG.getUNDEF(SValVT); 5977 SDLoc SL(Op); 5978 5979 SmallVector<SDValue, 8> VElts; 5980 VElts.push_back(SVal); 5981 for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I) 5982 VElts.push_back(UndefVal); 5983 5984 return DAG.getBuildVector(ResultVT, SL, VElts); 5985 } 5986 5987 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5988 SelectionDAG &DAG) const { 5989 SDLoc SL(Op); 5990 EVT VT = Op.getValueType(); 5991 5992 if (VT == MVT::v4i16 || VT == MVT::v4f16 || 5993 VT == MVT::v8i16 || VT == MVT::v8f16) { 5994 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 5995 VT.getVectorNumElements() / 2); 5996 MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits()); 5997 5998 // Turn into pair of packed build_vectors. 5999 // TODO: Special case for constants that can be materialized with s_mov_b64. 6000 SmallVector<SDValue, 4> LoOps, HiOps; 6001 for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) { 6002 LoOps.push_back(Op.getOperand(I)); 6003 HiOps.push_back(Op.getOperand(I + E)); 6004 } 6005 SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps); 6006 SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps); 6007 6008 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo); 6009 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi); 6010 6011 SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL, 6012 { CastLo, CastHi }); 6013 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 6014 } 6015 6016 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 6017 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 6018 6019 SDValue Lo = Op.getOperand(0); 6020 SDValue Hi = Op.getOperand(1); 6021 6022 // Avoid adding defined bits with the zero_extend. 6023 if (Hi.isUndef()) { 6024 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 6025 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 6026 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 6027 } 6028 6029 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 6030 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 6031 6032 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 6033 DAG.getConstant(16, SL, MVT::i32)); 6034 if (Lo.isUndef()) 6035 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 6036 6037 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 6038 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 6039 6040 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 6041 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 6042 } 6043 6044 bool 6045 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 6046 // We can fold offsets for anything that doesn't require a GOT relocation. 6047 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 6048 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 6049 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 6050 !shouldEmitGOTReloc(GA->getGlobal()); 6051 } 6052 6053 static SDValue 6054 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 6055 const SDLoc &DL, int64_t Offset, EVT PtrVT, 6056 unsigned GAFlags = SIInstrInfo::MO_NONE) { 6057 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 6058 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 6059 // lowered to the following code sequence: 6060 // 6061 // For constant address space: 6062 // s_getpc_b64 s[0:1] 6063 // s_add_u32 s0, s0, $symbol 6064 // s_addc_u32 s1, s1, 0 6065 // 6066 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6067 // a fixup or relocation is emitted to replace $symbol with a literal 6068 // constant, which is a pc-relative offset from the encoding of the $symbol 6069 // operand to the global variable. 6070 // 6071 // For global address space: 6072 // s_getpc_b64 s[0:1] 6073 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 6074 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 6075 // 6076 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 6077 // fixups or relocations are emitted to replace $symbol@*@lo and 6078 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 6079 // which is a 64-bit pc-relative offset from the encoding of the $symbol 6080 // operand to the global variable. 6081 // 6082 // What we want here is an offset from the value returned by s_getpc 6083 // (which is the address of the s_add_u32 instruction) to the global 6084 // variable, but since the encoding of $symbol starts 4 bytes after the start 6085 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 6086 // small. This requires us to add 4 to the global variable offset in order to 6087 // compute the correct address. Similarly for the s_addc_u32 instruction, the 6088 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 6089 // instruction. 6090 SDValue PtrLo = 6091 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 6092 SDValue PtrHi; 6093 if (GAFlags == SIInstrInfo::MO_NONE) { 6094 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 6095 } else { 6096 PtrHi = 6097 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 6098 } 6099 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 6100 } 6101 6102 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 6103 SDValue Op, 6104 SelectionDAG &DAG) const { 6105 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 6106 SDLoc DL(GSD); 6107 EVT PtrVT = Op.getValueType(); 6108 6109 const GlobalValue *GV = GSD->getGlobal(); 6110 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6111 shouldUseLDSConstAddress(GV)) || 6112 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 6113 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 6114 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 6115 GV->hasExternalLinkage()) { 6116 Type *Ty = GV->getValueType(); 6117 // HIP uses an unsized array `extern __shared__ T s[]` or similar 6118 // zero-sized type in other languages to declare the dynamic shared 6119 // memory which size is not known at the compile time. They will be 6120 // allocated by the runtime and placed directly after the static 6121 // allocated ones. They all share the same offset. 6122 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 6123 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 6124 // Adjust alignment for that dynamic shared memory array. 6125 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 6126 return SDValue( 6127 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 6128 } 6129 } 6130 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 6131 } 6132 6133 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 6134 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 6135 SIInstrInfo::MO_ABS32_LO); 6136 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 6137 } 6138 6139 if (shouldEmitFixup(GV)) 6140 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 6141 else if (shouldEmitPCReloc(GV)) 6142 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 6143 SIInstrInfo::MO_REL32); 6144 6145 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 6146 SIInstrInfo::MO_GOTPCREL32); 6147 6148 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 6149 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 6150 const DataLayout &DataLayout = DAG.getDataLayout(); 6151 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 6152 MachinePointerInfo PtrInfo 6153 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 6154 6155 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 6156 MachineMemOperand::MODereferenceable | 6157 MachineMemOperand::MOInvariant); 6158 } 6159 6160 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 6161 const SDLoc &DL, SDValue V) const { 6162 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 6163 // the destination register. 6164 // 6165 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 6166 // so we will end up with redundant moves to m0. 6167 // 6168 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 6169 6170 // A Null SDValue creates a glue result. 6171 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 6172 V, Chain); 6173 return SDValue(M0, 0); 6174 } 6175 6176 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 6177 SDValue Op, 6178 MVT VT, 6179 unsigned Offset) const { 6180 SDLoc SL(Op); 6181 SDValue Param = lowerKernargMemParameter( 6182 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 6183 // The local size values will have the hi 16-bits as zero. 6184 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 6185 DAG.getValueType(VT)); 6186 } 6187 6188 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6189 EVT VT) { 6190 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6191 "non-hsa intrinsic with hsa target", 6192 DL.getDebugLoc()); 6193 DAG.getContext()->diagnose(BadIntrin); 6194 return DAG.getUNDEF(VT); 6195 } 6196 6197 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 6198 EVT VT) { 6199 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 6200 "intrinsic not supported on subtarget", 6201 DL.getDebugLoc()); 6202 DAG.getContext()->diagnose(BadIntrin); 6203 return DAG.getUNDEF(VT); 6204 } 6205 6206 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 6207 ArrayRef<SDValue> Elts) { 6208 assert(!Elts.empty()); 6209 MVT Type; 6210 unsigned NumElts = Elts.size(); 6211 6212 if (NumElts <= 8) { 6213 Type = MVT::getVectorVT(MVT::f32, NumElts); 6214 } else { 6215 assert(Elts.size() <= 16); 6216 Type = MVT::v16f32; 6217 NumElts = 16; 6218 } 6219 6220 SmallVector<SDValue, 16> VecElts(NumElts); 6221 for (unsigned i = 0; i < Elts.size(); ++i) { 6222 SDValue Elt = Elts[i]; 6223 if (Elt.getValueType() != MVT::f32) 6224 Elt = DAG.getBitcast(MVT::f32, Elt); 6225 VecElts[i] = Elt; 6226 } 6227 for (unsigned i = Elts.size(); i < NumElts; ++i) 6228 VecElts[i] = DAG.getUNDEF(MVT::f32); 6229 6230 if (NumElts == 1) 6231 return VecElts[0]; 6232 return DAG.getBuildVector(Type, DL, VecElts); 6233 } 6234 6235 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6236 SDValue Src, int ExtraElts) { 6237 EVT SrcVT = Src.getValueType(); 6238 6239 SmallVector<SDValue, 8> Elts; 6240 6241 if (SrcVT.isVector()) 6242 DAG.ExtractVectorElements(Src, Elts); 6243 else 6244 Elts.push_back(Src); 6245 6246 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6247 while (ExtraElts--) 6248 Elts.push_back(Undef); 6249 6250 return DAG.getBuildVector(CastVT, DL, Elts); 6251 } 6252 6253 // Re-construct the required return value for a image load intrinsic. 6254 // This is more complicated due to the optional use TexFailCtrl which means the required 6255 // return type is an aggregate 6256 static SDValue constructRetValue(SelectionDAG &DAG, 6257 MachineSDNode *Result, 6258 ArrayRef<EVT> ResultTypes, 6259 bool IsTexFail, bool Unpacked, bool IsD16, 6260 int DMaskPop, int NumVDataDwords, 6261 const SDLoc &DL) { 6262 // Determine the required return type. This is the same regardless of IsTexFail flag 6263 EVT ReqRetVT = ResultTypes[0]; 6264 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6265 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6266 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6267 6268 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6269 DMaskPop : (DMaskPop + 1) / 2; 6270 6271 MVT DataDwordVT = NumDataDwords == 1 ? 6272 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6273 6274 MVT MaskPopVT = MaskPopDwords == 1 ? 6275 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6276 6277 SDValue Data(Result, 0); 6278 SDValue TexFail; 6279 6280 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6281 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6282 if (MaskPopVT.isVector()) { 6283 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6284 SDValue(Result, 0), ZeroIdx); 6285 } else { 6286 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6287 SDValue(Result, 0), ZeroIdx); 6288 } 6289 } 6290 6291 if (DataDwordVT.isVector()) 6292 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6293 NumDataDwords - MaskPopDwords); 6294 6295 if (IsD16) 6296 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6297 6298 EVT LegalReqRetVT = ReqRetVT; 6299 if (!ReqRetVT.isVector()) { 6300 if (!Data.getValueType().isInteger()) 6301 Data = DAG.getNode(ISD::BITCAST, DL, 6302 Data.getValueType().changeTypeToInteger(), Data); 6303 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6304 } else { 6305 // We need to widen the return vector to a legal type 6306 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6307 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6308 LegalReqRetVT = 6309 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6310 ReqRetVT.getVectorNumElements() + 1); 6311 } 6312 } 6313 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6314 6315 if (IsTexFail) { 6316 TexFail = 6317 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6318 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6319 6320 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6321 } 6322 6323 if (Result->getNumValues() == 1) 6324 return Data; 6325 6326 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6327 } 6328 6329 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6330 SDValue *LWE, bool &IsTexFail) { 6331 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6332 6333 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6334 if (Value) { 6335 IsTexFail = true; 6336 } 6337 6338 SDLoc DL(TexFailCtrlConst); 6339 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6340 Value &= ~(uint64_t)0x1; 6341 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6342 Value &= ~(uint64_t)0x2; 6343 6344 return Value == 0; 6345 } 6346 6347 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6348 MVT PackVectorVT, 6349 SmallVectorImpl<SDValue> &PackedAddrs, 6350 unsigned DimIdx, unsigned EndIdx, 6351 unsigned NumGradients) { 6352 SDLoc DL(Op); 6353 for (unsigned I = DimIdx; I < EndIdx; I++) { 6354 SDValue Addr = Op.getOperand(I); 6355 6356 // Gradients are packed with undef for each coordinate. 6357 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6358 // 1D: undef,dx/dh; undef,dx/dv 6359 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6360 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6361 if (((I + 1) >= EndIdx) || 6362 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6363 I == DimIdx + NumGradients - 1))) { 6364 if (Addr.getValueType() != MVT::i16) 6365 Addr = DAG.getBitcast(MVT::i16, Addr); 6366 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6367 } else { 6368 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6369 I++; 6370 } 6371 Addr = DAG.getBitcast(MVT::f32, Addr); 6372 PackedAddrs.push_back(Addr); 6373 } 6374 } 6375 6376 SDValue SITargetLowering::lowerImage(SDValue Op, 6377 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6378 SelectionDAG &DAG, bool WithChain) const { 6379 SDLoc DL(Op); 6380 MachineFunction &MF = DAG.getMachineFunction(); 6381 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6382 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6383 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6384 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6385 unsigned IntrOpcode = Intr->BaseOpcode; 6386 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6387 6388 SmallVector<EVT, 3> ResultTypes(Op->values()); 6389 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6390 bool IsD16 = false; 6391 bool IsG16 = false; 6392 bool IsA16 = false; 6393 SDValue VData; 6394 int NumVDataDwords; 6395 bool AdjustRetType = false; 6396 6397 // Offset of intrinsic arguments 6398 const unsigned ArgOffset = WithChain ? 2 : 1; 6399 6400 unsigned DMask; 6401 unsigned DMaskLanes = 0; 6402 6403 if (BaseOpcode->Atomic) { 6404 VData = Op.getOperand(2); 6405 6406 bool Is64Bit = VData.getValueType() == MVT::i64; 6407 if (BaseOpcode->AtomicX2) { 6408 SDValue VData2 = Op.getOperand(3); 6409 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6410 {VData, VData2}); 6411 if (Is64Bit) 6412 VData = DAG.getBitcast(MVT::v4i32, VData); 6413 6414 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6415 DMask = Is64Bit ? 0xf : 0x3; 6416 NumVDataDwords = Is64Bit ? 4 : 2; 6417 } else { 6418 DMask = Is64Bit ? 0x3 : 0x1; 6419 NumVDataDwords = Is64Bit ? 2 : 1; 6420 } 6421 } else { 6422 auto *DMaskConst = 6423 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6424 DMask = DMaskConst->getZExtValue(); 6425 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6426 6427 if (BaseOpcode->Store) { 6428 VData = Op.getOperand(2); 6429 6430 MVT StoreVT = VData.getSimpleValueType(); 6431 if (StoreVT.getScalarType() == MVT::f16) { 6432 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6433 return Op; // D16 is unsupported for this instruction 6434 6435 IsD16 = true; 6436 VData = handleD16VData(VData, DAG, true); 6437 } 6438 6439 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6440 } else { 6441 // Work out the num dwords based on the dmask popcount and underlying type 6442 // and whether packing is supported. 6443 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6444 if (LoadVT.getScalarType() == MVT::f16) { 6445 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6446 return Op; // D16 is unsupported for this instruction 6447 6448 IsD16 = true; 6449 } 6450 6451 // Confirm that the return type is large enough for the dmask specified 6452 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6453 (!LoadVT.isVector() && DMaskLanes > 1)) 6454 return Op; 6455 6456 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6457 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6458 // instructions. 6459 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6460 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6461 NumVDataDwords = (DMaskLanes + 1) / 2; 6462 else 6463 NumVDataDwords = DMaskLanes; 6464 6465 AdjustRetType = true; 6466 } 6467 } 6468 6469 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6470 SmallVector<SDValue, 4> VAddrs; 6471 6472 // Check for 16 bit addresses or derivatives and pack if true. 6473 MVT VAddrVT = 6474 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6475 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6476 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6477 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6478 6479 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6480 VAddrScalarVT = VAddrVT.getScalarType(); 6481 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6482 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6483 6484 // Push back extra arguments. 6485 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6486 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6487 assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument"); 6488 // Special handling of bias when A16 is on. Bias is of type half but 6489 // occupies full 32-bit. 6490 SDValue Bias = DAG.getBuildVector( 6491 MVT::v2f16, DL, 6492 {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6493 VAddrs.push_back(Bias); 6494 } else { 6495 assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) && 6496 "Bias needs to be converted to 16 bit in A16 mode"); 6497 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6498 } 6499 } 6500 6501 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6502 // 16 bit gradients are supported, but are tied to the A16 control 6503 // so both gradients and addresses must be 16 bit 6504 LLVM_DEBUG( 6505 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6506 "require 16 bit args for both gradients and addresses"); 6507 return Op; 6508 } 6509 6510 if (IsA16) { 6511 if (!ST->hasA16()) { 6512 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6513 "support 16 bit addresses\n"); 6514 return Op; 6515 } 6516 } 6517 6518 // We've dealt with incorrect input so we know that if IsA16, IsG16 6519 // are set then we have to compress/pack operands (either address, 6520 // gradient or both) 6521 // In the case where a16 and gradients are tied (no G16 support) then we 6522 // have already verified that both IsA16 and IsG16 are true 6523 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6524 // Activate g16 6525 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6526 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6527 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6528 } 6529 6530 // Add gradients (packed or unpacked) 6531 if (IsG16) { 6532 // Pack the gradients 6533 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6534 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6535 ArgOffset + Intr->GradientStart, 6536 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6537 } else { 6538 for (unsigned I = ArgOffset + Intr->GradientStart; 6539 I < ArgOffset + Intr->CoordStart; I++) 6540 VAddrs.push_back(Op.getOperand(I)); 6541 } 6542 6543 // Add addresses (packed or unpacked) 6544 if (IsA16) { 6545 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6546 ArgOffset + Intr->CoordStart, VAddrEnd, 6547 0 /* No gradients */); 6548 } else { 6549 // Add uncompressed address 6550 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6551 VAddrs.push_back(Op.getOperand(I)); 6552 } 6553 6554 // If the register allocator cannot place the address registers contiguously 6555 // without introducing moves, then using the non-sequential address encoding 6556 // is always preferable, since it saves VALU instructions and is usually a 6557 // wash in terms of code size or even better. 6558 // 6559 // However, we currently have no way of hinting to the register allocator that 6560 // MIMG addresses should be placed contiguously when it is possible to do so, 6561 // so force non-NSA for the common 2-address case as a heuristic. 6562 // 6563 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6564 // allocation when possible. 6565 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6566 VAddrs.size() >= 3 && 6567 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6568 SDValue VAddr; 6569 if (!UseNSA) 6570 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6571 6572 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6573 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6574 SDValue Unorm; 6575 if (!BaseOpcode->Sampler) { 6576 Unorm = True; 6577 } else { 6578 auto UnormConst = 6579 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6580 6581 Unorm = UnormConst->getZExtValue() ? True : False; 6582 } 6583 6584 SDValue TFE; 6585 SDValue LWE; 6586 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6587 bool IsTexFail = false; 6588 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6589 return Op; 6590 6591 if (IsTexFail) { 6592 if (!DMaskLanes) { 6593 // Expecting to get an error flag since TFC is on - and dmask is 0 6594 // Force dmask to be at least 1 otherwise the instruction will fail 6595 DMask = 0x1; 6596 DMaskLanes = 1; 6597 NumVDataDwords = 1; 6598 } 6599 NumVDataDwords += 1; 6600 AdjustRetType = true; 6601 } 6602 6603 // Has something earlier tagged that the return type needs adjusting 6604 // This happens if the instruction is a load or has set TexFailCtrl flags 6605 if (AdjustRetType) { 6606 // NumVDataDwords reflects the true number of dwords required in the return type 6607 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6608 // This is a no-op load. This can be eliminated 6609 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6610 if (isa<MemSDNode>(Op)) 6611 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6612 return Undef; 6613 } 6614 6615 EVT NewVT = NumVDataDwords > 1 ? 6616 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6617 : MVT::i32; 6618 6619 ResultTypes[0] = NewVT; 6620 if (ResultTypes.size() == 3) { 6621 // Original result was aggregate type used for TexFailCtrl results 6622 // The actual instruction returns as a vector type which has now been 6623 // created. Remove the aggregate result. 6624 ResultTypes.erase(&ResultTypes[1]); 6625 } 6626 } 6627 6628 unsigned CPol = cast<ConstantSDNode>( 6629 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6630 if (BaseOpcode->Atomic) 6631 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6632 if (CPol & ~AMDGPU::CPol::ALL) 6633 return Op; 6634 6635 SmallVector<SDValue, 26> Ops; 6636 if (BaseOpcode->Store || BaseOpcode->Atomic) 6637 Ops.push_back(VData); // vdata 6638 if (UseNSA) 6639 append_range(Ops, VAddrs); 6640 else 6641 Ops.push_back(VAddr); 6642 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6643 if (BaseOpcode->Sampler) 6644 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6645 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6646 if (IsGFX10Plus) 6647 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6648 Ops.push_back(Unorm); 6649 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6650 Ops.push_back(IsA16 && // r128, a16 for gfx9 6651 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6652 if (IsGFX10Plus) 6653 Ops.push_back(IsA16 ? True : False); 6654 if (!Subtarget->hasGFX90AInsts()) { 6655 Ops.push_back(TFE); //tfe 6656 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6657 report_fatal_error("TFE is not supported on this GPU"); 6658 } 6659 Ops.push_back(LWE); // lwe 6660 if (!IsGFX10Plus) 6661 Ops.push_back(DimInfo->DA ? True : False); 6662 if (BaseOpcode->HasD16) 6663 Ops.push_back(IsD16 ? True : False); 6664 if (isa<MemSDNode>(Op)) 6665 Ops.push_back(Op.getOperand(0)); // chain 6666 6667 int NumVAddrDwords = 6668 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6669 int Opcode = -1; 6670 6671 if (IsGFX10Plus) { 6672 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6673 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6674 : AMDGPU::MIMGEncGfx10Default, 6675 NumVDataDwords, NumVAddrDwords); 6676 } else { 6677 if (Subtarget->hasGFX90AInsts()) { 6678 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6679 NumVDataDwords, NumVAddrDwords); 6680 if (Opcode == -1) 6681 report_fatal_error( 6682 "requested image instruction is not supported on this GPU"); 6683 } 6684 if (Opcode == -1 && 6685 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6686 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6687 NumVDataDwords, NumVAddrDwords); 6688 if (Opcode == -1) 6689 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6690 NumVDataDwords, NumVAddrDwords); 6691 } 6692 assert(Opcode != -1); 6693 6694 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6695 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6696 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6697 DAG.setNodeMemRefs(NewNode, {MemRef}); 6698 } 6699 6700 if (BaseOpcode->AtomicX2) { 6701 SmallVector<SDValue, 1> Elt; 6702 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6703 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6704 } 6705 if (BaseOpcode->Store) 6706 return SDValue(NewNode, 0); 6707 return constructRetValue(DAG, NewNode, 6708 OrigResultTypes, IsTexFail, 6709 Subtarget->hasUnpackedD16VMem(), IsD16, 6710 DMaskLanes, NumVDataDwords, DL); 6711 } 6712 6713 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6714 SDValue Offset, SDValue CachePolicy, 6715 SelectionDAG &DAG) const { 6716 MachineFunction &MF = DAG.getMachineFunction(); 6717 6718 const DataLayout &DataLayout = DAG.getDataLayout(); 6719 Align Alignment = 6720 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6721 6722 MachineMemOperand *MMO = MF.getMachineMemOperand( 6723 MachinePointerInfo(), 6724 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6725 MachineMemOperand::MOInvariant, 6726 VT.getStoreSize(), Alignment); 6727 6728 if (!Offset->isDivergent()) { 6729 SDValue Ops[] = { 6730 Rsrc, 6731 Offset, // Offset 6732 CachePolicy 6733 }; 6734 6735 // Widen vec3 load to vec4. 6736 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6737 EVT WidenedVT = 6738 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6739 auto WidenedOp = DAG.getMemIntrinsicNode( 6740 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6741 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6742 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6743 DAG.getVectorIdxConstant(0, DL)); 6744 return Subvector; 6745 } 6746 6747 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6748 DAG.getVTList(VT), Ops, VT, MMO); 6749 } 6750 6751 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6752 // assume that the buffer is unswizzled. 6753 SmallVector<SDValue, 4> Loads; 6754 unsigned NumLoads = 1; 6755 MVT LoadVT = VT.getSimpleVT(); 6756 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6757 assert((LoadVT.getScalarType() == MVT::i32 || 6758 LoadVT.getScalarType() == MVT::f32)); 6759 6760 if (NumElts == 8 || NumElts == 16) { 6761 NumLoads = NumElts / 4; 6762 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6763 } 6764 6765 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6766 SDValue Ops[] = { 6767 DAG.getEntryNode(), // Chain 6768 Rsrc, // rsrc 6769 DAG.getConstant(0, DL, MVT::i32), // vindex 6770 {}, // voffset 6771 {}, // soffset 6772 {}, // offset 6773 CachePolicy, // cachepolicy 6774 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6775 }; 6776 6777 // Use the alignment to ensure that the required offsets will fit into the 6778 // immediate offsets. 6779 setBufferOffsets(Offset, DAG, &Ops[3], 6780 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6781 6782 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6783 for (unsigned i = 0; i < NumLoads; ++i) { 6784 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6785 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6786 LoadVT, MMO, DAG)); 6787 } 6788 6789 if (NumElts == 8 || NumElts == 16) 6790 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6791 6792 return Loads[0]; 6793 } 6794 6795 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op, 6796 unsigned Dim, 6797 const ArgDescriptor &Arg) const { 6798 SDLoc SL(Op); 6799 MachineFunction &MF = DAG.getMachineFunction(); 6800 unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim); 6801 if (MaxID == 0) 6802 return DAG.getConstant(0, SL, MVT::i32); 6803 6804 SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6805 SDLoc(DAG.getEntryNode()), Arg); 6806 6807 // Don't bother inserting AssertZext for packed IDs since we're emitting the 6808 // masking operations anyway. 6809 // 6810 // TODO: We could assert the top bit is 0 for the source copy. 6811 if (Arg.isMasked()) 6812 return Val; 6813 6814 // Preserve the known bits after expansion to a copy. 6815 EVT SmallVT = 6816 EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID)); 6817 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val, 6818 DAG.getValueType(SmallVT)); 6819 } 6820 6821 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6822 SelectionDAG &DAG) const { 6823 MachineFunction &MF = DAG.getMachineFunction(); 6824 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6825 6826 EVT VT = Op.getValueType(); 6827 SDLoc DL(Op); 6828 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6829 6830 // TODO: Should this propagate fast-math-flags? 6831 6832 switch (IntrinsicID) { 6833 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6834 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6835 return emitNonHSAIntrinsicError(DAG, DL, VT); 6836 return getPreloadedValue(DAG, *MFI, VT, 6837 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6838 } 6839 case Intrinsic::amdgcn_dispatch_ptr: 6840 case Intrinsic::amdgcn_queue_ptr: { 6841 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6842 DiagnosticInfoUnsupported BadIntrin( 6843 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6844 DL.getDebugLoc()); 6845 DAG.getContext()->diagnose(BadIntrin); 6846 return DAG.getUNDEF(VT); 6847 } 6848 6849 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6850 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6851 return getPreloadedValue(DAG, *MFI, VT, RegID); 6852 } 6853 case Intrinsic::amdgcn_implicitarg_ptr: { 6854 if (MFI->isEntryFunction()) 6855 return getImplicitArgPtr(DAG, DL); 6856 return getPreloadedValue(DAG, *MFI, VT, 6857 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6858 } 6859 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6860 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6861 // This only makes sense to call in a kernel, so just lower to null. 6862 return DAG.getConstant(0, DL, VT); 6863 } 6864 6865 return getPreloadedValue(DAG, *MFI, VT, 6866 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6867 } 6868 case Intrinsic::amdgcn_dispatch_id: { 6869 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6870 } 6871 case Intrinsic::amdgcn_rcp: 6872 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6873 case Intrinsic::amdgcn_rsq: 6874 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6875 case Intrinsic::amdgcn_rsq_legacy: 6876 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6877 return emitRemovedIntrinsicError(DAG, DL, VT); 6878 return SDValue(); 6879 case Intrinsic::amdgcn_rcp_legacy: 6880 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6881 return emitRemovedIntrinsicError(DAG, DL, VT); 6882 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6883 case Intrinsic::amdgcn_rsq_clamp: { 6884 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6885 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6886 6887 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6888 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6889 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6890 6891 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6892 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6893 DAG.getConstantFP(Max, DL, VT)); 6894 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6895 DAG.getConstantFP(Min, DL, VT)); 6896 } 6897 case Intrinsic::r600_read_ngroups_x: 6898 if (Subtarget->isAmdHsaOS()) 6899 return emitNonHSAIntrinsicError(DAG, DL, VT); 6900 6901 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6902 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6903 false); 6904 case Intrinsic::r600_read_ngroups_y: 6905 if (Subtarget->isAmdHsaOS()) 6906 return emitNonHSAIntrinsicError(DAG, DL, VT); 6907 6908 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6909 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6910 false); 6911 case Intrinsic::r600_read_ngroups_z: 6912 if (Subtarget->isAmdHsaOS()) 6913 return emitNonHSAIntrinsicError(DAG, DL, VT); 6914 6915 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6916 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6917 false); 6918 case Intrinsic::r600_read_global_size_x: 6919 if (Subtarget->isAmdHsaOS()) 6920 return emitNonHSAIntrinsicError(DAG, DL, VT); 6921 6922 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6923 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6924 Align(4), false); 6925 case Intrinsic::r600_read_global_size_y: 6926 if (Subtarget->isAmdHsaOS()) 6927 return emitNonHSAIntrinsicError(DAG, DL, VT); 6928 6929 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6930 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6931 Align(4), false); 6932 case Intrinsic::r600_read_global_size_z: 6933 if (Subtarget->isAmdHsaOS()) 6934 return emitNonHSAIntrinsicError(DAG, DL, VT); 6935 6936 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6937 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6938 Align(4), false); 6939 case Intrinsic::r600_read_local_size_x: 6940 if (Subtarget->isAmdHsaOS()) 6941 return emitNonHSAIntrinsicError(DAG, DL, VT); 6942 6943 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6944 SI::KernelInputOffsets::LOCAL_SIZE_X); 6945 case Intrinsic::r600_read_local_size_y: 6946 if (Subtarget->isAmdHsaOS()) 6947 return emitNonHSAIntrinsicError(DAG, DL, VT); 6948 6949 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6950 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6951 case Intrinsic::r600_read_local_size_z: 6952 if (Subtarget->isAmdHsaOS()) 6953 return emitNonHSAIntrinsicError(DAG, DL, VT); 6954 6955 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6956 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6957 case Intrinsic::amdgcn_workgroup_id_x: 6958 return getPreloadedValue(DAG, *MFI, VT, 6959 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6960 case Intrinsic::amdgcn_workgroup_id_y: 6961 return getPreloadedValue(DAG, *MFI, VT, 6962 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6963 case Intrinsic::amdgcn_workgroup_id_z: 6964 return getPreloadedValue(DAG, *MFI, VT, 6965 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6966 case Intrinsic::amdgcn_workitem_id_x: 6967 return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX); 6968 case Intrinsic::amdgcn_workitem_id_y: 6969 return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY); 6970 case Intrinsic::amdgcn_workitem_id_z: 6971 return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ); 6972 case Intrinsic::amdgcn_wavefrontsize: 6973 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6974 SDLoc(Op), MVT::i32); 6975 case Intrinsic::amdgcn_s_buffer_load: { 6976 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6977 if (CPol & ~AMDGPU::CPol::ALL) 6978 return Op; 6979 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6980 DAG); 6981 } 6982 case Intrinsic::amdgcn_fdiv_fast: 6983 return lowerFDIV_FAST(Op, DAG); 6984 case Intrinsic::amdgcn_sin: 6985 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6986 6987 case Intrinsic::amdgcn_cos: 6988 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6989 6990 case Intrinsic::amdgcn_mul_u24: 6991 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6992 case Intrinsic::amdgcn_mul_i24: 6993 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6994 6995 case Intrinsic::amdgcn_log_clamp: { 6996 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6997 return SDValue(); 6998 6999 return emitRemovedIntrinsicError(DAG, DL, VT); 7000 } 7001 case Intrinsic::amdgcn_ldexp: 7002 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 7003 Op.getOperand(1), Op.getOperand(2)); 7004 7005 case Intrinsic::amdgcn_fract: 7006 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 7007 7008 case Intrinsic::amdgcn_class: 7009 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 7010 Op.getOperand(1), Op.getOperand(2)); 7011 case Intrinsic::amdgcn_div_fmas: 7012 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 7013 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 7014 Op.getOperand(4)); 7015 7016 case Intrinsic::amdgcn_div_fixup: 7017 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 7018 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7019 7020 case Intrinsic::amdgcn_div_scale: { 7021 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 7022 7023 // Translate to the operands expected by the machine instruction. The 7024 // first parameter must be the same as the first instruction. 7025 SDValue Numerator = Op.getOperand(1); 7026 SDValue Denominator = Op.getOperand(2); 7027 7028 // Note this order is opposite of the machine instruction's operations, 7029 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 7030 // intrinsic has the numerator as the first operand to match a normal 7031 // division operation. 7032 7033 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 7034 7035 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 7036 Denominator, Numerator); 7037 } 7038 case Intrinsic::amdgcn_icmp: { 7039 // There is a Pat that handles this variant, so return it as-is. 7040 if (Op.getOperand(1).getValueType() == MVT::i1 && 7041 Op.getConstantOperandVal(2) == 0 && 7042 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 7043 return Op; 7044 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 7045 } 7046 case Intrinsic::amdgcn_fcmp: { 7047 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 7048 } 7049 case Intrinsic::amdgcn_ballot: 7050 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 7051 case Intrinsic::amdgcn_fmed3: 7052 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 7053 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7054 case Intrinsic::amdgcn_fdot2: 7055 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 7056 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 7057 Op.getOperand(4)); 7058 case Intrinsic::amdgcn_fmul_legacy: 7059 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 7060 Op.getOperand(1), Op.getOperand(2)); 7061 case Intrinsic::amdgcn_sffbh: 7062 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 7063 case Intrinsic::amdgcn_sbfe: 7064 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 7065 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7066 case Intrinsic::amdgcn_ubfe: 7067 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 7068 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 7069 case Intrinsic::amdgcn_cvt_pkrtz: 7070 case Intrinsic::amdgcn_cvt_pknorm_i16: 7071 case Intrinsic::amdgcn_cvt_pknorm_u16: 7072 case Intrinsic::amdgcn_cvt_pk_i16: 7073 case Intrinsic::amdgcn_cvt_pk_u16: { 7074 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 7075 EVT VT = Op.getValueType(); 7076 unsigned Opcode; 7077 7078 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 7079 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 7080 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 7081 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 7082 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 7083 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 7084 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 7085 Opcode = AMDGPUISD::CVT_PK_I16_I32; 7086 else 7087 Opcode = AMDGPUISD::CVT_PK_U16_U32; 7088 7089 if (isTypeLegal(VT)) 7090 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 7091 7092 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 7093 Op.getOperand(1), Op.getOperand(2)); 7094 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 7095 } 7096 case Intrinsic::amdgcn_fmad_ftz: 7097 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 7098 Op.getOperand(2), Op.getOperand(3)); 7099 7100 case Intrinsic::amdgcn_if_break: 7101 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 7102 Op->getOperand(1), Op->getOperand(2)), 0); 7103 7104 case Intrinsic::amdgcn_groupstaticsize: { 7105 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 7106 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 7107 return Op; 7108 7109 const Module *M = MF.getFunction().getParent(); 7110 const GlobalValue *GV = 7111 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 7112 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 7113 SIInstrInfo::MO_ABS32_LO); 7114 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7115 } 7116 case Intrinsic::amdgcn_is_shared: 7117 case Intrinsic::amdgcn_is_private: { 7118 SDLoc SL(Op); 7119 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 7120 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 7121 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 7122 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 7123 Op.getOperand(1)); 7124 7125 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 7126 DAG.getConstant(1, SL, MVT::i32)); 7127 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 7128 } 7129 case Intrinsic::amdgcn_perm: 7130 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 7131 Op.getOperand(2), Op.getOperand(3)); 7132 case Intrinsic::amdgcn_reloc_constant: { 7133 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 7134 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 7135 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 7136 auto RelocSymbol = cast<GlobalVariable>( 7137 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 7138 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 7139 SIInstrInfo::MO_ABS32_LO); 7140 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 7141 } 7142 default: 7143 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7144 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7145 return lowerImage(Op, ImageDimIntr, DAG, false); 7146 7147 return Op; 7148 } 7149 } 7150 7151 /// Update \p MMO based on the offset inputs to an intrinsic. 7152 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 7153 SDValue SOffset, SDValue Offset, 7154 SDValue VIndex = SDValue()) { 7155 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 7156 !isa<ConstantSDNode>(Offset)) { 7157 // The combined offset is not known to be constant, so we cannot represent 7158 // it in the MMO. Give up. 7159 MMO->setValue((Value *)nullptr); 7160 return; 7161 } 7162 7163 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 7164 !cast<ConstantSDNode>(VIndex)->isZero())) { 7165 // The strided index component of the address is not known to be zero, so we 7166 // cannot represent it in the MMO. Give up. 7167 MMO->setValue((Value *)nullptr); 7168 return; 7169 } 7170 7171 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 7172 cast<ConstantSDNode>(SOffset)->getSExtValue() + 7173 cast<ConstantSDNode>(Offset)->getSExtValue()); 7174 } 7175 7176 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 7177 SelectionDAG &DAG, 7178 unsigned NewOpcode) const { 7179 SDLoc DL(Op); 7180 7181 SDValue VData = Op.getOperand(2); 7182 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7183 SDValue Ops[] = { 7184 Op.getOperand(0), // Chain 7185 VData, // vdata 7186 Op.getOperand(3), // rsrc 7187 DAG.getConstant(0, DL, MVT::i32), // vindex 7188 Offsets.first, // voffset 7189 Op.getOperand(5), // soffset 7190 Offsets.second, // offset 7191 Op.getOperand(6), // cachepolicy 7192 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7193 }; 7194 7195 auto *M = cast<MemSDNode>(Op); 7196 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7197 7198 EVT MemVT = VData.getValueType(); 7199 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7200 M->getMemOperand()); 7201 } 7202 7203 // Return a value to use for the idxen operand by examining the vindex operand. 7204 static unsigned getIdxEn(SDValue VIndex) { 7205 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7206 // No need to set idxen if vindex is known to be zero. 7207 return VIndexC->getZExtValue() != 0; 7208 return 1; 7209 } 7210 7211 SDValue 7212 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7213 unsigned NewOpcode) const { 7214 SDLoc DL(Op); 7215 7216 SDValue VData = Op.getOperand(2); 7217 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7218 SDValue Ops[] = { 7219 Op.getOperand(0), // Chain 7220 VData, // vdata 7221 Op.getOperand(3), // rsrc 7222 Op.getOperand(4), // vindex 7223 Offsets.first, // voffset 7224 Op.getOperand(6), // soffset 7225 Offsets.second, // offset 7226 Op.getOperand(7), // cachepolicy 7227 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7228 }; 7229 7230 auto *M = cast<MemSDNode>(Op); 7231 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7232 7233 EVT MemVT = VData.getValueType(); 7234 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7235 M->getMemOperand()); 7236 } 7237 7238 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7239 SelectionDAG &DAG) const { 7240 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7241 SDLoc DL(Op); 7242 7243 switch (IntrID) { 7244 case Intrinsic::amdgcn_ds_ordered_add: 7245 case Intrinsic::amdgcn_ds_ordered_swap: { 7246 MemSDNode *M = cast<MemSDNode>(Op); 7247 SDValue Chain = M->getOperand(0); 7248 SDValue M0 = M->getOperand(2); 7249 SDValue Value = M->getOperand(3); 7250 unsigned IndexOperand = M->getConstantOperandVal(7); 7251 unsigned WaveRelease = M->getConstantOperandVal(8); 7252 unsigned WaveDone = M->getConstantOperandVal(9); 7253 7254 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7255 IndexOperand &= ~0x3f; 7256 unsigned CountDw = 0; 7257 7258 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7259 CountDw = (IndexOperand >> 24) & 0xf; 7260 IndexOperand &= ~(0xf << 24); 7261 7262 if (CountDw < 1 || CountDw > 4) { 7263 report_fatal_error( 7264 "ds_ordered_count: dword count must be between 1 and 4"); 7265 } 7266 } 7267 7268 if (IndexOperand) 7269 report_fatal_error("ds_ordered_count: bad index operand"); 7270 7271 if (WaveDone && !WaveRelease) 7272 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7273 7274 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7275 unsigned ShaderType = 7276 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7277 unsigned Offset0 = OrderedCountIndex << 2; 7278 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7279 (Instruction << 4); 7280 7281 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7282 Offset1 |= (CountDw - 1) << 6; 7283 7284 unsigned Offset = Offset0 | (Offset1 << 8); 7285 7286 SDValue Ops[] = { 7287 Chain, 7288 Value, 7289 DAG.getTargetConstant(Offset, DL, MVT::i16), 7290 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7291 }; 7292 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7293 M->getVTList(), Ops, M->getMemoryVT(), 7294 M->getMemOperand()); 7295 } 7296 case Intrinsic::amdgcn_ds_fadd: { 7297 MemSDNode *M = cast<MemSDNode>(Op); 7298 unsigned Opc; 7299 switch (IntrID) { 7300 case Intrinsic::amdgcn_ds_fadd: 7301 Opc = ISD::ATOMIC_LOAD_FADD; 7302 break; 7303 } 7304 7305 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7306 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7307 M->getMemOperand()); 7308 } 7309 case Intrinsic::amdgcn_atomic_inc: 7310 case Intrinsic::amdgcn_atomic_dec: 7311 case Intrinsic::amdgcn_ds_fmin: 7312 case Intrinsic::amdgcn_ds_fmax: { 7313 MemSDNode *M = cast<MemSDNode>(Op); 7314 unsigned Opc; 7315 switch (IntrID) { 7316 case Intrinsic::amdgcn_atomic_inc: 7317 Opc = AMDGPUISD::ATOMIC_INC; 7318 break; 7319 case Intrinsic::amdgcn_atomic_dec: 7320 Opc = AMDGPUISD::ATOMIC_DEC; 7321 break; 7322 case Intrinsic::amdgcn_ds_fmin: 7323 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7324 break; 7325 case Intrinsic::amdgcn_ds_fmax: 7326 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7327 break; 7328 default: 7329 llvm_unreachable("Unknown intrinsic!"); 7330 } 7331 SDValue Ops[] = { 7332 M->getOperand(0), // Chain 7333 M->getOperand(2), // Ptr 7334 M->getOperand(3) // Value 7335 }; 7336 7337 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7338 M->getMemoryVT(), M->getMemOperand()); 7339 } 7340 case Intrinsic::amdgcn_buffer_load: 7341 case Intrinsic::amdgcn_buffer_load_format: { 7342 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7343 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->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 SDValue(), // voffset -- will be set by setBufferOffsets 7350 SDValue(), // soffset -- will be set by setBufferOffsets 7351 SDValue(), // offset -- will be set by setBufferOffsets 7352 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7353 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7354 }; 7355 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7356 7357 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7358 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7359 7360 EVT VT = Op.getValueType(); 7361 EVT IntVT = VT.changeTypeToInteger(); 7362 auto *M = cast<MemSDNode>(Op); 7363 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7364 EVT LoadVT = Op.getValueType(); 7365 7366 if (LoadVT.getScalarType() == MVT::f16) 7367 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7368 M, DAG, Ops); 7369 7370 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7371 if (LoadVT.getScalarType() == MVT::i8 || 7372 LoadVT.getScalarType() == MVT::i16) 7373 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7374 7375 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7376 M->getMemOperand(), DAG); 7377 } 7378 case Intrinsic::amdgcn_raw_buffer_load: 7379 case Intrinsic::amdgcn_raw_buffer_load_format: { 7380 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7381 7382 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7383 SDValue Ops[] = { 7384 Op.getOperand(0), // Chain 7385 Op.getOperand(2), // rsrc 7386 DAG.getConstant(0, DL, MVT::i32), // vindex 7387 Offsets.first, // voffset 7388 Op.getOperand(4), // soffset 7389 Offsets.second, // offset 7390 Op.getOperand(5), // cachepolicy, swizzled buffer 7391 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7392 }; 7393 7394 auto *M = cast<MemSDNode>(Op); 7395 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7396 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7397 } 7398 case Intrinsic::amdgcn_struct_buffer_load: 7399 case Intrinsic::amdgcn_struct_buffer_load_format: { 7400 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7401 7402 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7403 SDValue Ops[] = { 7404 Op.getOperand(0), // Chain 7405 Op.getOperand(2), // rsrc 7406 Op.getOperand(3), // vindex 7407 Offsets.first, // voffset 7408 Op.getOperand(5), // soffset 7409 Offsets.second, // offset 7410 Op.getOperand(6), // cachepolicy, swizzled buffer 7411 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7412 }; 7413 7414 auto *M = cast<MemSDNode>(Op); 7415 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7416 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7417 } 7418 case Intrinsic::amdgcn_tbuffer_load: { 7419 MemSDNode *M = cast<MemSDNode>(Op); 7420 EVT LoadVT = Op.getValueType(); 7421 7422 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7423 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7424 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7425 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7426 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7427 SDValue Ops[] = { 7428 Op.getOperand(0), // Chain 7429 Op.getOperand(2), // rsrc 7430 Op.getOperand(3), // vindex 7431 Op.getOperand(4), // voffset 7432 Op.getOperand(5), // soffset 7433 Op.getOperand(6), // offset 7434 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7435 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7436 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7437 }; 7438 7439 if (LoadVT.getScalarType() == MVT::f16) 7440 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7441 M, DAG, Ops); 7442 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7443 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7444 DAG); 7445 } 7446 case Intrinsic::amdgcn_raw_tbuffer_load: { 7447 MemSDNode *M = cast<MemSDNode>(Op); 7448 EVT LoadVT = Op.getValueType(); 7449 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7450 7451 SDValue Ops[] = { 7452 Op.getOperand(0), // Chain 7453 Op.getOperand(2), // rsrc 7454 DAG.getConstant(0, DL, MVT::i32), // vindex 7455 Offsets.first, // voffset 7456 Op.getOperand(4), // soffset 7457 Offsets.second, // offset 7458 Op.getOperand(5), // format 7459 Op.getOperand(6), // cachepolicy, swizzled buffer 7460 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7461 }; 7462 7463 if (LoadVT.getScalarType() == MVT::f16) 7464 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7465 M, DAG, Ops); 7466 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7467 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7468 DAG); 7469 } 7470 case Intrinsic::amdgcn_struct_tbuffer_load: { 7471 MemSDNode *M = cast<MemSDNode>(Op); 7472 EVT LoadVT = Op.getValueType(); 7473 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7474 7475 SDValue Ops[] = { 7476 Op.getOperand(0), // Chain 7477 Op.getOperand(2), // rsrc 7478 Op.getOperand(3), // vindex 7479 Offsets.first, // voffset 7480 Op.getOperand(5), // soffset 7481 Offsets.second, // offset 7482 Op.getOperand(6), // format 7483 Op.getOperand(7), // cachepolicy, swizzled buffer 7484 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7485 }; 7486 7487 if (LoadVT.getScalarType() == MVT::f16) 7488 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7489 M, DAG, Ops); 7490 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7491 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7492 DAG); 7493 } 7494 case Intrinsic::amdgcn_buffer_atomic_swap: 7495 case Intrinsic::amdgcn_buffer_atomic_add: 7496 case Intrinsic::amdgcn_buffer_atomic_sub: 7497 case Intrinsic::amdgcn_buffer_atomic_csub: 7498 case Intrinsic::amdgcn_buffer_atomic_smin: 7499 case Intrinsic::amdgcn_buffer_atomic_umin: 7500 case Intrinsic::amdgcn_buffer_atomic_smax: 7501 case Intrinsic::amdgcn_buffer_atomic_umax: 7502 case Intrinsic::amdgcn_buffer_atomic_and: 7503 case Intrinsic::amdgcn_buffer_atomic_or: 7504 case Intrinsic::amdgcn_buffer_atomic_xor: 7505 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7506 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7507 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7508 SDValue Ops[] = { 7509 Op.getOperand(0), // Chain 7510 Op.getOperand(2), // vdata 7511 Op.getOperand(3), // rsrc 7512 Op.getOperand(4), // vindex 7513 SDValue(), // voffset -- will be set by setBufferOffsets 7514 SDValue(), // soffset -- will be set by setBufferOffsets 7515 SDValue(), // offset -- will be set by setBufferOffsets 7516 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7517 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7518 }; 7519 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7520 7521 EVT VT = Op.getValueType(); 7522 7523 auto *M = cast<MemSDNode>(Op); 7524 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7525 unsigned Opcode = 0; 7526 7527 switch (IntrID) { 7528 case Intrinsic::amdgcn_buffer_atomic_swap: 7529 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7530 break; 7531 case Intrinsic::amdgcn_buffer_atomic_add: 7532 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7533 break; 7534 case Intrinsic::amdgcn_buffer_atomic_sub: 7535 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7536 break; 7537 case Intrinsic::amdgcn_buffer_atomic_csub: 7538 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7539 break; 7540 case Intrinsic::amdgcn_buffer_atomic_smin: 7541 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7542 break; 7543 case Intrinsic::amdgcn_buffer_atomic_umin: 7544 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7545 break; 7546 case Intrinsic::amdgcn_buffer_atomic_smax: 7547 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7548 break; 7549 case Intrinsic::amdgcn_buffer_atomic_umax: 7550 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7551 break; 7552 case Intrinsic::amdgcn_buffer_atomic_and: 7553 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7554 break; 7555 case Intrinsic::amdgcn_buffer_atomic_or: 7556 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7557 break; 7558 case Intrinsic::amdgcn_buffer_atomic_xor: 7559 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7560 break; 7561 case Intrinsic::amdgcn_buffer_atomic_fadd: 7562 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7563 DiagnosticInfoUnsupported 7564 NoFpRet(DAG.getMachineFunction().getFunction(), 7565 "return versions of fp atomics not supported", 7566 DL.getDebugLoc(), DS_Error); 7567 DAG.getContext()->diagnose(NoFpRet); 7568 return SDValue(); 7569 } 7570 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7571 break; 7572 default: 7573 llvm_unreachable("unhandled atomic opcode"); 7574 } 7575 7576 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7577 M->getMemOperand()); 7578 } 7579 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7580 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7581 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7582 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7583 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7584 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7585 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7586 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7587 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7588 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7589 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7590 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7591 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7592 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7593 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7594 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7595 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7596 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7597 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7598 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7599 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7600 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7601 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7602 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7603 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7604 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7605 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7606 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7607 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7608 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7609 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7610 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7611 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7612 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7613 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7614 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7615 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7616 return lowerStructBufferAtomicIntrin(Op, DAG, 7617 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7618 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7619 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7620 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7621 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7622 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7623 return lowerStructBufferAtomicIntrin(Op, DAG, 7624 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7625 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7626 return lowerStructBufferAtomicIntrin(Op, DAG, 7627 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7628 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7629 return lowerStructBufferAtomicIntrin(Op, DAG, 7630 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7631 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7632 return lowerStructBufferAtomicIntrin(Op, DAG, 7633 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7634 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7635 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7636 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7637 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7638 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7639 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7640 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7641 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7642 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7643 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7644 7645 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7646 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7647 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7648 SDValue Ops[] = { 7649 Op.getOperand(0), // Chain 7650 Op.getOperand(2), // src 7651 Op.getOperand(3), // cmp 7652 Op.getOperand(4), // rsrc 7653 Op.getOperand(5), // vindex 7654 SDValue(), // voffset -- will be set by setBufferOffsets 7655 SDValue(), // soffset -- will be set by setBufferOffsets 7656 SDValue(), // offset -- will be set by setBufferOffsets 7657 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7658 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7659 }; 7660 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7661 7662 EVT VT = Op.getValueType(); 7663 auto *M = cast<MemSDNode>(Op); 7664 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7665 7666 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7667 Op->getVTList(), Ops, VT, M->getMemOperand()); 7668 } 7669 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7670 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7671 SDValue Ops[] = { 7672 Op.getOperand(0), // Chain 7673 Op.getOperand(2), // src 7674 Op.getOperand(3), // cmp 7675 Op.getOperand(4), // rsrc 7676 DAG.getConstant(0, DL, MVT::i32), // vindex 7677 Offsets.first, // voffset 7678 Op.getOperand(6), // soffset 7679 Offsets.second, // offset 7680 Op.getOperand(7), // cachepolicy 7681 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7682 }; 7683 EVT VT = Op.getValueType(); 7684 auto *M = cast<MemSDNode>(Op); 7685 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7686 7687 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7688 Op->getVTList(), Ops, VT, M->getMemOperand()); 7689 } 7690 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7691 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7692 SDValue Ops[] = { 7693 Op.getOperand(0), // Chain 7694 Op.getOperand(2), // src 7695 Op.getOperand(3), // cmp 7696 Op.getOperand(4), // rsrc 7697 Op.getOperand(5), // vindex 7698 Offsets.first, // voffset 7699 Op.getOperand(7), // soffset 7700 Offsets.second, // offset 7701 Op.getOperand(8), // cachepolicy 7702 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7703 }; 7704 EVT VT = Op.getValueType(); 7705 auto *M = cast<MemSDNode>(Op); 7706 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7707 7708 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7709 Op->getVTList(), Ops, VT, M->getMemOperand()); 7710 } 7711 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7712 MemSDNode *M = cast<MemSDNode>(Op); 7713 SDValue NodePtr = M->getOperand(2); 7714 SDValue RayExtent = M->getOperand(3); 7715 SDValue RayOrigin = M->getOperand(4); 7716 SDValue RayDir = M->getOperand(5); 7717 SDValue RayInvDir = M->getOperand(6); 7718 SDValue TDescr = M->getOperand(7); 7719 7720 assert(NodePtr.getValueType() == MVT::i32 || 7721 NodePtr.getValueType() == MVT::i64); 7722 assert(RayDir.getValueType() == MVT::v3f16 || 7723 RayDir.getValueType() == MVT::v3f32); 7724 7725 if (!Subtarget->hasGFX10_AEncoding()) { 7726 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7727 return SDValue(); 7728 } 7729 7730 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7731 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7732 const unsigned NumVDataDwords = 4; 7733 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7734 const bool UseNSA = Subtarget->hasNSAEncoding() && 7735 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7736 const unsigned BaseOpcodes[2][2] = { 7737 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7738 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7739 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7740 int Opcode; 7741 if (UseNSA) { 7742 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7743 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7744 NumVAddrDwords); 7745 } else { 7746 Opcode = AMDGPU::getMIMGOpcode( 7747 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7748 PowerOf2Ceil(NumVAddrDwords)); 7749 } 7750 assert(Opcode != -1); 7751 7752 SmallVector<SDValue, 16> Ops; 7753 7754 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7755 SmallVector<SDValue, 3> Lanes; 7756 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7757 if (Lanes[0].getValueSizeInBits() == 32) { 7758 for (unsigned I = 0; I < 3; ++I) 7759 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7760 } else { 7761 if (IsAligned) { 7762 Ops.push_back( 7763 DAG.getBitcast(MVT::i32, 7764 DAG.getBuildVector(MVT::v2f16, DL, 7765 { Lanes[0], Lanes[1] }))); 7766 Ops.push_back(Lanes[2]); 7767 } else { 7768 SDValue Elt0 = Ops.pop_back_val(); 7769 Ops.push_back( 7770 DAG.getBitcast(MVT::i32, 7771 DAG.getBuildVector(MVT::v2f16, DL, 7772 { Elt0, Lanes[0] }))); 7773 Ops.push_back( 7774 DAG.getBitcast(MVT::i32, 7775 DAG.getBuildVector(MVT::v2f16, DL, 7776 { Lanes[1], Lanes[2] }))); 7777 } 7778 } 7779 }; 7780 7781 if (Is64) 7782 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7783 else 7784 Ops.push_back(NodePtr); 7785 7786 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7787 packLanes(RayOrigin, true); 7788 packLanes(RayDir, true); 7789 packLanes(RayInvDir, false); 7790 7791 if (!UseNSA) { 7792 // Build a single vector containing all the operands so far prepared. 7793 if (NumVAddrDwords > 8) { 7794 SDValue Undef = DAG.getUNDEF(MVT::i32); 7795 Ops.append(16 - Ops.size(), Undef); 7796 } 7797 assert(Ops.size() == 8 || Ops.size() == 16); 7798 SDValue MergedOps = DAG.getBuildVector( 7799 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7800 Ops.clear(); 7801 Ops.push_back(MergedOps); 7802 } 7803 7804 Ops.push_back(TDescr); 7805 if (IsA16) 7806 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7807 Ops.push_back(M->getChain()); 7808 7809 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7810 MachineMemOperand *MemRef = M->getMemOperand(); 7811 DAG.setNodeMemRefs(NewNode, {MemRef}); 7812 return SDValue(NewNode, 0); 7813 } 7814 case Intrinsic::amdgcn_global_atomic_fadd: 7815 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7816 DiagnosticInfoUnsupported 7817 NoFpRet(DAG.getMachineFunction().getFunction(), 7818 "return versions of fp atomics not supported", 7819 DL.getDebugLoc(), DS_Error); 7820 DAG.getContext()->diagnose(NoFpRet); 7821 return SDValue(); 7822 } 7823 LLVM_FALLTHROUGH; 7824 case Intrinsic::amdgcn_global_atomic_fmin: 7825 case Intrinsic::amdgcn_global_atomic_fmax: 7826 case Intrinsic::amdgcn_flat_atomic_fadd: 7827 case Intrinsic::amdgcn_flat_atomic_fmin: 7828 case Intrinsic::amdgcn_flat_atomic_fmax: { 7829 MemSDNode *M = cast<MemSDNode>(Op); 7830 SDValue Ops[] = { 7831 M->getOperand(0), // Chain 7832 M->getOperand(2), // Ptr 7833 M->getOperand(3) // Value 7834 }; 7835 unsigned Opcode = 0; 7836 switch (IntrID) { 7837 case Intrinsic::amdgcn_global_atomic_fadd: 7838 case Intrinsic::amdgcn_flat_atomic_fadd: { 7839 EVT VT = Op.getOperand(3).getValueType(); 7840 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7841 DAG.getVTList(VT, MVT::Other), Ops, 7842 M->getMemOperand()); 7843 } 7844 case Intrinsic::amdgcn_global_atomic_fmin: 7845 case Intrinsic::amdgcn_flat_atomic_fmin: { 7846 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7847 break; 7848 } 7849 case Intrinsic::amdgcn_global_atomic_fmax: 7850 case Intrinsic::amdgcn_flat_atomic_fmax: { 7851 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7852 break; 7853 } 7854 default: 7855 llvm_unreachable("unhandled atomic opcode"); 7856 } 7857 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7858 M->getVTList(), Ops, M->getMemoryVT(), 7859 M->getMemOperand()); 7860 } 7861 default: 7862 7863 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7864 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7865 return lowerImage(Op, ImageDimIntr, DAG, true); 7866 7867 return SDValue(); 7868 } 7869 } 7870 7871 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7872 // dwordx4 if on SI. 7873 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7874 SDVTList VTList, 7875 ArrayRef<SDValue> Ops, EVT MemVT, 7876 MachineMemOperand *MMO, 7877 SelectionDAG &DAG) const { 7878 EVT VT = VTList.VTs[0]; 7879 EVT WidenedVT = VT; 7880 EVT WidenedMemVT = MemVT; 7881 if (!Subtarget->hasDwordx3LoadStores() && 7882 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7883 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7884 WidenedVT.getVectorElementType(), 4); 7885 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7886 WidenedMemVT.getVectorElementType(), 4); 7887 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7888 } 7889 7890 assert(VTList.NumVTs == 2); 7891 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7892 7893 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7894 WidenedMemVT, MMO); 7895 if (WidenedVT != VT) { 7896 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7897 DAG.getVectorIdxConstant(0, DL)); 7898 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7899 } 7900 return NewOp; 7901 } 7902 7903 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7904 bool ImageStore) const { 7905 EVT StoreVT = VData.getValueType(); 7906 7907 // No change for f16 and legal vector D16 types. 7908 if (!StoreVT.isVector()) 7909 return VData; 7910 7911 SDLoc DL(VData); 7912 unsigned NumElements = StoreVT.getVectorNumElements(); 7913 7914 if (Subtarget->hasUnpackedD16VMem()) { 7915 // We need to unpack the packed data to store. 7916 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7917 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7918 7919 EVT EquivStoreVT = 7920 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7921 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7922 return DAG.UnrollVectorOp(ZExt.getNode()); 7923 } 7924 7925 // The sq block of gfx8.1 does not estimate register use correctly for d16 7926 // image store instructions. The data operand is computed as if it were not a 7927 // d16 image instruction. 7928 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7929 // Bitcast to i16 7930 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7931 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7932 7933 // Decompose into scalars 7934 SmallVector<SDValue, 4> Elts; 7935 DAG.ExtractVectorElements(IntVData, Elts); 7936 7937 // Group pairs of i16 into v2i16 and bitcast to i32 7938 SmallVector<SDValue, 4> PackedElts; 7939 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7940 SDValue Pair = 7941 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7942 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7943 PackedElts.push_back(IntPair); 7944 } 7945 if ((NumElements % 2) == 1) { 7946 // Handle v3i16 7947 unsigned I = Elts.size() / 2; 7948 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7949 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7950 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7951 PackedElts.push_back(IntPair); 7952 } 7953 7954 // Pad using UNDEF 7955 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7956 7957 // Build final vector 7958 EVT VecVT = 7959 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7960 return DAG.getBuildVector(VecVT, DL, PackedElts); 7961 } 7962 7963 if (NumElements == 3) { 7964 EVT IntStoreVT = 7965 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7966 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7967 7968 EVT WidenedStoreVT = EVT::getVectorVT( 7969 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7970 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7971 WidenedStoreVT.getStoreSizeInBits()); 7972 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7973 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7974 } 7975 7976 assert(isTypeLegal(StoreVT)); 7977 return VData; 7978 } 7979 7980 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7981 SelectionDAG &DAG) const { 7982 SDLoc DL(Op); 7983 SDValue Chain = Op.getOperand(0); 7984 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7985 MachineFunction &MF = DAG.getMachineFunction(); 7986 7987 switch (IntrinsicID) { 7988 case Intrinsic::amdgcn_exp_compr: { 7989 SDValue Src0 = Op.getOperand(4); 7990 SDValue Src1 = Op.getOperand(5); 7991 // Hack around illegal type on SI by directly selecting it. 7992 if (isTypeLegal(Src0.getValueType())) 7993 return SDValue(); 7994 7995 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7996 SDValue Undef = DAG.getUNDEF(MVT::f32); 7997 const SDValue Ops[] = { 7998 Op.getOperand(2), // tgt 7999 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 8000 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 8001 Undef, // src2 8002 Undef, // src3 8003 Op.getOperand(7), // vm 8004 DAG.getTargetConstant(1, DL, MVT::i1), // compr 8005 Op.getOperand(3), // en 8006 Op.getOperand(0) // Chain 8007 }; 8008 8009 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 8010 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 8011 } 8012 case Intrinsic::amdgcn_s_barrier: { 8013 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 8014 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 8015 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 8016 if (WGSize <= ST.getWavefrontSize()) 8017 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 8018 Op.getOperand(0)), 0); 8019 } 8020 return SDValue(); 8021 }; 8022 case Intrinsic::amdgcn_tbuffer_store: { 8023 SDValue VData = Op.getOperand(2); 8024 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8025 if (IsD16) 8026 VData = handleD16VData(VData, DAG); 8027 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 8028 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 8029 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 8030 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 8031 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8032 SDValue Ops[] = { 8033 Chain, 8034 VData, // vdata 8035 Op.getOperand(3), // rsrc 8036 Op.getOperand(4), // vindex 8037 Op.getOperand(5), // voffset 8038 Op.getOperand(6), // soffset 8039 Op.getOperand(7), // offset 8040 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 8041 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8042 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8043 }; 8044 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8045 AMDGPUISD::TBUFFER_STORE_FORMAT; 8046 MemSDNode *M = cast<MemSDNode>(Op); 8047 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8048 M->getMemoryVT(), M->getMemOperand()); 8049 } 8050 8051 case Intrinsic::amdgcn_struct_tbuffer_store: { 8052 SDValue VData = Op.getOperand(2); 8053 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8054 if (IsD16) 8055 VData = handleD16VData(VData, DAG); 8056 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8057 SDValue Ops[] = { 8058 Chain, 8059 VData, // vdata 8060 Op.getOperand(3), // rsrc 8061 Op.getOperand(4), // vindex 8062 Offsets.first, // voffset 8063 Op.getOperand(6), // soffset 8064 Offsets.second, // offset 8065 Op.getOperand(7), // format 8066 Op.getOperand(8), // cachepolicy, swizzled buffer 8067 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8068 }; 8069 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8070 AMDGPUISD::TBUFFER_STORE_FORMAT; 8071 MemSDNode *M = cast<MemSDNode>(Op); 8072 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8073 M->getMemoryVT(), M->getMemOperand()); 8074 } 8075 8076 case Intrinsic::amdgcn_raw_tbuffer_store: { 8077 SDValue VData = Op.getOperand(2); 8078 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8079 if (IsD16) 8080 VData = handleD16VData(VData, DAG); 8081 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8082 SDValue Ops[] = { 8083 Chain, 8084 VData, // vdata 8085 Op.getOperand(3), // rsrc 8086 DAG.getConstant(0, DL, MVT::i32), // vindex 8087 Offsets.first, // voffset 8088 Op.getOperand(5), // soffset 8089 Offsets.second, // offset 8090 Op.getOperand(6), // format 8091 Op.getOperand(7), // cachepolicy, swizzled buffer 8092 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8093 }; 8094 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 8095 AMDGPUISD::TBUFFER_STORE_FORMAT; 8096 MemSDNode *M = cast<MemSDNode>(Op); 8097 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8098 M->getMemoryVT(), M->getMemOperand()); 8099 } 8100 8101 case Intrinsic::amdgcn_buffer_store: 8102 case Intrinsic::amdgcn_buffer_store_format: { 8103 SDValue VData = Op.getOperand(2); 8104 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 8105 if (IsD16) 8106 VData = handleD16VData(VData, DAG); 8107 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 8108 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 8109 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 8110 SDValue Ops[] = { 8111 Chain, 8112 VData, 8113 Op.getOperand(3), // rsrc 8114 Op.getOperand(4), // vindex 8115 SDValue(), // voffset -- will be set by setBufferOffsets 8116 SDValue(), // soffset -- will be set by setBufferOffsets 8117 SDValue(), // offset -- will be set by setBufferOffsets 8118 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 8119 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 8120 }; 8121 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 8122 8123 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 8124 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8125 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8126 MemSDNode *M = cast<MemSDNode>(Op); 8127 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8128 8129 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8130 EVT VDataType = VData.getValueType().getScalarType(); 8131 if (VDataType == MVT::i8 || VDataType == MVT::i16) 8132 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8133 8134 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8135 M->getMemoryVT(), M->getMemOperand()); 8136 } 8137 8138 case Intrinsic::amdgcn_raw_buffer_store: 8139 case Intrinsic::amdgcn_raw_buffer_store_format: { 8140 const bool IsFormat = 8141 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 8142 8143 SDValue VData = Op.getOperand(2); 8144 EVT VDataVT = VData.getValueType(); 8145 EVT EltType = VDataVT.getScalarType(); 8146 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8147 if (IsD16) { 8148 VData = handleD16VData(VData, DAG); 8149 VDataVT = VData.getValueType(); 8150 } 8151 8152 if (!isTypeLegal(VDataVT)) { 8153 VData = 8154 DAG.getNode(ISD::BITCAST, DL, 8155 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8156 } 8157 8158 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 8159 SDValue Ops[] = { 8160 Chain, 8161 VData, 8162 Op.getOperand(3), // rsrc 8163 DAG.getConstant(0, DL, MVT::i32), // vindex 8164 Offsets.first, // voffset 8165 Op.getOperand(5), // soffset 8166 Offsets.second, // offset 8167 Op.getOperand(6), // cachepolicy, swizzled buffer 8168 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 8169 }; 8170 unsigned Opc = 8171 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 8172 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8173 MemSDNode *M = cast<MemSDNode>(Op); 8174 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 8175 8176 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8177 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8178 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 8179 8180 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8181 M->getMemoryVT(), M->getMemOperand()); 8182 } 8183 8184 case Intrinsic::amdgcn_struct_buffer_store: 8185 case Intrinsic::amdgcn_struct_buffer_store_format: { 8186 const bool IsFormat = 8187 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 8188 8189 SDValue VData = Op.getOperand(2); 8190 EVT VDataVT = VData.getValueType(); 8191 EVT EltType = VDataVT.getScalarType(); 8192 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 8193 8194 if (IsD16) { 8195 VData = handleD16VData(VData, DAG); 8196 VDataVT = VData.getValueType(); 8197 } 8198 8199 if (!isTypeLegal(VDataVT)) { 8200 VData = 8201 DAG.getNode(ISD::BITCAST, DL, 8202 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 8203 } 8204 8205 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8206 SDValue Ops[] = { 8207 Chain, 8208 VData, 8209 Op.getOperand(3), // rsrc 8210 Op.getOperand(4), // vindex 8211 Offsets.first, // voffset 8212 Op.getOperand(6), // soffset 8213 Offsets.second, // offset 8214 Op.getOperand(7), // cachepolicy, swizzled buffer 8215 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8216 }; 8217 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8218 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8219 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8220 MemSDNode *M = cast<MemSDNode>(Op); 8221 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8222 8223 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8224 EVT VDataType = VData.getValueType().getScalarType(); 8225 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8226 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8227 8228 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8229 M->getMemoryVT(), M->getMemOperand()); 8230 } 8231 case Intrinsic::amdgcn_end_cf: 8232 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8233 Op->getOperand(2), Chain), 0); 8234 8235 default: { 8236 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8237 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8238 return lowerImage(Op, ImageDimIntr, DAG, true); 8239 8240 return Op; 8241 } 8242 } 8243 } 8244 8245 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8246 // offset (the offset that is included in bounds checking and swizzling, to be 8247 // split between the instruction's voffset and immoffset fields) and soffset 8248 // (the offset that is excluded from bounds checking and swizzling, to go in 8249 // the instruction's soffset field). This function takes the first kind of 8250 // offset and figures out how to split it between voffset and immoffset. 8251 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8252 SDValue Offset, SelectionDAG &DAG) const { 8253 SDLoc DL(Offset); 8254 const unsigned MaxImm = 4095; 8255 SDValue N0 = Offset; 8256 ConstantSDNode *C1 = nullptr; 8257 8258 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8259 N0 = SDValue(); 8260 else if (DAG.isBaseWithConstantOffset(N0)) { 8261 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8262 N0 = N0.getOperand(0); 8263 } 8264 8265 if (C1) { 8266 unsigned ImmOffset = C1->getZExtValue(); 8267 // If the immediate value is too big for the immoffset field, put the value 8268 // and -4096 into the immoffset field so that the value that is copied/added 8269 // for the voffset field is a multiple of 4096, and it stands more chance 8270 // of being CSEd with the copy/add for another similar load/store. 8271 // However, do not do that rounding down to a multiple of 4096 if that is a 8272 // negative number, as it appears to be illegal to have a negative offset 8273 // in the vgpr, even if adding the immediate offset makes it positive. 8274 unsigned Overflow = ImmOffset & ~MaxImm; 8275 ImmOffset -= Overflow; 8276 if ((int32_t)Overflow < 0) { 8277 Overflow += ImmOffset; 8278 ImmOffset = 0; 8279 } 8280 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8281 if (Overflow) { 8282 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8283 if (!N0) 8284 N0 = OverflowVal; 8285 else { 8286 SDValue Ops[] = { N0, OverflowVal }; 8287 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8288 } 8289 } 8290 } 8291 if (!N0) 8292 N0 = DAG.getConstant(0, DL, MVT::i32); 8293 if (!C1) 8294 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8295 return {N0, SDValue(C1, 0)}; 8296 } 8297 8298 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8299 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8300 // pointed to by Offsets. 8301 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8302 SelectionDAG &DAG, SDValue *Offsets, 8303 Align Alignment) const { 8304 SDLoc DL(CombinedOffset); 8305 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8306 uint32_t Imm = C->getZExtValue(); 8307 uint32_t SOffset, ImmOffset; 8308 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8309 Alignment)) { 8310 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8311 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8312 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8313 return; 8314 } 8315 } 8316 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8317 SDValue N0 = CombinedOffset.getOperand(0); 8318 SDValue N1 = CombinedOffset.getOperand(1); 8319 uint32_t SOffset, ImmOffset; 8320 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8321 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8322 Subtarget, Alignment)) { 8323 Offsets[0] = N0; 8324 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8325 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8326 return; 8327 } 8328 } 8329 Offsets[0] = CombinedOffset; 8330 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8331 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8332 } 8333 8334 // Handle 8 bit and 16 bit buffer loads 8335 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8336 EVT LoadVT, SDLoc DL, 8337 ArrayRef<SDValue> Ops, 8338 MemSDNode *M) const { 8339 EVT IntVT = LoadVT.changeTypeToInteger(); 8340 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8341 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8342 8343 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8344 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8345 Ops, IntVT, 8346 M->getMemOperand()); 8347 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8348 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8349 8350 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8351 } 8352 8353 // Handle 8 bit and 16 bit buffer stores 8354 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8355 EVT VDataType, SDLoc DL, 8356 SDValue Ops[], 8357 MemSDNode *M) const { 8358 if (VDataType == MVT::f16) 8359 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8360 8361 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8362 Ops[1] = BufferStoreExt; 8363 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8364 AMDGPUISD::BUFFER_STORE_SHORT; 8365 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8366 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8367 M->getMemOperand()); 8368 } 8369 8370 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8371 ISD::LoadExtType ExtType, SDValue Op, 8372 const SDLoc &SL, EVT VT) { 8373 if (VT.bitsLT(Op.getValueType())) 8374 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8375 8376 switch (ExtType) { 8377 case ISD::SEXTLOAD: 8378 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8379 case ISD::ZEXTLOAD: 8380 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8381 case ISD::EXTLOAD: 8382 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8383 case ISD::NON_EXTLOAD: 8384 return Op; 8385 } 8386 8387 llvm_unreachable("invalid ext type"); 8388 } 8389 8390 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8391 SelectionDAG &DAG = DCI.DAG; 8392 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8393 return SDValue(); 8394 8395 // FIXME: Constant loads should all be marked invariant. 8396 unsigned AS = Ld->getAddressSpace(); 8397 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8398 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8399 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8400 return SDValue(); 8401 8402 // Don't do this early, since it may interfere with adjacent load merging for 8403 // illegal types. We can avoid losing alignment information for exotic types 8404 // pre-legalize. 8405 EVT MemVT = Ld->getMemoryVT(); 8406 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8407 MemVT.getSizeInBits() >= 32) 8408 return SDValue(); 8409 8410 SDLoc SL(Ld); 8411 8412 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8413 "unexpected vector extload"); 8414 8415 // TODO: Drop only high part of range. 8416 SDValue Ptr = Ld->getBasePtr(); 8417 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8418 MVT::i32, SL, Ld->getChain(), Ptr, 8419 Ld->getOffset(), 8420 Ld->getPointerInfo(), MVT::i32, 8421 Ld->getAlignment(), 8422 Ld->getMemOperand()->getFlags(), 8423 Ld->getAAInfo(), 8424 nullptr); // Drop ranges 8425 8426 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8427 if (MemVT.isFloatingPoint()) { 8428 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8429 "unexpected fp extload"); 8430 TruncVT = MemVT.changeTypeToInteger(); 8431 } 8432 8433 SDValue Cvt = NewLoad; 8434 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8435 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8436 DAG.getValueType(TruncVT)); 8437 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8438 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8439 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8440 } else { 8441 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8442 } 8443 8444 EVT VT = Ld->getValueType(0); 8445 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8446 8447 DCI.AddToWorklist(Cvt.getNode()); 8448 8449 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8450 // the appropriate extension from the 32-bit load. 8451 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8452 DCI.AddToWorklist(Cvt.getNode()); 8453 8454 // Handle conversion back to floating point if necessary. 8455 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8456 8457 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8458 } 8459 8460 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8461 SDLoc DL(Op); 8462 LoadSDNode *Load = cast<LoadSDNode>(Op); 8463 ISD::LoadExtType ExtType = Load->getExtensionType(); 8464 EVT MemVT = Load->getMemoryVT(); 8465 8466 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8467 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8468 return SDValue(); 8469 8470 // FIXME: Copied from PPC 8471 // First, load into 32 bits, then truncate to 1 bit. 8472 8473 SDValue Chain = Load->getChain(); 8474 SDValue BasePtr = Load->getBasePtr(); 8475 MachineMemOperand *MMO = Load->getMemOperand(); 8476 8477 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8478 8479 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8480 BasePtr, RealMemVT, MMO); 8481 8482 if (!MemVT.isVector()) { 8483 SDValue Ops[] = { 8484 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8485 NewLD.getValue(1) 8486 }; 8487 8488 return DAG.getMergeValues(Ops, DL); 8489 } 8490 8491 SmallVector<SDValue, 3> Elts; 8492 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8493 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8494 DAG.getConstant(I, DL, MVT::i32)); 8495 8496 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8497 } 8498 8499 SDValue Ops[] = { 8500 DAG.getBuildVector(MemVT, DL, Elts), 8501 NewLD.getValue(1) 8502 }; 8503 8504 return DAG.getMergeValues(Ops, DL); 8505 } 8506 8507 if (!MemVT.isVector()) 8508 return SDValue(); 8509 8510 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8511 "Custom lowering for non-i32 vectors hasn't been implemented."); 8512 8513 unsigned Alignment = Load->getAlignment(); 8514 unsigned AS = Load->getAddressSpace(); 8515 if (Subtarget->hasLDSMisalignedBug() && 8516 AS == AMDGPUAS::FLAT_ADDRESS && 8517 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8518 return SplitVectorLoad(Op, DAG); 8519 } 8520 8521 MachineFunction &MF = DAG.getMachineFunction(); 8522 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8523 // If there is a possibility that flat instruction access scratch memory 8524 // then we need to use the same legalization rules we use for private. 8525 if (AS == AMDGPUAS::FLAT_ADDRESS && 8526 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8527 AS = MFI->hasFlatScratchInit() ? 8528 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8529 8530 unsigned NumElements = MemVT.getVectorNumElements(); 8531 8532 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8533 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8534 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8535 if (MemVT.isPow2VectorType()) 8536 return SDValue(); 8537 return WidenOrSplitVectorLoad(Op, DAG); 8538 } 8539 // Non-uniform loads will be selected to MUBUF instructions, so they 8540 // have the same legalization requirements as global and private 8541 // loads. 8542 // 8543 } 8544 8545 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8546 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8547 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8548 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8549 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8550 Alignment >= 4 && NumElements < 32) { 8551 if (MemVT.isPow2VectorType()) 8552 return SDValue(); 8553 return WidenOrSplitVectorLoad(Op, DAG); 8554 } 8555 // Non-uniform loads will be selected to MUBUF instructions, so they 8556 // have the same legalization requirements as global and private 8557 // loads. 8558 // 8559 } 8560 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8561 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8562 AS == AMDGPUAS::GLOBAL_ADDRESS || 8563 AS == AMDGPUAS::FLAT_ADDRESS) { 8564 if (NumElements > 4) 8565 return SplitVectorLoad(Op, DAG); 8566 // v3 loads not supported on SI. 8567 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8568 return WidenOrSplitVectorLoad(Op, DAG); 8569 8570 // v3 and v4 loads are supported for private and global memory. 8571 return SDValue(); 8572 } 8573 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8574 // Depending on the setting of the private_element_size field in the 8575 // resource descriptor, we can only make private accesses up to a certain 8576 // size. 8577 switch (Subtarget->getMaxPrivateElementSize()) { 8578 case 4: { 8579 SDValue Ops[2]; 8580 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8581 return DAG.getMergeValues(Ops, DL); 8582 } 8583 case 8: 8584 if (NumElements > 2) 8585 return SplitVectorLoad(Op, DAG); 8586 return SDValue(); 8587 case 16: 8588 // Same as global/flat 8589 if (NumElements > 4) 8590 return SplitVectorLoad(Op, DAG); 8591 // v3 loads not supported on SI. 8592 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8593 return WidenOrSplitVectorLoad(Op, DAG); 8594 8595 return SDValue(); 8596 default: 8597 llvm_unreachable("unsupported private_element_size"); 8598 } 8599 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8600 bool Fast = false; 8601 auto Flags = Load->getMemOperand()->getFlags(); 8602 if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8603 Load->getAlign(), Flags, &Fast) && 8604 Fast) 8605 return SDValue(); 8606 8607 if (MemVT.isVector()) 8608 return SplitVectorLoad(Op, DAG); 8609 } 8610 8611 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8612 MemVT, *Load->getMemOperand())) { 8613 SDValue Ops[2]; 8614 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8615 return DAG.getMergeValues(Ops, DL); 8616 } 8617 8618 return SDValue(); 8619 } 8620 8621 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8622 EVT VT = Op.getValueType(); 8623 if (VT.getSizeInBits() == 128) 8624 return splitTernaryVectorOp(Op, DAG); 8625 8626 assert(VT.getSizeInBits() == 64); 8627 8628 SDLoc DL(Op); 8629 SDValue Cond = Op.getOperand(0); 8630 8631 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8632 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8633 8634 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8635 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8636 8637 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8638 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8639 8640 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8641 8642 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8643 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8644 8645 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8646 8647 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8648 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8649 } 8650 8651 // Catch division cases where we can use shortcuts with rcp and rsq 8652 // instructions. 8653 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8654 SelectionDAG &DAG) const { 8655 SDLoc SL(Op); 8656 SDValue LHS = Op.getOperand(0); 8657 SDValue RHS = Op.getOperand(1); 8658 EVT VT = Op.getValueType(); 8659 const SDNodeFlags Flags = Op->getFlags(); 8660 8661 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8662 8663 // Without !fpmath accuracy information, we can't do more because we don't 8664 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8665 if (!AllowInaccurateRcp) 8666 return SDValue(); 8667 8668 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8669 if (CLHS->isExactlyValue(1.0)) { 8670 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8671 // the CI documentation has a worst case error of 1 ulp. 8672 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8673 // use it as long as we aren't trying to use denormals. 8674 // 8675 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8676 8677 // 1.0 / sqrt(x) -> rsq(x) 8678 8679 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8680 // error seems really high at 2^29 ULP. 8681 if (RHS.getOpcode() == ISD::FSQRT) 8682 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8683 8684 // 1.0 / x -> rcp(x) 8685 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8686 } 8687 8688 // Same as for 1.0, but expand the sign out of the constant. 8689 if (CLHS->isExactlyValue(-1.0)) { 8690 // -1.0 / x -> rcp (fneg x) 8691 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8692 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8693 } 8694 } 8695 8696 // Turn into multiply by the reciprocal. 8697 // x / y -> x * (1.0 / y) 8698 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8699 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8700 } 8701 8702 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8703 SelectionDAG &DAG) const { 8704 SDLoc SL(Op); 8705 SDValue X = Op.getOperand(0); 8706 SDValue Y = Op.getOperand(1); 8707 EVT VT = Op.getValueType(); 8708 const SDNodeFlags Flags = Op->getFlags(); 8709 8710 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8711 DAG.getTarget().Options.UnsafeFPMath; 8712 if (!AllowInaccurateDiv) 8713 return SDValue(); 8714 8715 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8716 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8717 8718 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8719 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8720 8721 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8722 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8723 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8724 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8725 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8726 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8727 } 8728 8729 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8730 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8731 SDNodeFlags Flags) { 8732 if (GlueChain->getNumValues() <= 1) { 8733 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8734 } 8735 8736 assert(GlueChain->getNumValues() == 3); 8737 8738 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8739 switch (Opcode) { 8740 default: llvm_unreachable("no chain equivalent for opcode"); 8741 case ISD::FMUL: 8742 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8743 break; 8744 } 8745 8746 return DAG.getNode(Opcode, SL, VTList, 8747 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8748 Flags); 8749 } 8750 8751 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8752 EVT VT, SDValue A, SDValue B, SDValue C, 8753 SDValue GlueChain, SDNodeFlags Flags) { 8754 if (GlueChain->getNumValues() <= 1) { 8755 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8756 } 8757 8758 assert(GlueChain->getNumValues() == 3); 8759 8760 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8761 switch (Opcode) { 8762 default: llvm_unreachable("no chain equivalent for opcode"); 8763 case ISD::FMA: 8764 Opcode = AMDGPUISD::FMA_W_CHAIN; 8765 break; 8766 } 8767 8768 return DAG.getNode(Opcode, SL, VTList, 8769 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8770 Flags); 8771 } 8772 8773 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8774 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8775 return FastLowered; 8776 8777 SDLoc SL(Op); 8778 SDValue Src0 = Op.getOperand(0); 8779 SDValue Src1 = Op.getOperand(1); 8780 8781 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8782 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8783 8784 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8785 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8786 8787 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8788 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8789 8790 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8791 } 8792 8793 // Faster 2.5 ULP division that does not support denormals. 8794 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8795 SDLoc SL(Op); 8796 SDValue LHS = Op.getOperand(1); 8797 SDValue RHS = Op.getOperand(2); 8798 8799 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8800 8801 const APFloat K0Val(BitsToFloat(0x6f800000)); 8802 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8803 8804 const APFloat K1Val(BitsToFloat(0x2f800000)); 8805 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8806 8807 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8808 8809 EVT SetCCVT = 8810 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8811 8812 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8813 8814 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8815 8816 // TODO: Should this propagate fast-math-flags? 8817 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8818 8819 // rcp does not support denormals. 8820 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8821 8822 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8823 8824 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8825 } 8826 8827 // Returns immediate value for setting the F32 denorm mode when using the 8828 // S_DENORM_MODE instruction. 8829 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8830 const SDLoc &SL, const GCNSubtarget *ST) { 8831 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8832 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8833 ? FP_DENORM_FLUSH_NONE 8834 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8835 8836 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8837 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8838 } 8839 8840 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8841 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8842 return FastLowered; 8843 8844 // The selection matcher assumes anything with a chain selecting to a 8845 // mayRaiseFPException machine instruction. Since we're introducing a chain 8846 // here, we need to explicitly report nofpexcept for the regular fdiv 8847 // lowering. 8848 SDNodeFlags Flags = Op->getFlags(); 8849 Flags.setNoFPExcept(true); 8850 8851 SDLoc SL(Op); 8852 SDValue LHS = Op.getOperand(0); 8853 SDValue RHS = Op.getOperand(1); 8854 8855 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8856 8857 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8858 8859 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8860 {RHS, RHS, LHS}, Flags); 8861 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8862 {LHS, RHS, LHS}, Flags); 8863 8864 // Denominator is scaled to not be denormal, so using rcp is ok. 8865 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8866 DenominatorScaled, Flags); 8867 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8868 DenominatorScaled, Flags); 8869 8870 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8871 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8872 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8873 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8874 8875 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8876 8877 if (!HasFP32Denormals) { 8878 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8879 // lowering. The chain dependence is insufficient, and we need glue. We do 8880 // not need the glue variants in a strictfp function. 8881 8882 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8883 8884 SDNode *EnableDenorm; 8885 if (Subtarget->hasDenormModeInst()) { 8886 const SDValue EnableDenormValue = 8887 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8888 8889 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8890 DAG.getEntryNode(), EnableDenormValue).getNode(); 8891 } else { 8892 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8893 SL, MVT::i32); 8894 EnableDenorm = 8895 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8896 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8897 } 8898 8899 SDValue Ops[3] = { 8900 NegDivScale0, 8901 SDValue(EnableDenorm, 0), 8902 SDValue(EnableDenorm, 1) 8903 }; 8904 8905 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8906 } 8907 8908 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8909 ApproxRcp, One, NegDivScale0, Flags); 8910 8911 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8912 ApproxRcp, Fma0, Flags); 8913 8914 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8915 Fma1, Fma1, Flags); 8916 8917 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8918 NumeratorScaled, Mul, Flags); 8919 8920 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8921 Fma2, Fma1, Mul, Fma2, Flags); 8922 8923 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8924 NumeratorScaled, Fma3, Flags); 8925 8926 if (!HasFP32Denormals) { 8927 SDNode *DisableDenorm; 8928 if (Subtarget->hasDenormModeInst()) { 8929 const SDValue DisableDenormValue = 8930 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8931 8932 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8933 Fma4.getValue(1), DisableDenormValue, 8934 Fma4.getValue(2)).getNode(); 8935 } else { 8936 const SDValue DisableDenormValue = 8937 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8938 8939 DisableDenorm = DAG.getMachineNode( 8940 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8941 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8942 } 8943 8944 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8945 SDValue(DisableDenorm, 0), DAG.getRoot()); 8946 DAG.setRoot(OutputChain); 8947 } 8948 8949 SDValue Scale = NumeratorScaled.getValue(1); 8950 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8951 {Fma4, Fma1, Fma3, Scale}, Flags); 8952 8953 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8954 } 8955 8956 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8957 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8958 return FastLowered; 8959 8960 SDLoc SL(Op); 8961 SDValue X = Op.getOperand(0); 8962 SDValue Y = Op.getOperand(1); 8963 8964 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8965 8966 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8967 8968 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8969 8970 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8971 8972 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8973 8974 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8975 8976 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8977 8978 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8979 8980 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8981 8982 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8983 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8984 8985 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8986 NegDivScale0, Mul, DivScale1); 8987 8988 SDValue Scale; 8989 8990 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8991 // Workaround a hardware bug on SI where the condition output from div_scale 8992 // is not usable. 8993 8994 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8995 8996 // Figure out if the scale to use for div_fmas. 8997 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8998 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8999 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 9000 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 9001 9002 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 9003 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 9004 9005 SDValue Scale0Hi 9006 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 9007 SDValue Scale1Hi 9008 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 9009 9010 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 9011 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 9012 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 9013 } else { 9014 Scale = DivScale1.getValue(1); 9015 } 9016 9017 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 9018 Fma4, Fma3, Mul, Scale); 9019 9020 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 9021 } 9022 9023 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 9024 EVT VT = Op.getValueType(); 9025 9026 if (VT == MVT::f32) 9027 return LowerFDIV32(Op, DAG); 9028 9029 if (VT == MVT::f64) 9030 return LowerFDIV64(Op, DAG); 9031 9032 if (VT == MVT::f16) 9033 return LowerFDIV16(Op, DAG); 9034 9035 llvm_unreachable("Unexpected type for fdiv"); 9036 } 9037 9038 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 9039 SDLoc DL(Op); 9040 StoreSDNode *Store = cast<StoreSDNode>(Op); 9041 EVT VT = Store->getMemoryVT(); 9042 9043 if (VT == MVT::i1) { 9044 return DAG.getTruncStore(Store->getChain(), DL, 9045 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 9046 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 9047 } 9048 9049 assert(VT.isVector() && 9050 Store->getValue().getValueType().getScalarType() == MVT::i32); 9051 9052 unsigned AS = Store->getAddressSpace(); 9053 if (Subtarget->hasLDSMisalignedBug() && 9054 AS == AMDGPUAS::FLAT_ADDRESS && 9055 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 9056 return SplitVectorStore(Op, DAG); 9057 } 9058 9059 MachineFunction &MF = DAG.getMachineFunction(); 9060 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 9061 // If there is a possibility that flat instruction access scratch memory 9062 // then we need to use the same legalization rules we use for private. 9063 if (AS == AMDGPUAS::FLAT_ADDRESS && 9064 !Subtarget->hasMultiDwordFlatScratchAddressing()) 9065 AS = MFI->hasFlatScratchInit() ? 9066 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 9067 9068 unsigned NumElements = VT.getVectorNumElements(); 9069 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 9070 AS == AMDGPUAS::FLAT_ADDRESS) { 9071 if (NumElements > 4) 9072 return SplitVectorStore(Op, DAG); 9073 // v3 stores not supported on SI. 9074 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 9075 return SplitVectorStore(Op, DAG); 9076 9077 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 9078 VT, *Store->getMemOperand())) 9079 return expandUnalignedStore(Store, DAG); 9080 9081 return SDValue(); 9082 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 9083 switch (Subtarget->getMaxPrivateElementSize()) { 9084 case 4: 9085 return scalarizeVectorStore(Store, DAG); 9086 case 8: 9087 if (NumElements > 2) 9088 return SplitVectorStore(Op, DAG); 9089 return SDValue(); 9090 case 16: 9091 if (NumElements > 4 || 9092 (NumElements == 3 && !Subtarget->enableFlatScratch())) 9093 return SplitVectorStore(Op, DAG); 9094 return SDValue(); 9095 default: 9096 llvm_unreachable("unsupported private_element_size"); 9097 } 9098 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 9099 bool Fast = false; 9100 auto Flags = Store->getMemOperand()->getFlags(); 9101 if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 9102 Store->getAlign(), Flags, &Fast) && 9103 Fast) 9104 return SDValue(); 9105 9106 if (VT.isVector()) 9107 return SplitVectorStore(Op, DAG); 9108 9109 return expandUnalignedStore(Store, DAG); 9110 } 9111 9112 // Probably an invalid store. If so we'll end up emitting a selection error. 9113 return SDValue(); 9114 } 9115 9116 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 9117 SDLoc DL(Op); 9118 EVT VT = Op.getValueType(); 9119 SDValue Arg = Op.getOperand(0); 9120 SDValue TrigVal; 9121 9122 // Propagate fast-math flags so that the multiply we introduce can be folded 9123 // if Arg is already the result of a multiply by constant. 9124 auto Flags = Op->getFlags(); 9125 9126 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 9127 9128 if (Subtarget->hasTrigReducedRange()) { 9129 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9130 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 9131 } else { 9132 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 9133 } 9134 9135 switch (Op.getOpcode()) { 9136 case ISD::FCOS: 9137 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 9138 case ISD::FSIN: 9139 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 9140 default: 9141 llvm_unreachable("Wrong trig opcode"); 9142 } 9143 } 9144 9145 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 9146 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 9147 assert(AtomicNode->isCompareAndSwap()); 9148 unsigned AS = AtomicNode->getAddressSpace(); 9149 9150 // No custom lowering required for local address space 9151 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 9152 return Op; 9153 9154 // Non-local address space requires custom lowering for atomic compare 9155 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 9156 SDLoc DL(Op); 9157 SDValue ChainIn = Op.getOperand(0); 9158 SDValue Addr = Op.getOperand(1); 9159 SDValue Old = Op.getOperand(2); 9160 SDValue New = Op.getOperand(3); 9161 EVT VT = Op.getValueType(); 9162 MVT SimpleVT = VT.getSimpleVT(); 9163 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 9164 9165 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 9166 SDValue Ops[] = { ChainIn, Addr, NewOld }; 9167 9168 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 9169 Ops, VT, AtomicNode->getMemOperand()); 9170 } 9171 9172 //===----------------------------------------------------------------------===// 9173 // Custom DAG optimizations 9174 //===----------------------------------------------------------------------===// 9175 9176 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 9177 DAGCombinerInfo &DCI) const { 9178 EVT VT = N->getValueType(0); 9179 EVT ScalarVT = VT.getScalarType(); 9180 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9181 return SDValue(); 9182 9183 SelectionDAG &DAG = DCI.DAG; 9184 SDLoc DL(N); 9185 9186 SDValue Src = N->getOperand(0); 9187 EVT SrcVT = Src.getValueType(); 9188 9189 // TODO: We could try to match extracting the higher bytes, which would be 9190 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9191 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9192 // about in practice. 9193 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9194 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9195 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9196 DCI.AddToWorklist(Cvt.getNode()); 9197 9198 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9199 if (ScalarVT != MVT::f32) { 9200 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9201 DAG.getTargetConstant(0, DL, MVT::i32)); 9202 } 9203 return Cvt; 9204 } 9205 } 9206 9207 return SDValue(); 9208 } 9209 9210 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9211 9212 // This is a variant of 9213 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9214 // 9215 // The normal DAG combiner will do this, but only if the add has one use since 9216 // that would increase the number of instructions. 9217 // 9218 // This prevents us from seeing a constant offset that can be folded into a 9219 // memory instruction's addressing mode. If we know the resulting add offset of 9220 // a pointer can be folded into an addressing offset, we can replace the pointer 9221 // operand with the add of new constant offset. This eliminates one of the uses, 9222 // and may allow the remaining use to also be simplified. 9223 // 9224 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9225 unsigned AddrSpace, 9226 EVT MemVT, 9227 DAGCombinerInfo &DCI) const { 9228 SDValue N0 = N->getOperand(0); 9229 SDValue N1 = N->getOperand(1); 9230 9231 // We only do this to handle cases where it's profitable when there are 9232 // multiple uses of the add, so defer to the standard combine. 9233 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9234 N0->hasOneUse()) 9235 return SDValue(); 9236 9237 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9238 if (!CN1) 9239 return SDValue(); 9240 9241 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9242 if (!CAdd) 9243 return SDValue(); 9244 9245 // If the resulting offset is too large, we can't fold it into the addressing 9246 // mode offset. 9247 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9248 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9249 9250 AddrMode AM; 9251 AM.HasBaseReg = true; 9252 AM.BaseOffs = Offset.getSExtValue(); 9253 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9254 return SDValue(); 9255 9256 SelectionDAG &DAG = DCI.DAG; 9257 SDLoc SL(N); 9258 EVT VT = N->getValueType(0); 9259 9260 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9261 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9262 9263 SDNodeFlags Flags; 9264 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9265 (N0.getOpcode() == ISD::OR || 9266 N0->getFlags().hasNoUnsignedWrap())); 9267 9268 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9269 } 9270 9271 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9272 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9273 /// specific intrinsic, but they all place the pointer operand first. 9274 static unsigned getBasePtrIndex(const MemSDNode *N) { 9275 switch (N->getOpcode()) { 9276 case ISD::STORE: 9277 case ISD::INTRINSIC_W_CHAIN: 9278 case ISD::INTRINSIC_VOID: 9279 return 2; 9280 default: 9281 return 1; 9282 } 9283 } 9284 9285 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9286 DAGCombinerInfo &DCI) const { 9287 SelectionDAG &DAG = DCI.DAG; 9288 SDLoc SL(N); 9289 9290 unsigned PtrIdx = getBasePtrIndex(N); 9291 SDValue Ptr = N->getOperand(PtrIdx); 9292 9293 // TODO: We could also do this for multiplies. 9294 if (Ptr.getOpcode() == ISD::SHL) { 9295 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9296 N->getMemoryVT(), DCI); 9297 if (NewPtr) { 9298 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9299 9300 NewOps[PtrIdx] = NewPtr; 9301 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9302 } 9303 } 9304 9305 return SDValue(); 9306 } 9307 9308 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9309 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9310 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9311 (Opc == ISD::XOR && Val == 0); 9312 } 9313 9314 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9315 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9316 // integer combine opportunities since most 64-bit operations are decomposed 9317 // this way. TODO: We won't want this for SALU especially if it is an inline 9318 // immediate. 9319 SDValue SITargetLowering::splitBinaryBitConstantOp( 9320 DAGCombinerInfo &DCI, 9321 const SDLoc &SL, 9322 unsigned Opc, SDValue LHS, 9323 const ConstantSDNode *CRHS) const { 9324 uint64_t Val = CRHS->getZExtValue(); 9325 uint32_t ValLo = Lo_32(Val); 9326 uint32_t ValHi = Hi_32(Val); 9327 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9328 9329 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9330 bitOpWithConstantIsReducible(Opc, ValHi)) || 9331 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9332 // If we need to materialize a 64-bit immediate, it will be split up later 9333 // anyway. Avoid creating the harder to understand 64-bit immediate 9334 // materialization. 9335 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9336 } 9337 9338 return SDValue(); 9339 } 9340 9341 // Returns true if argument is a boolean value which is not serialized into 9342 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9343 static bool isBoolSGPR(SDValue V) { 9344 if (V.getValueType() != MVT::i1) 9345 return false; 9346 switch (V.getOpcode()) { 9347 default: 9348 break; 9349 case ISD::SETCC: 9350 case AMDGPUISD::FP_CLASS: 9351 return true; 9352 case ISD::AND: 9353 case ISD::OR: 9354 case ISD::XOR: 9355 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9356 } 9357 return false; 9358 } 9359 9360 // If a constant has all zeroes or all ones within each byte return it. 9361 // Otherwise return 0. 9362 static uint32_t getConstantPermuteMask(uint32_t C) { 9363 // 0xff for any zero byte in the mask 9364 uint32_t ZeroByteMask = 0; 9365 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9366 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9367 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9368 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9369 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9370 if ((NonZeroByteMask & C) != NonZeroByteMask) 9371 return 0; // Partial bytes selected. 9372 return C; 9373 } 9374 9375 // Check if a node selects whole bytes from its operand 0 starting at a byte 9376 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9377 // or -1 if not succeeded. 9378 // Note byte select encoding: 9379 // value 0-3 selects corresponding source byte; 9380 // value 0xc selects zero; 9381 // value 0xff selects 0xff. 9382 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9383 assert(V.getValueSizeInBits() == 32); 9384 9385 if (V.getNumOperands() != 2) 9386 return ~0; 9387 9388 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9389 if (!N1) 9390 return ~0; 9391 9392 uint32_t C = N1->getZExtValue(); 9393 9394 switch (V.getOpcode()) { 9395 default: 9396 break; 9397 case ISD::AND: 9398 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9399 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9400 } 9401 break; 9402 9403 case ISD::OR: 9404 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9405 return (0x03020100 & ~ConstMask) | ConstMask; 9406 } 9407 break; 9408 9409 case ISD::SHL: 9410 if (C % 8) 9411 return ~0; 9412 9413 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9414 9415 case ISD::SRL: 9416 if (C % 8) 9417 return ~0; 9418 9419 return uint32_t(0x0c0c0c0c03020100ull >> C); 9420 } 9421 9422 return ~0; 9423 } 9424 9425 SDValue SITargetLowering::performAndCombine(SDNode *N, 9426 DAGCombinerInfo &DCI) const { 9427 if (DCI.isBeforeLegalize()) 9428 return SDValue(); 9429 9430 SelectionDAG &DAG = DCI.DAG; 9431 EVT VT = N->getValueType(0); 9432 SDValue LHS = N->getOperand(0); 9433 SDValue RHS = N->getOperand(1); 9434 9435 9436 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9437 if (VT == MVT::i64 && CRHS) { 9438 if (SDValue Split 9439 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9440 return Split; 9441 } 9442 9443 if (CRHS && VT == MVT::i32) { 9444 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9445 // nb = number of trailing zeroes in mask 9446 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9447 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9448 uint64_t Mask = CRHS->getZExtValue(); 9449 unsigned Bits = countPopulation(Mask); 9450 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9451 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9452 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9453 unsigned Shift = CShift->getZExtValue(); 9454 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9455 unsigned Offset = NB + Shift; 9456 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9457 SDLoc SL(N); 9458 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9459 LHS->getOperand(0), 9460 DAG.getConstant(Offset, SL, MVT::i32), 9461 DAG.getConstant(Bits, SL, MVT::i32)); 9462 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9463 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9464 DAG.getValueType(NarrowVT)); 9465 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9466 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9467 return Shl; 9468 } 9469 } 9470 } 9471 9472 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9473 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9474 isa<ConstantSDNode>(LHS.getOperand(2))) { 9475 uint32_t Sel = getConstantPermuteMask(Mask); 9476 if (!Sel) 9477 return SDValue(); 9478 9479 // Select 0xc for all zero bytes 9480 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9481 SDLoc DL(N); 9482 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9483 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9484 } 9485 } 9486 9487 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9488 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9489 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9490 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9491 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9492 9493 SDValue X = LHS.getOperand(0); 9494 SDValue Y = RHS.getOperand(0); 9495 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9496 return SDValue(); 9497 9498 if (LCC == ISD::SETO) { 9499 if (X != LHS.getOperand(1)) 9500 return SDValue(); 9501 9502 if (RCC == ISD::SETUNE) { 9503 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9504 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9505 return SDValue(); 9506 9507 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9508 SIInstrFlags::N_SUBNORMAL | 9509 SIInstrFlags::N_ZERO | 9510 SIInstrFlags::P_ZERO | 9511 SIInstrFlags::P_SUBNORMAL | 9512 SIInstrFlags::P_NORMAL; 9513 9514 static_assert(((~(SIInstrFlags::S_NAN | 9515 SIInstrFlags::Q_NAN | 9516 SIInstrFlags::N_INFINITY | 9517 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9518 "mask not equal"); 9519 9520 SDLoc DL(N); 9521 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9522 X, DAG.getConstant(Mask, DL, MVT::i32)); 9523 } 9524 } 9525 } 9526 9527 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9528 std::swap(LHS, RHS); 9529 9530 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9531 RHS.hasOneUse()) { 9532 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9533 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9534 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9535 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9536 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9537 (RHS.getOperand(0) == LHS.getOperand(0) && 9538 LHS.getOperand(0) == LHS.getOperand(1))) { 9539 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9540 unsigned NewMask = LCC == ISD::SETO ? 9541 Mask->getZExtValue() & ~OrdMask : 9542 Mask->getZExtValue() & OrdMask; 9543 9544 SDLoc DL(N); 9545 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9546 DAG.getConstant(NewMask, DL, MVT::i32)); 9547 } 9548 } 9549 9550 if (VT == MVT::i32 && 9551 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9552 // and x, (sext cc from i1) => select cc, x, 0 9553 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9554 std::swap(LHS, RHS); 9555 if (isBoolSGPR(RHS.getOperand(0))) 9556 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9557 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9558 } 9559 9560 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9561 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9562 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9563 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9564 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9565 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9566 if (LHSMask != ~0u && RHSMask != ~0u) { 9567 // Canonicalize the expression in an attempt to have fewer unique masks 9568 // and therefore fewer registers used to hold the masks. 9569 if (LHSMask > RHSMask) { 9570 std::swap(LHSMask, RHSMask); 9571 std::swap(LHS, RHS); 9572 } 9573 9574 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9575 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9576 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9577 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9578 9579 // Check of we need to combine values from two sources within a byte. 9580 if (!(LHSUsedLanes & RHSUsedLanes) && 9581 // If we select high and lower word keep it for SDWA. 9582 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9583 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9584 // Each byte in each mask is either selector mask 0-3, or has higher 9585 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9586 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9587 // mask which is not 0xff wins. By anding both masks we have a correct 9588 // result except that 0x0c shall be corrected to give 0x0c only. 9589 uint32_t Mask = LHSMask & RHSMask; 9590 for (unsigned I = 0; I < 32; I += 8) { 9591 uint32_t ByteSel = 0xff << I; 9592 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9593 Mask &= (0x0c << I) & 0xffffffff; 9594 } 9595 9596 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9597 // or 0x0c. 9598 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9599 SDLoc DL(N); 9600 9601 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9602 LHS.getOperand(0), RHS.getOperand(0), 9603 DAG.getConstant(Sel, DL, MVT::i32)); 9604 } 9605 } 9606 } 9607 9608 return SDValue(); 9609 } 9610 9611 SDValue SITargetLowering::performOrCombine(SDNode *N, 9612 DAGCombinerInfo &DCI) const { 9613 SelectionDAG &DAG = DCI.DAG; 9614 SDValue LHS = N->getOperand(0); 9615 SDValue RHS = N->getOperand(1); 9616 9617 EVT VT = N->getValueType(0); 9618 if (VT == MVT::i1) { 9619 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9620 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9621 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9622 SDValue Src = LHS.getOperand(0); 9623 if (Src != RHS.getOperand(0)) 9624 return SDValue(); 9625 9626 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9627 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9628 if (!CLHS || !CRHS) 9629 return SDValue(); 9630 9631 // Only 10 bits are used. 9632 static const uint32_t MaxMask = 0x3ff; 9633 9634 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9635 SDLoc DL(N); 9636 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9637 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9638 } 9639 9640 return SDValue(); 9641 } 9642 9643 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9644 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9645 LHS.getOpcode() == AMDGPUISD::PERM && 9646 isa<ConstantSDNode>(LHS.getOperand(2))) { 9647 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9648 if (!Sel) 9649 return SDValue(); 9650 9651 Sel |= LHS.getConstantOperandVal(2); 9652 SDLoc DL(N); 9653 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9654 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9655 } 9656 9657 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9658 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9659 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9660 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9661 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9662 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9663 if (LHSMask != ~0u && RHSMask != ~0u) { 9664 // Canonicalize the expression in an attempt to have fewer unique masks 9665 // and therefore fewer registers used to hold the masks. 9666 if (LHSMask > RHSMask) { 9667 std::swap(LHSMask, RHSMask); 9668 std::swap(LHS, RHS); 9669 } 9670 9671 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9672 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9673 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9674 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9675 9676 // Check of we need to combine values from two sources within a byte. 9677 if (!(LHSUsedLanes & RHSUsedLanes) && 9678 // If we select high and lower word keep it for SDWA. 9679 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9680 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9681 // Kill zero bytes selected by other mask. Zero value is 0xc. 9682 LHSMask &= ~RHSUsedLanes; 9683 RHSMask &= ~LHSUsedLanes; 9684 // Add 4 to each active LHS lane 9685 LHSMask |= LHSUsedLanes & 0x04040404; 9686 // Combine masks 9687 uint32_t Sel = LHSMask | RHSMask; 9688 SDLoc DL(N); 9689 9690 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9691 LHS.getOperand(0), RHS.getOperand(0), 9692 DAG.getConstant(Sel, DL, MVT::i32)); 9693 } 9694 } 9695 } 9696 9697 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9698 return SDValue(); 9699 9700 // TODO: This could be a generic combine with a predicate for extracting the 9701 // high half of an integer being free. 9702 9703 // (or i64:x, (zero_extend i32:y)) -> 9704 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9705 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9706 RHS.getOpcode() != ISD::ZERO_EXTEND) 9707 std::swap(LHS, RHS); 9708 9709 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9710 SDValue ExtSrc = RHS.getOperand(0); 9711 EVT SrcVT = ExtSrc.getValueType(); 9712 if (SrcVT == MVT::i32) { 9713 SDLoc SL(N); 9714 SDValue LowLHS, HiBits; 9715 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9716 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9717 9718 DCI.AddToWorklist(LowOr.getNode()); 9719 DCI.AddToWorklist(HiBits.getNode()); 9720 9721 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9722 LowOr, HiBits); 9723 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9724 } 9725 } 9726 9727 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9728 if (CRHS) { 9729 if (SDValue Split 9730 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9731 N->getOperand(0), CRHS)) 9732 return Split; 9733 } 9734 9735 return SDValue(); 9736 } 9737 9738 SDValue SITargetLowering::performXorCombine(SDNode *N, 9739 DAGCombinerInfo &DCI) const { 9740 if (SDValue RV = reassociateScalarOps(N, DCI.DAG)) 9741 return RV; 9742 9743 EVT VT = N->getValueType(0); 9744 if (VT != MVT::i64) 9745 return SDValue(); 9746 9747 SDValue LHS = N->getOperand(0); 9748 SDValue RHS = N->getOperand(1); 9749 9750 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9751 if (CRHS) { 9752 if (SDValue Split 9753 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9754 return Split; 9755 } 9756 9757 return SDValue(); 9758 } 9759 9760 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9761 DAGCombinerInfo &DCI) const { 9762 if (!Subtarget->has16BitInsts() || 9763 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9764 return SDValue(); 9765 9766 EVT VT = N->getValueType(0); 9767 if (VT != MVT::i32) 9768 return SDValue(); 9769 9770 SDValue Src = N->getOperand(0); 9771 if (Src.getValueType() != MVT::i16) 9772 return SDValue(); 9773 9774 return SDValue(); 9775 } 9776 9777 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9778 DAGCombinerInfo &DCI) 9779 const { 9780 SDValue Src = N->getOperand(0); 9781 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9782 9783 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9784 VTSign->getVT() == MVT::i8) || 9785 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9786 VTSign->getVT() == MVT::i16)) && 9787 Src.hasOneUse()) { 9788 auto *M = cast<MemSDNode>(Src); 9789 SDValue Ops[] = { 9790 Src.getOperand(0), // Chain 9791 Src.getOperand(1), // rsrc 9792 Src.getOperand(2), // vindex 9793 Src.getOperand(3), // voffset 9794 Src.getOperand(4), // soffset 9795 Src.getOperand(5), // offset 9796 Src.getOperand(6), 9797 Src.getOperand(7) 9798 }; 9799 // replace with BUFFER_LOAD_BYTE/SHORT 9800 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9801 Src.getOperand(0).getValueType()); 9802 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9803 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9804 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9805 ResList, 9806 Ops, M->getMemoryVT(), 9807 M->getMemOperand()); 9808 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9809 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9810 } 9811 return SDValue(); 9812 } 9813 9814 SDValue SITargetLowering::performClassCombine(SDNode *N, 9815 DAGCombinerInfo &DCI) const { 9816 SelectionDAG &DAG = DCI.DAG; 9817 SDValue Mask = N->getOperand(1); 9818 9819 // fp_class x, 0 -> false 9820 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9821 if (CMask->isZero()) 9822 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9823 } 9824 9825 if (N->getOperand(0).isUndef()) 9826 return DAG.getUNDEF(MVT::i1); 9827 9828 return SDValue(); 9829 } 9830 9831 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9832 DAGCombinerInfo &DCI) const { 9833 EVT VT = N->getValueType(0); 9834 SDValue N0 = N->getOperand(0); 9835 9836 if (N0.isUndef()) 9837 return N0; 9838 9839 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9840 N0.getOpcode() == ISD::SINT_TO_FP)) { 9841 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9842 N->getFlags()); 9843 } 9844 9845 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9846 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9847 N0.getOperand(0), N->getFlags()); 9848 } 9849 9850 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9851 } 9852 9853 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9854 unsigned MaxDepth) const { 9855 unsigned Opcode = Op.getOpcode(); 9856 if (Opcode == ISD::FCANONICALIZE) 9857 return true; 9858 9859 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9860 auto F = CFP->getValueAPF(); 9861 if (F.isNaN() && F.isSignaling()) 9862 return false; 9863 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9864 } 9865 9866 // If source is a result of another standard FP operation it is already in 9867 // canonical form. 9868 if (MaxDepth == 0) 9869 return false; 9870 9871 switch (Opcode) { 9872 // These will flush denorms if required. 9873 case ISD::FADD: 9874 case ISD::FSUB: 9875 case ISD::FMUL: 9876 case ISD::FCEIL: 9877 case ISD::FFLOOR: 9878 case ISD::FMA: 9879 case ISD::FMAD: 9880 case ISD::FSQRT: 9881 case ISD::FDIV: 9882 case ISD::FREM: 9883 case ISD::FP_ROUND: 9884 case ISD::FP_EXTEND: 9885 case AMDGPUISD::FMUL_LEGACY: 9886 case AMDGPUISD::FMAD_FTZ: 9887 case AMDGPUISD::RCP: 9888 case AMDGPUISD::RSQ: 9889 case AMDGPUISD::RSQ_CLAMP: 9890 case AMDGPUISD::RCP_LEGACY: 9891 case AMDGPUISD::RCP_IFLAG: 9892 case AMDGPUISD::DIV_SCALE: 9893 case AMDGPUISD::DIV_FMAS: 9894 case AMDGPUISD::DIV_FIXUP: 9895 case AMDGPUISD::FRACT: 9896 case AMDGPUISD::LDEXP: 9897 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9898 case AMDGPUISD::CVT_F32_UBYTE0: 9899 case AMDGPUISD::CVT_F32_UBYTE1: 9900 case AMDGPUISD::CVT_F32_UBYTE2: 9901 case AMDGPUISD::CVT_F32_UBYTE3: 9902 return true; 9903 9904 // It can/will be lowered or combined as a bit operation. 9905 // Need to check their input recursively to handle. 9906 case ISD::FNEG: 9907 case ISD::FABS: 9908 case ISD::FCOPYSIGN: 9909 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9910 9911 case ISD::FSIN: 9912 case ISD::FCOS: 9913 case ISD::FSINCOS: 9914 return Op.getValueType().getScalarType() != MVT::f16; 9915 9916 case ISD::FMINNUM: 9917 case ISD::FMAXNUM: 9918 case ISD::FMINNUM_IEEE: 9919 case ISD::FMAXNUM_IEEE: 9920 case AMDGPUISD::CLAMP: 9921 case AMDGPUISD::FMED3: 9922 case AMDGPUISD::FMAX3: 9923 case AMDGPUISD::FMIN3: { 9924 // FIXME: Shouldn't treat the generic operations different based these. 9925 // However, we aren't really required to flush the result from 9926 // minnum/maxnum.. 9927 9928 // snans will be quieted, so we only need to worry about denormals. 9929 if (Subtarget->supportsMinMaxDenormModes() || 9930 denormalsEnabledForType(DAG, Op.getValueType())) 9931 return true; 9932 9933 // Flushing may be required. 9934 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9935 // targets need to check their input recursively. 9936 9937 // FIXME: Does this apply with clamp? It's implemented with max. 9938 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9939 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9940 return false; 9941 } 9942 9943 return true; 9944 } 9945 case ISD::SELECT: { 9946 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9947 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9948 } 9949 case ISD::BUILD_VECTOR: { 9950 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9951 SDValue SrcOp = Op.getOperand(i); 9952 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9953 return false; 9954 } 9955 9956 return true; 9957 } 9958 case ISD::EXTRACT_VECTOR_ELT: 9959 case ISD::EXTRACT_SUBVECTOR: { 9960 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9961 } 9962 case ISD::INSERT_VECTOR_ELT: { 9963 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9964 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9965 } 9966 case ISD::UNDEF: 9967 // Could be anything. 9968 return false; 9969 9970 case ISD::BITCAST: 9971 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9972 case ISD::TRUNCATE: { 9973 // Hack round the mess we make when legalizing extract_vector_elt 9974 if (Op.getValueType() == MVT::i16) { 9975 SDValue TruncSrc = Op.getOperand(0); 9976 if (TruncSrc.getValueType() == MVT::i32 && 9977 TruncSrc.getOpcode() == ISD::BITCAST && 9978 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9979 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9980 } 9981 } 9982 return false; 9983 } 9984 case ISD::INTRINSIC_WO_CHAIN: { 9985 unsigned IntrinsicID 9986 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9987 // TODO: Handle more intrinsics 9988 switch (IntrinsicID) { 9989 case Intrinsic::amdgcn_cvt_pkrtz: 9990 case Intrinsic::amdgcn_cubeid: 9991 case Intrinsic::amdgcn_frexp_mant: 9992 case Intrinsic::amdgcn_fdot2: 9993 case Intrinsic::amdgcn_rcp: 9994 case Intrinsic::amdgcn_rsq: 9995 case Intrinsic::amdgcn_rsq_clamp: 9996 case Intrinsic::amdgcn_rcp_legacy: 9997 case Intrinsic::amdgcn_rsq_legacy: 9998 case Intrinsic::amdgcn_trig_preop: 9999 return true; 10000 default: 10001 break; 10002 } 10003 10004 LLVM_FALLTHROUGH; 10005 } 10006 default: 10007 return denormalsEnabledForType(DAG, Op.getValueType()) && 10008 DAG.isKnownNeverSNaN(Op); 10009 } 10010 10011 llvm_unreachable("invalid operation"); 10012 } 10013 10014 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 10015 unsigned MaxDepth) const { 10016 MachineRegisterInfo &MRI = MF.getRegInfo(); 10017 MachineInstr *MI = MRI.getVRegDef(Reg); 10018 unsigned Opcode = MI->getOpcode(); 10019 10020 if (Opcode == AMDGPU::G_FCANONICALIZE) 10021 return true; 10022 10023 Optional<FPValueAndVReg> FCR; 10024 // Constant splat (can be padded with undef) or scalar constant. 10025 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 10026 if (FCR->Value.isSignaling()) 10027 return false; 10028 return !FCR->Value.isDenormal() || 10029 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 10030 } 10031 10032 if (MaxDepth == 0) 10033 return false; 10034 10035 switch (Opcode) { 10036 case AMDGPU::G_FMINNUM_IEEE: 10037 case AMDGPU::G_FMAXNUM_IEEE: { 10038 if (Subtarget->supportsMinMaxDenormModes() || 10039 denormalsEnabledForType(MRI.getType(Reg), MF)) 10040 return true; 10041 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 10042 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 10043 return false; 10044 return true; 10045 } 10046 default: 10047 return denormalsEnabledForType(MRI.getType(Reg), MF) && 10048 isKnownNeverSNaN(Reg, MRI); 10049 } 10050 10051 llvm_unreachable("invalid operation"); 10052 } 10053 10054 // Constant fold canonicalize. 10055 SDValue SITargetLowering::getCanonicalConstantFP( 10056 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 10057 // Flush denormals to 0 if not enabled. 10058 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 10059 return DAG.getConstantFP(0.0, SL, VT); 10060 10061 if (C.isNaN()) { 10062 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 10063 if (C.isSignaling()) { 10064 // Quiet a signaling NaN. 10065 // FIXME: Is this supposed to preserve payload bits? 10066 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10067 } 10068 10069 // Make sure it is the canonical NaN bitpattern. 10070 // 10071 // TODO: Can we use -1 as the canonical NaN value since it's an inline 10072 // immediate? 10073 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 10074 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 10075 } 10076 10077 // Already canonical. 10078 return DAG.getConstantFP(C, SL, VT); 10079 } 10080 10081 static bool vectorEltWillFoldAway(SDValue Op) { 10082 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 10083 } 10084 10085 SDValue SITargetLowering::performFCanonicalizeCombine( 10086 SDNode *N, 10087 DAGCombinerInfo &DCI) const { 10088 SelectionDAG &DAG = DCI.DAG; 10089 SDValue N0 = N->getOperand(0); 10090 EVT VT = N->getValueType(0); 10091 10092 // fcanonicalize undef -> qnan 10093 if (N0.isUndef()) { 10094 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 10095 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 10096 } 10097 10098 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 10099 EVT VT = N->getValueType(0); 10100 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 10101 } 10102 10103 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 10104 // (fcanonicalize k) 10105 // 10106 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 10107 10108 // TODO: This could be better with wider vectors that will be split to v2f16, 10109 // and to consider uses since there aren't that many packed operations. 10110 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 10111 isTypeLegal(MVT::v2f16)) { 10112 SDLoc SL(N); 10113 SDValue NewElts[2]; 10114 SDValue Lo = N0.getOperand(0); 10115 SDValue Hi = N0.getOperand(1); 10116 EVT EltVT = Lo.getValueType(); 10117 10118 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 10119 for (unsigned I = 0; I != 2; ++I) { 10120 SDValue Op = N0.getOperand(I); 10121 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 10122 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 10123 CFP->getValueAPF()); 10124 } else if (Op.isUndef()) { 10125 // Handled below based on what the other operand is. 10126 NewElts[I] = Op; 10127 } else { 10128 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 10129 } 10130 } 10131 10132 // If one half is undef, and one is constant, prefer a splat vector rather 10133 // than the normal qNaN. If it's a register, prefer 0.0 since that's 10134 // cheaper to use and may be free with a packed operation. 10135 if (NewElts[0].isUndef()) { 10136 if (isa<ConstantFPSDNode>(NewElts[1])) 10137 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 10138 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 10139 } 10140 10141 if (NewElts[1].isUndef()) { 10142 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 10143 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 10144 } 10145 10146 return DAG.getBuildVector(VT, SL, NewElts); 10147 } 10148 } 10149 10150 unsigned SrcOpc = N0.getOpcode(); 10151 10152 // If it's free to do so, push canonicalizes further up the source, which may 10153 // find a canonical source. 10154 // 10155 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 10156 // sNaNs. 10157 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 10158 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 10159 if (CRHS && N0.hasOneUse()) { 10160 SDLoc SL(N); 10161 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 10162 N0.getOperand(0)); 10163 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 10164 DCI.AddToWorklist(Canon0.getNode()); 10165 10166 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 10167 } 10168 } 10169 10170 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 10171 } 10172 10173 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 10174 switch (Opc) { 10175 case ISD::FMAXNUM: 10176 case ISD::FMAXNUM_IEEE: 10177 return AMDGPUISD::FMAX3; 10178 case ISD::SMAX: 10179 return AMDGPUISD::SMAX3; 10180 case ISD::UMAX: 10181 return AMDGPUISD::UMAX3; 10182 case ISD::FMINNUM: 10183 case ISD::FMINNUM_IEEE: 10184 return AMDGPUISD::FMIN3; 10185 case ISD::SMIN: 10186 return AMDGPUISD::SMIN3; 10187 case ISD::UMIN: 10188 return AMDGPUISD::UMIN3; 10189 default: 10190 llvm_unreachable("Not a min/max opcode"); 10191 } 10192 } 10193 10194 SDValue SITargetLowering::performIntMed3ImmCombine( 10195 SelectionDAG &DAG, const SDLoc &SL, 10196 SDValue Op0, SDValue Op1, bool Signed) const { 10197 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10198 if (!K1) 10199 return SDValue(); 10200 10201 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10202 if (!K0) 10203 return SDValue(); 10204 10205 if (Signed) { 10206 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10207 return SDValue(); 10208 } else { 10209 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10210 return SDValue(); 10211 } 10212 10213 EVT VT = K0->getValueType(0); 10214 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10215 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10216 return DAG.getNode(Med3Opc, SL, VT, 10217 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10218 } 10219 10220 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10221 if (VT == MVT::i16) { 10222 MVT NVT = MVT::i32; 10223 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10224 10225 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10226 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10227 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10228 10229 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10230 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10231 } 10232 10233 return SDValue(); 10234 } 10235 10236 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10237 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10238 return C; 10239 10240 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10241 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10242 return C; 10243 } 10244 10245 return nullptr; 10246 } 10247 10248 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10249 const SDLoc &SL, 10250 SDValue Op0, 10251 SDValue Op1) const { 10252 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10253 if (!K1) 10254 return SDValue(); 10255 10256 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10257 if (!K0) 10258 return SDValue(); 10259 10260 // Ordered >= (although NaN inputs should have folded away by now). 10261 if (K0->getValueAPF() > K1->getValueAPF()) 10262 return SDValue(); 10263 10264 const MachineFunction &MF = DAG.getMachineFunction(); 10265 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10266 10267 // TODO: Check IEEE bit enabled? 10268 EVT VT = Op0.getValueType(); 10269 if (Info->getMode().DX10Clamp) { 10270 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10271 // hardware fmed3 behavior converting to a min. 10272 // FIXME: Should this be allowing -0.0? 10273 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10274 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10275 } 10276 10277 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10278 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10279 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10280 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10281 // then give the other result, which is different from med3 with a NaN 10282 // input. 10283 SDValue Var = Op0.getOperand(0); 10284 if (!DAG.isKnownNeverSNaN(Var)) 10285 return SDValue(); 10286 10287 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10288 10289 if ((!K0->hasOneUse() || 10290 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10291 (!K1->hasOneUse() || 10292 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10293 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10294 Var, SDValue(K0, 0), SDValue(K1, 0)); 10295 } 10296 } 10297 10298 return SDValue(); 10299 } 10300 10301 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10302 DAGCombinerInfo &DCI) const { 10303 SelectionDAG &DAG = DCI.DAG; 10304 10305 EVT VT = N->getValueType(0); 10306 unsigned Opc = N->getOpcode(); 10307 SDValue Op0 = N->getOperand(0); 10308 SDValue Op1 = N->getOperand(1); 10309 10310 // Only do this if the inner op has one use since this will just increases 10311 // register pressure for no benefit. 10312 10313 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10314 !VT.isVector() && 10315 (VT == MVT::i32 || VT == MVT::f32 || 10316 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10317 // max(max(a, b), c) -> max3(a, b, c) 10318 // min(min(a, b), c) -> min3(a, b, c) 10319 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10320 SDLoc DL(N); 10321 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10322 DL, 10323 N->getValueType(0), 10324 Op0.getOperand(0), 10325 Op0.getOperand(1), 10326 Op1); 10327 } 10328 10329 // Try commuted. 10330 // max(a, max(b, c)) -> max3(a, b, c) 10331 // min(a, min(b, c)) -> min3(a, b, c) 10332 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10333 SDLoc DL(N); 10334 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10335 DL, 10336 N->getValueType(0), 10337 Op0, 10338 Op1.getOperand(0), 10339 Op1.getOperand(1)); 10340 } 10341 } 10342 10343 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10344 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10345 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10346 return Med3; 10347 } 10348 10349 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10350 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10351 return Med3; 10352 } 10353 10354 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10355 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10356 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10357 (Opc == AMDGPUISD::FMIN_LEGACY && 10358 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10359 (VT == MVT::f32 || VT == MVT::f64 || 10360 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10361 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10362 Op0.hasOneUse()) { 10363 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10364 return Res; 10365 } 10366 10367 return SDValue(); 10368 } 10369 10370 static bool isClampZeroToOne(SDValue A, SDValue B) { 10371 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10372 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10373 // FIXME: Should this be allowing -0.0? 10374 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10375 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10376 } 10377 } 10378 10379 return false; 10380 } 10381 10382 // FIXME: Should only worry about snans for version with chain. 10383 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10384 DAGCombinerInfo &DCI) const { 10385 EVT VT = N->getValueType(0); 10386 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10387 // NaNs. With a NaN input, the order of the operands may change the result. 10388 10389 SelectionDAG &DAG = DCI.DAG; 10390 SDLoc SL(N); 10391 10392 SDValue Src0 = N->getOperand(0); 10393 SDValue Src1 = N->getOperand(1); 10394 SDValue Src2 = N->getOperand(2); 10395 10396 if (isClampZeroToOne(Src0, Src1)) { 10397 // const_a, const_b, x -> clamp is safe in all cases including signaling 10398 // nans. 10399 // FIXME: Should this be allowing -0.0? 10400 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10401 } 10402 10403 const MachineFunction &MF = DAG.getMachineFunction(); 10404 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10405 10406 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10407 // handling no dx10-clamp? 10408 if (Info->getMode().DX10Clamp) { 10409 // If NaNs is clamped to 0, we are free to reorder the inputs. 10410 10411 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10412 std::swap(Src0, Src1); 10413 10414 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10415 std::swap(Src1, Src2); 10416 10417 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10418 std::swap(Src0, Src1); 10419 10420 if (isClampZeroToOne(Src1, Src2)) 10421 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10422 } 10423 10424 return SDValue(); 10425 } 10426 10427 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10428 DAGCombinerInfo &DCI) const { 10429 SDValue Src0 = N->getOperand(0); 10430 SDValue Src1 = N->getOperand(1); 10431 if (Src0.isUndef() && Src1.isUndef()) 10432 return DCI.DAG.getUNDEF(N->getValueType(0)); 10433 return SDValue(); 10434 } 10435 10436 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10437 // expanded into a set of cmp/select instructions. 10438 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10439 unsigned NumElem, 10440 bool IsDivergentIdx) { 10441 if (UseDivergentRegisterIndexing) 10442 return false; 10443 10444 unsigned VecSize = EltSize * NumElem; 10445 10446 // Sub-dword vectors of size 2 dword or less have better implementation. 10447 if (VecSize <= 64 && EltSize < 32) 10448 return false; 10449 10450 // Always expand the rest of sub-dword instructions, otherwise it will be 10451 // lowered via memory. 10452 if (EltSize < 32) 10453 return true; 10454 10455 // Always do this if var-idx is divergent, otherwise it will become a loop. 10456 if (IsDivergentIdx) 10457 return true; 10458 10459 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10460 unsigned NumInsts = NumElem /* Number of compares */ + 10461 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10462 return NumInsts <= 16; 10463 } 10464 10465 static bool shouldExpandVectorDynExt(SDNode *N) { 10466 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10467 if (isa<ConstantSDNode>(Idx)) 10468 return false; 10469 10470 SDValue Vec = N->getOperand(0); 10471 EVT VecVT = Vec.getValueType(); 10472 EVT EltVT = VecVT.getVectorElementType(); 10473 unsigned EltSize = EltVT.getSizeInBits(); 10474 unsigned NumElem = VecVT.getVectorNumElements(); 10475 10476 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10477 Idx->isDivergent()); 10478 } 10479 10480 SDValue SITargetLowering::performExtractVectorEltCombine( 10481 SDNode *N, DAGCombinerInfo &DCI) const { 10482 SDValue Vec = N->getOperand(0); 10483 SelectionDAG &DAG = DCI.DAG; 10484 10485 EVT VecVT = Vec.getValueType(); 10486 EVT EltVT = VecVT.getVectorElementType(); 10487 10488 if ((Vec.getOpcode() == ISD::FNEG || 10489 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10490 SDLoc SL(N); 10491 EVT EltVT = N->getValueType(0); 10492 SDValue Idx = N->getOperand(1); 10493 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10494 Vec.getOperand(0), Idx); 10495 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10496 } 10497 10498 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10499 // => 10500 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10501 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10502 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10503 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10504 SDLoc SL(N); 10505 EVT EltVT = N->getValueType(0); 10506 SDValue Idx = N->getOperand(1); 10507 unsigned Opc = Vec.getOpcode(); 10508 10509 switch(Opc) { 10510 default: 10511 break; 10512 // TODO: Support other binary operations. 10513 case ISD::FADD: 10514 case ISD::FSUB: 10515 case ISD::FMUL: 10516 case ISD::ADD: 10517 case ISD::UMIN: 10518 case ISD::UMAX: 10519 case ISD::SMIN: 10520 case ISD::SMAX: 10521 case ISD::FMAXNUM: 10522 case ISD::FMINNUM: 10523 case ISD::FMAXNUM_IEEE: 10524 case ISD::FMINNUM_IEEE: { 10525 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10526 Vec.getOperand(0), Idx); 10527 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10528 Vec.getOperand(1), Idx); 10529 10530 DCI.AddToWorklist(Elt0.getNode()); 10531 DCI.AddToWorklist(Elt1.getNode()); 10532 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10533 } 10534 } 10535 } 10536 10537 unsigned VecSize = VecVT.getSizeInBits(); 10538 unsigned EltSize = EltVT.getSizeInBits(); 10539 10540 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10541 if (::shouldExpandVectorDynExt(N)) { 10542 SDLoc SL(N); 10543 SDValue Idx = N->getOperand(1); 10544 SDValue V; 10545 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10546 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10547 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10548 if (I == 0) 10549 V = Elt; 10550 else 10551 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10552 } 10553 return V; 10554 } 10555 10556 if (!DCI.isBeforeLegalize()) 10557 return SDValue(); 10558 10559 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10560 // elements. This exposes more load reduction opportunities by replacing 10561 // multiple small extract_vector_elements with a single 32-bit extract. 10562 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10563 if (isa<MemSDNode>(Vec) && 10564 EltSize <= 16 && 10565 EltVT.isByteSized() && 10566 VecSize > 32 && 10567 VecSize % 32 == 0 && 10568 Idx) { 10569 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10570 10571 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10572 unsigned EltIdx = BitIndex / 32; 10573 unsigned LeftoverBitIdx = BitIndex % 32; 10574 SDLoc SL(N); 10575 10576 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10577 DCI.AddToWorklist(Cast.getNode()); 10578 10579 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10580 DAG.getConstant(EltIdx, SL, MVT::i32)); 10581 DCI.AddToWorklist(Elt.getNode()); 10582 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10583 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10584 DCI.AddToWorklist(Srl.getNode()); 10585 10586 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10587 DCI.AddToWorklist(Trunc.getNode()); 10588 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10589 } 10590 10591 return SDValue(); 10592 } 10593 10594 SDValue 10595 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10596 DAGCombinerInfo &DCI) const { 10597 SDValue Vec = N->getOperand(0); 10598 SDValue Idx = N->getOperand(2); 10599 EVT VecVT = Vec.getValueType(); 10600 EVT EltVT = VecVT.getVectorElementType(); 10601 10602 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10603 // => BUILD_VECTOR n x select (e, const-idx) 10604 if (!::shouldExpandVectorDynExt(N)) 10605 return SDValue(); 10606 10607 SelectionDAG &DAG = DCI.DAG; 10608 SDLoc SL(N); 10609 SDValue Ins = N->getOperand(1); 10610 EVT IdxVT = Idx.getValueType(); 10611 10612 SmallVector<SDValue, 16> Ops; 10613 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10614 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10615 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10616 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10617 Ops.push_back(V); 10618 } 10619 10620 return DAG.getBuildVector(VecVT, SL, Ops); 10621 } 10622 10623 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10624 const SDNode *N0, 10625 const SDNode *N1) const { 10626 EVT VT = N0->getValueType(0); 10627 10628 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10629 // support denormals ever. 10630 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10631 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10632 getSubtarget()->hasMadF16())) && 10633 isOperationLegal(ISD::FMAD, VT)) 10634 return ISD::FMAD; 10635 10636 const TargetOptions &Options = DAG.getTarget().Options; 10637 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10638 (N0->getFlags().hasAllowContract() && 10639 N1->getFlags().hasAllowContract())) && 10640 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10641 return ISD::FMA; 10642 } 10643 10644 return 0; 10645 } 10646 10647 // For a reassociatable opcode perform: 10648 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10649 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10650 SelectionDAG &DAG) const { 10651 EVT VT = N->getValueType(0); 10652 if (VT != MVT::i32 && VT != MVT::i64) 10653 return SDValue(); 10654 10655 if (DAG.isBaseWithConstantOffset(SDValue(N, 0))) 10656 return SDValue(); 10657 10658 unsigned Opc = N->getOpcode(); 10659 SDValue Op0 = N->getOperand(0); 10660 SDValue Op1 = N->getOperand(1); 10661 10662 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10663 return SDValue(); 10664 10665 if (Op0->isDivergent()) 10666 std::swap(Op0, Op1); 10667 10668 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10669 return SDValue(); 10670 10671 SDValue Op2 = Op1.getOperand(1); 10672 Op1 = Op1.getOperand(0); 10673 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10674 return SDValue(); 10675 10676 if (Op1->isDivergent()) 10677 std::swap(Op1, Op2); 10678 10679 SDLoc SL(N); 10680 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10681 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10682 } 10683 10684 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10685 EVT VT, 10686 SDValue N0, SDValue N1, SDValue N2, 10687 bool Signed) { 10688 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10689 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10690 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10691 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10692 } 10693 10694 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high 10695 // multiplies, if any. 10696 // 10697 // Full 64-bit multiplies that feed into an addition are lowered here instead 10698 // of using the generic expansion. The generic expansion ends up with 10699 // a tree of ADD nodes that prevents us from using the "add" part of the 10700 // MAD instruction. The expansion produced here results in a chain of ADDs 10701 // instead of a tree. 10702 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N, 10703 DAGCombinerInfo &DCI) const { 10704 assert(N->getOpcode() == ISD::ADD); 10705 10706 SelectionDAG &DAG = DCI.DAG; 10707 EVT VT = N->getValueType(0); 10708 SDLoc SL(N); 10709 SDValue LHS = N->getOperand(0); 10710 SDValue RHS = N->getOperand(1); 10711 10712 if (VT.isVector()) 10713 return SDValue(); 10714 10715 // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall 10716 // result in scalar registers for uniform values. 10717 if (!N->isDivergent() && Subtarget->hasSMulHi()) 10718 return SDValue(); 10719 10720 unsigned NumBits = VT.getScalarSizeInBits(); 10721 if (NumBits <= 32 || NumBits > 64) 10722 return SDValue(); 10723 10724 if (LHS.getOpcode() != ISD::MUL) { 10725 assert(RHS.getOpcode() == ISD::MUL); 10726 std::swap(LHS, RHS); 10727 } 10728 10729 // Avoid the fold if it would unduly increase the number of multiplies due to 10730 // multiple uses, except on hardware with full-rate multiply-add (which is 10731 // part of full-rate 64-bit ops). 10732 if (!Subtarget->hasFullRate64Ops()) { 10733 unsigned NumUsers = 0; 10734 for (SDNode *Use : LHS->uses()) { 10735 // There is a use that does not feed into addition, so the multiply can't 10736 // be removed. We prefer MUL + ADD + ADDC over MAD + MUL. 10737 if (Use->getOpcode() != ISD::ADD) 10738 return SDValue(); 10739 10740 // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer 10741 // MUL + 3xADD + 3xADDC over 3xMAD. 10742 ++NumUsers; 10743 if (NumUsers >= 3) 10744 return SDValue(); 10745 } 10746 } 10747 10748 SDValue MulLHS = LHS.getOperand(0); 10749 SDValue MulRHS = LHS.getOperand(1); 10750 SDValue AddRHS = RHS; 10751 10752 // Always check whether operands are small unsigned values, since that 10753 // knowledge is useful in more cases. Check for small signed values only if 10754 // doing so can unlock a shorter code sequence. 10755 bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32; 10756 bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32; 10757 10758 bool MulSignedLo = false; 10759 if (!MulLHSUnsigned32 || !MulRHSUnsigned32) { 10760 MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 && 10761 numBitsSigned(MulRHS, DAG) <= 32; 10762 } 10763 10764 // The operands and final result all have the same number of bits. If 10765 // operands need to be extended, they can be extended with garbage. The 10766 // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is 10767 // truncated away in the end. 10768 if (VT != MVT::i64) { 10769 MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS); 10770 MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS); 10771 AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS); 10772 } 10773 10774 // The basic code generated is conceptually straightforward. Pseudo code: 10775 // 10776 // accum = mad_64_32 lhs.lo, rhs.lo, accum 10777 // accum.hi = add (mul lhs.hi, rhs.lo), accum.hi 10778 // accum.hi = add (mul lhs.lo, rhs.hi), accum.hi 10779 // 10780 // The second and third lines are optional, depending on whether the factors 10781 // are {sign,zero}-extended or not. 10782 // 10783 // The actual DAG is noisier than the pseudo code, but only due to 10784 // instructions that disassemble values into low and high parts, and 10785 // assemble the final result. 10786 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 10787 SDValue One = DAG.getConstant(1, SL, MVT::i32); 10788 10789 auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS); 10790 auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS); 10791 SDValue Accum = 10792 getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo); 10793 10794 if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) { 10795 auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero); 10796 auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One); 10797 10798 if (!MulLHSUnsigned32) { 10799 auto MulLHSHi = 10800 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One); 10801 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo); 10802 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10803 } 10804 10805 if (!MulRHSUnsigned32) { 10806 auto MulRHSHi = 10807 DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One); 10808 SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi); 10809 AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi); 10810 } 10811 10812 Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi}); 10813 Accum = DAG.getBitcast(MVT::i64, Accum); 10814 } 10815 10816 if (VT != MVT::i64) 10817 Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum); 10818 return Accum; 10819 } 10820 10821 SDValue SITargetLowering::performAddCombine(SDNode *N, 10822 DAGCombinerInfo &DCI) const { 10823 SelectionDAG &DAG = DCI.DAG; 10824 EVT VT = N->getValueType(0); 10825 SDLoc SL(N); 10826 SDValue LHS = N->getOperand(0); 10827 SDValue RHS = N->getOperand(1); 10828 10829 if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) { 10830 if (Subtarget->hasMad64_32()) { 10831 if (SDValue Folded = tryFoldToMad64_32(N, DCI)) 10832 return Folded; 10833 } 10834 10835 return SDValue(); 10836 } 10837 10838 if (SDValue V = reassociateScalarOps(N, DAG)) { 10839 return V; 10840 } 10841 10842 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10843 return SDValue(); 10844 10845 // add x, zext (setcc) => addcarry x, 0, setcc 10846 // add x, sext (setcc) => subcarry x, 0, setcc 10847 unsigned Opc = LHS.getOpcode(); 10848 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10849 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10850 std::swap(RHS, LHS); 10851 10852 Opc = RHS.getOpcode(); 10853 switch (Opc) { 10854 default: break; 10855 case ISD::ZERO_EXTEND: 10856 case ISD::SIGN_EXTEND: 10857 case ISD::ANY_EXTEND: { 10858 auto Cond = RHS.getOperand(0); 10859 // If this won't be a real VOPC output, we would still need to insert an 10860 // extra instruction anyway. 10861 if (!isBoolSGPR(Cond)) 10862 break; 10863 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10864 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10865 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10866 return DAG.getNode(Opc, SL, VTList, Args); 10867 } 10868 case ISD::ADDCARRY: { 10869 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10870 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10871 if (!C || C->getZExtValue() != 0) break; 10872 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10873 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10874 } 10875 } 10876 return SDValue(); 10877 } 10878 10879 SDValue SITargetLowering::performSubCombine(SDNode *N, 10880 DAGCombinerInfo &DCI) const { 10881 SelectionDAG &DAG = DCI.DAG; 10882 EVT VT = N->getValueType(0); 10883 10884 if (VT != MVT::i32) 10885 return SDValue(); 10886 10887 SDLoc SL(N); 10888 SDValue LHS = N->getOperand(0); 10889 SDValue RHS = N->getOperand(1); 10890 10891 // sub x, zext (setcc) => subcarry x, 0, setcc 10892 // sub x, sext (setcc) => addcarry x, 0, setcc 10893 unsigned Opc = RHS.getOpcode(); 10894 switch (Opc) { 10895 default: break; 10896 case ISD::ZERO_EXTEND: 10897 case ISD::SIGN_EXTEND: 10898 case ISD::ANY_EXTEND: { 10899 auto Cond = RHS.getOperand(0); 10900 // If this won't be a real VOPC output, we would still need to insert an 10901 // extra instruction anyway. 10902 if (!isBoolSGPR(Cond)) 10903 break; 10904 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10905 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10906 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10907 return DAG.getNode(Opc, SL, VTList, Args); 10908 } 10909 } 10910 10911 if (LHS.getOpcode() == ISD::SUBCARRY) { 10912 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10913 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10914 if (!C || !C->isZero()) 10915 return SDValue(); 10916 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10917 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10918 } 10919 return SDValue(); 10920 } 10921 10922 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10923 DAGCombinerInfo &DCI) const { 10924 10925 if (N->getValueType(0) != MVT::i32) 10926 return SDValue(); 10927 10928 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10929 if (!C || C->getZExtValue() != 0) 10930 return SDValue(); 10931 10932 SelectionDAG &DAG = DCI.DAG; 10933 SDValue LHS = N->getOperand(0); 10934 10935 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10936 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10937 unsigned LHSOpc = LHS.getOpcode(); 10938 unsigned Opc = N->getOpcode(); 10939 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10940 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10941 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10942 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10943 } 10944 return SDValue(); 10945 } 10946 10947 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10948 DAGCombinerInfo &DCI) const { 10949 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10950 return SDValue(); 10951 10952 SelectionDAG &DAG = DCI.DAG; 10953 EVT VT = N->getValueType(0); 10954 10955 SDLoc SL(N); 10956 SDValue LHS = N->getOperand(0); 10957 SDValue RHS = N->getOperand(1); 10958 10959 // These should really be instruction patterns, but writing patterns with 10960 // source modifiers is a pain. 10961 10962 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10963 if (LHS.getOpcode() == ISD::FADD) { 10964 SDValue A = LHS.getOperand(0); 10965 if (A == LHS.getOperand(1)) { 10966 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10967 if (FusedOp != 0) { 10968 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10969 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10970 } 10971 } 10972 } 10973 10974 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10975 if (RHS.getOpcode() == ISD::FADD) { 10976 SDValue A = RHS.getOperand(0); 10977 if (A == RHS.getOperand(1)) { 10978 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10979 if (FusedOp != 0) { 10980 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10981 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10982 } 10983 } 10984 } 10985 10986 return SDValue(); 10987 } 10988 10989 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10990 DAGCombinerInfo &DCI) const { 10991 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10992 return SDValue(); 10993 10994 SelectionDAG &DAG = DCI.DAG; 10995 SDLoc SL(N); 10996 EVT VT = N->getValueType(0); 10997 assert(!VT.isVector()); 10998 10999 // Try to get the fneg to fold into the source modifier. This undoes generic 11000 // DAG combines and folds them into the mad. 11001 // 11002 // Only do this if we are not trying to support denormals. v_mad_f32 does 11003 // not support denormals ever. 11004 SDValue LHS = N->getOperand(0); 11005 SDValue RHS = N->getOperand(1); 11006 if (LHS.getOpcode() == ISD::FADD) { 11007 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 11008 SDValue A = LHS.getOperand(0); 11009 if (A == LHS.getOperand(1)) { 11010 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 11011 if (FusedOp != 0){ 11012 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 11013 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 11014 11015 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 11016 } 11017 } 11018 } 11019 11020 if (RHS.getOpcode() == ISD::FADD) { 11021 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 11022 11023 SDValue A = RHS.getOperand(0); 11024 if (A == RHS.getOperand(1)) { 11025 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 11026 if (FusedOp != 0){ 11027 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 11028 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 11029 } 11030 } 11031 } 11032 11033 return SDValue(); 11034 } 11035 11036 SDValue SITargetLowering::performFMACombine(SDNode *N, 11037 DAGCombinerInfo &DCI) const { 11038 SelectionDAG &DAG = DCI.DAG; 11039 EVT VT = N->getValueType(0); 11040 SDLoc SL(N); 11041 11042 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 11043 return SDValue(); 11044 11045 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 11046 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 11047 SDValue Op1 = N->getOperand(0); 11048 SDValue Op2 = N->getOperand(1); 11049 SDValue FMA = N->getOperand(2); 11050 11051 if (FMA.getOpcode() != ISD::FMA || 11052 Op1.getOpcode() != ISD::FP_EXTEND || 11053 Op2.getOpcode() != ISD::FP_EXTEND) 11054 return SDValue(); 11055 11056 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 11057 // regardless of the denorm mode setting. Therefore, 11058 // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2. 11059 const TargetOptions &Options = DAG.getTarget().Options; 11060 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 11061 (N->getFlags().hasAllowContract() && 11062 FMA->getFlags().hasAllowContract())) { 11063 Op1 = Op1.getOperand(0); 11064 Op2 = Op2.getOperand(0); 11065 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11066 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11067 return SDValue(); 11068 11069 SDValue Vec1 = Op1.getOperand(0); 11070 SDValue Idx1 = Op1.getOperand(1); 11071 SDValue Vec2 = Op2.getOperand(0); 11072 11073 SDValue FMAOp1 = FMA.getOperand(0); 11074 SDValue FMAOp2 = FMA.getOperand(1); 11075 SDValue FMAAcc = FMA.getOperand(2); 11076 11077 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 11078 FMAOp2.getOpcode() != ISD::FP_EXTEND) 11079 return SDValue(); 11080 11081 FMAOp1 = FMAOp1.getOperand(0); 11082 FMAOp2 = FMAOp2.getOperand(0); 11083 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11084 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 11085 return SDValue(); 11086 11087 SDValue Vec3 = FMAOp1.getOperand(0); 11088 SDValue Vec4 = FMAOp2.getOperand(0); 11089 SDValue Idx2 = FMAOp1.getOperand(1); 11090 11091 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 11092 // Idx1 and Idx2 cannot be the same. 11093 Idx1 == Idx2) 11094 return SDValue(); 11095 11096 if (Vec1 == Vec2 || Vec3 == Vec4) 11097 return SDValue(); 11098 11099 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 11100 return SDValue(); 11101 11102 if ((Vec1 == Vec3 && Vec2 == Vec4) || 11103 (Vec1 == Vec4 && Vec2 == Vec3)) { 11104 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 11105 DAG.getTargetConstant(0, SL, MVT::i1)); 11106 } 11107 } 11108 return SDValue(); 11109 } 11110 11111 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 11112 DAGCombinerInfo &DCI) const { 11113 SelectionDAG &DAG = DCI.DAG; 11114 SDLoc SL(N); 11115 11116 SDValue LHS = N->getOperand(0); 11117 SDValue RHS = N->getOperand(1); 11118 EVT VT = LHS.getValueType(); 11119 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 11120 11121 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 11122 if (!CRHS) { 11123 CRHS = dyn_cast<ConstantSDNode>(LHS); 11124 if (CRHS) { 11125 std::swap(LHS, RHS); 11126 CC = getSetCCSwappedOperands(CC); 11127 } 11128 } 11129 11130 if (CRHS) { 11131 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 11132 isBoolSGPR(LHS.getOperand(0))) { 11133 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 11134 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 11135 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 11136 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 11137 if ((CRHS->isAllOnes() && 11138 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 11139 (CRHS->isZero() && 11140 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 11141 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11142 DAG.getConstant(-1, SL, MVT::i1)); 11143 if ((CRHS->isAllOnes() && 11144 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 11145 (CRHS->isZero() && 11146 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 11147 return LHS.getOperand(0); 11148 } 11149 11150 const APInt &CRHSVal = CRHS->getAPIntValue(); 11151 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 11152 LHS.getOpcode() == ISD::SELECT && 11153 isa<ConstantSDNode>(LHS.getOperand(1)) && 11154 isa<ConstantSDNode>(LHS.getOperand(2)) && 11155 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 11156 isBoolSGPR(LHS.getOperand(0))) { 11157 // Given CT != FT: 11158 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 11159 // setcc (select cc, CT, CF), CF, ne => cc 11160 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 11161 // setcc (select cc, CT, CF), CT, eq => cc 11162 const APInt &CT = LHS.getConstantOperandAPInt(1); 11163 const APInt &CF = LHS.getConstantOperandAPInt(2); 11164 11165 if ((CF == CRHSVal && CC == ISD::SETEQ) || 11166 (CT == CRHSVal && CC == ISD::SETNE)) 11167 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 11168 DAG.getConstant(-1, SL, MVT::i1)); 11169 if ((CF == CRHSVal && CC == ISD::SETNE) || 11170 (CT == CRHSVal && CC == ISD::SETEQ)) 11171 return LHS.getOperand(0); 11172 } 11173 } 11174 11175 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 11176 VT != MVT::f16)) 11177 return SDValue(); 11178 11179 // Match isinf/isfinite pattern 11180 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 11181 // (fcmp one (fabs x), inf) -> (fp_class x, 11182 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 11183 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 11184 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 11185 if (!CRHS) 11186 return SDValue(); 11187 11188 const APFloat &APF = CRHS->getValueAPF(); 11189 if (APF.isInfinity() && !APF.isNegative()) { 11190 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 11191 SIInstrFlags::N_INFINITY; 11192 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 11193 SIInstrFlags::P_ZERO | 11194 SIInstrFlags::N_NORMAL | 11195 SIInstrFlags::P_NORMAL | 11196 SIInstrFlags::N_SUBNORMAL | 11197 SIInstrFlags::P_SUBNORMAL; 11198 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 11199 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 11200 DAG.getConstant(Mask, SL, MVT::i32)); 11201 } 11202 } 11203 11204 return SDValue(); 11205 } 11206 11207 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 11208 DAGCombinerInfo &DCI) const { 11209 SelectionDAG &DAG = DCI.DAG; 11210 SDLoc SL(N); 11211 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 11212 11213 SDValue Src = N->getOperand(0); 11214 SDValue Shift = N->getOperand(0); 11215 11216 // TODO: Extend type shouldn't matter (assuming legal types). 11217 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 11218 Shift = Shift.getOperand(0); 11219 11220 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 11221 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 11222 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 11223 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 11224 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 11225 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 11226 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 11227 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 11228 SDLoc(Shift.getOperand(0)), MVT::i32); 11229 11230 unsigned ShiftOffset = 8 * Offset; 11231 if (Shift.getOpcode() == ISD::SHL) 11232 ShiftOffset -= C->getZExtValue(); 11233 else 11234 ShiftOffset += C->getZExtValue(); 11235 11236 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 11237 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 11238 MVT::f32, Shifted); 11239 } 11240 } 11241 } 11242 11243 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11244 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 11245 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 11246 // We simplified Src. If this node is not dead, visit it again so it is 11247 // folded properly. 11248 if (N->getOpcode() != ISD::DELETED_NODE) 11249 DCI.AddToWorklist(N); 11250 return SDValue(N, 0); 11251 } 11252 11253 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 11254 if (SDValue DemandedSrc = 11255 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 11256 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 11257 11258 return SDValue(); 11259 } 11260 11261 SDValue SITargetLowering::performClampCombine(SDNode *N, 11262 DAGCombinerInfo &DCI) const { 11263 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 11264 if (!CSrc) 11265 return SDValue(); 11266 11267 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 11268 const APFloat &F = CSrc->getValueAPF(); 11269 APFloat Zero = APFloat::getZero(F.getSemantics()); 11270 if (F < Zero || 11271 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 11272 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 11273 } 11274 11275 APFloat One(F.getSemantics(), "1.0"); 11276 if (F > One) 11277 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 11278 11279 return SDValue(CSrc, 0); 11280 } 11281 11282 11283 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11284 DAGCombinerInfo &DCI) const { 11285 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11286 return SDValue(); 11287 switch (N->getOpcode()) { 11288 case ISD::ADD: 11289 return performAddCombine(N, DCI); 11290 case ISD::SUB: 11291 return performSubCombine(N, DCI); 11292 case ISD::ADDCARRY: 11293 case ISD::SUBCARRY: 11294 return performAddCarrySubCarryCombine(N, DCI); 11295 case ISD::FADD: 11296 return performFAddCombine(N, DCI); 11297 case ISD::FSUB: 11298 return performFSubCombine(N, DCI); 11299 case ISD::SETCC: 11300 return performSetCCCombine(N, DCI); 11301 case ISD::FMAXNUM: 11302 case ISD::FMINNUM: 11303 case ISD::FMAXNUM_IEEE: 11304 case ISD::FMINNUM_IEEE: 11305 case ISD::SMAX: 11306 case ISD::SMIN: 11307 case ISD::UMAX: 11308 case ISD::UMIN: 11309 case AMDGPUISD::FMIN_LEGACY: 11310 case AMDGPUISD::FMAX_LEGACY: 11311 return performMinMaxCombine(N, DCI); 11312 case ISD::FMA: 11313 return performFMACombine(N, DCI); 11314 case ISD::AND: 11315 return performAndCombine(N, DCI); 11316 case ISD::OR: 11317 return performOrCombine(N, DCI); 11318 case ISD::XOR: 11319 return performXorCombine(N, DCI); 11320 case ISD::ZERO_EXTEND: 11321 return performZeroExtendCombine(N, DCI); 11322 case ISD::SIGN_EXTEND_INREG: 11323 return performSignExtendInRegCombine(N , DCI); 11324 case AMDGPUISD::FP_CLASS: 11325 return performClassCombine(N, DCI); 11326 case ISD::FCANONICALIZE: 11327 return performFCanonicalizeCombine(N, DCI); 11328 case AMDGPUISD::RCP: 11329 return performRcpCombine(N, DCI); 11330 case AMDGPUISD::FRACT: 11331 case AMDGPUISD::RSQ: 11332 case AMDGPUISD::RCP_LEGACY: 11333 case AMDGPUISD::RCP_IFLAG: 11334 case AMDGPUISD::RSQ_CLAMP: 11335 case AMDGPUISD::LDEXP: { 11336 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11337 SDValue Src = N->getOperand(0); 11338 if (Src.isUndef()) 11339 return Src; 11340 break; 11341 } 11342 case ISD::SINT_TO_FP: 11343 case ISD::UINT_TO_FP: 11344 return performUCharToFloatCombine(N, DCI); 11345 case AMDGPUISD::CVT_F32_UBYTE0: 11346 case AMDGPUISD::CVT_F32_UBYTE1: 11347 case AMDGPUISD::CVT_F32_UBYTE2: 11348 case AMDGPUISD::CVT_F32_UBYTE3: 11349 return performCvtF32UByteNCombine(N, DCI); 11350 case AMDGPUISD::FMED3: 11351 return performFMed3Combine(N, DCI); 11352 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11353 return performCvtPkRTZCombine(N, DCI); 11354 case AMDGPUISD::CLAMP: 11355 return performClampCombine(N, DCI); 11356 case ISD::SCALAR_TO_VECTOR: { 11357 SelectionDAG &DAG = DCI.DAG; 11358 EVT VT = N->getValueType(0); 11359 11360 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11361 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11362 SDLoc SL(N); 11363 SDValue Src = N->getOperand(0); 11364 EVT EltVT = Src.getValueType(); 11365 if (EltVT == MVT::f16) 11366 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11367 11368 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11369 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11370 } 11371 11372 break; 11373 } 11374 case ISD::EXTRACT_VECTOR_ELT: 11375 return performExtractVectorEltCombine(N, DCI); 11376 case ISD::INSERT_VECTOR_ELT: 11377 return performInsertVectorEltCombine(N, DCI); 11378 case ISD::LOAD: { 11379 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11380 return Widended; 11381 LLVM_FALLTHROUGH; 11382 } 11383 default: { 11384 if (!DCI.isBeforeLegalize()) { 11385 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11386 return performMemSDNodeCombine(MemNode, DCI); 11387 } 11388 11389 break; 11390 } 11391 } 11392 11393 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11394 } 11395 11396 /// Helper function for adjustWritemask 11397 static unsigned SubIdx2Lane(unsigned Idx) { 11398 switch (Idx) { 11399 default: return ~0u; 11400 case AMDGPU::sub0: return 0; 11401 case AMDGPU::sub1: return 1; 11402 case AMDGPU::sub2: return 2; 11403 case AMDGPU::sub3: return 3; 11404 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11405 } 11406 } 11407 11408 /// Adjust the writemask of MIMG instructions 11409 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11410 SelectionDAG &DAG) const { 11411 unsigned Opcode = Node->getMachineOpcode(); 11412 11413 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11414 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11415 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11416 return Node; // not implemented for D16 11417 11418 SDNode *Users[5] = { nullptr }; 11419 unsigned Lane = 0; 11420 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11421 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11422 unsigned NewDmask = 0; 11423 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11424 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11425 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11426 Node->getConstantOperandVal(LWEIdx)) 11427 ? true 11428 : false; 11429 unsigned TFCLane = 0; 11430 bool HasChain = Node->getNumValues() > 1; 11431 11432 if (OldDmask == 0) { 11433 // These are folded out, but on the chance it happens don't assert. 11434 return Node; 11435 } 11436 11437 unsigned OldBitsSet = countPopulation(OldDmask); 11438 // Work out which is the TFE/LWE lane if that is enabled. 11439 if (UsesTFC) { 11440 TFCLane = OldBitsSet; 11441 } 11442 11443 // Try to figure out the used register components 11444 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11445 I != E; ++I) { 11446 11447 // Don't look at users of the chain. 11448 if (I.getUse().getResNo() != 0) 11449 continue; 11450 11451 // Abort if we can't understand the usage 11452 if (!I->isMachineOpcode() || 11453 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11454 return Node; 11455 11456 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11457 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11458 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11459 // set, etc. 11460 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11461 if (Lane == ~0u) 11462 return Node; 11463 11464 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11465 if (UsesTFC && Lane == TFCLane) { 11466 Users[Lane] = *I; 11467 } else { 11468 // Set which texture component corresponds to the lane. 11469 unsigned Comp; 11470 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11471 Comp = countTrailingZeros(Dmask); 11472 Dmask &= ~(1 << Comp); 11473 } 11474 11475 // Abort if we have more than one user per component. 11476 if (Users[Lane]) 11477 return Node; 11478 11479 Users[Lane] = *I; 11480 NewDmask |= 1 << Comp; 11481 } 11482 } 11483 11484 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11485 bool NoChannels = !NewDmask; 11486 if (NoChannels) { 11487 if (!UsesTFC) { 11488 // No uses of the result and not using TFC. Then do nothing. 11489 return Node; 11490 } 11491 // If the original dmask has one channel - then nothing to do 11492 if (OldBitsSet == 1) 11493 return Node; 11494 // Use an arbitrary dmask - required for the instruction to work 11495 NewDmask = 1; 11496 } 11497 // Abort if there's no change 11498 if (NewDmask == OldDmask) 11499 return Node; 11500 11501 unsigned BitsSet = countPopulation(NewDmask); 11502 11503 // Check for TFE or LWE - increase the number of channels by one to account 11504 // for the extra return value 11505 // This will need adjustment for D16 if this is also included in 11506 // adjustWriteMask (this function) but at present D16 are excluded. 11507 unsigned NewChannels = BitsSet + UsesTFC; 11508 11509 int NewOpcode = 11510 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11511 assert(NewOpcode != -1 && 11512 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11513 "failed to find equivalent MIMG op"); 11514 11515 // Adjust the writemask in the node 11516 SmallVector<SDValue, 12> Ops; 11517 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11518 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11519 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11520 11521 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11522 11523 MVT ResultVT = NewChannels == 1 ? 11524 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11525 NewChannels == 5 ? 8 : NewChannels); 11526 SDVTList NewVTList = HasChain ? 11527 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11528 11529 11530 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11531 NewVTList, Ops); 11532 11533 if (HasChain) { 11534 // Update chain. 11535 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11536 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11537 } 11538 11539 if (NewChannels == 1) { 11540 assert(Node->hasNUsesOfValue(1, 0)); 11541 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11542 SDLoc(Node), Users[Lane]->getValueType(0), 11543 SDValue(NewNode, 0)); 11544 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11545 return nullptr; 11546 } 11547 11548 // Update the users of the node with the new indices 11549 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11550 SDNode *User = Users[i]; 11551 if (!User) { 11552 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11553 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11554 if (i || !NoChannels) 11555 continue; 11556 } else { 11557 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11558 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11559 } 11560 11561 switch (Idx) { 11562 default: break; 11563 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11564 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11565 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11566 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11567 } 11568 } 11569 11570 DAG.RemoveDeadNode(Node); 11571 return nullptr; 11572 } 11573 11574 static bool isFrameIndexOp(SDValue Op) { 11575 if (Op.getOpcode() == ISD::AssertZext) 11576 Op = Op.getOperand(0); 11577 11578 return isa<FrameIndexSDNode>(Op); 11579 } 11580 11581 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11582 /// with frame index operands. 11583 /// LLVM assumes that inputs are to these instructions are registers. 11584 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11585 SelectionDAG &DAG) const { 11586 if (Node->getOpcode() == ISD::CopyToReg) { 11587 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11588 SDValue SrcVal = Node->getOperand(2); 11589 11590 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11591 // to try understanding copies to physical registers. 11592 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11593 SDLoc SL(Node); 11594 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11595 SDValue VReg = DAG.getRegister( 11596 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11597 11598 SDNode *Glued = Node->getGluedNode(); 11599 SDValue ToVReg 11600 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11601 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11602 SDValue ToResultReg 11603 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11604 VReg, ToVReg.getValue(1)); 11605 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11606 DAG.RemoveDeadNode(Node); 11607 return ToResultReg.getNode(); 11608 } 11609 } 11610 11611 SmallVector<SDValue, 8> Ops; 11612 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11613 if (!isFrameIndexOp(Node->getOperand(i))) { 11614 Ops.push_back(Node->getOperand(i)); 11615 continue; 11616 } 11617 11618 SDLoc DL(Node); 11619 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11620 Node->getOperand(i).getValueType(), 11621 Node->getOperand(i)), 0)); 11622 } 11623 11624 return DAG.UpdateNodeOperands(Node, Ops); 11625 } 11626 11627 /// Fold the instructions after selecting them. 11628 /// Returns null if users were already updated. 11629 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11630 SelectionDAG &DAG) const { 11631 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11632 unsigned Opcode = Node->getMachineOpcode(); 11633 11634 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11635 !TII->isGather4(Opcode) && 11636 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11637 return adjustWritemask(Node, DAG); 11638 } 11639 11640 if (Opcode == AMDGPU::INSERT_SUBREG || 11641 Opcode == AMDGPU::REG_SEQUENCE) { 11642 legalizeTargetIndependentNode(Node, DAG); 11643 return Node; 11644 } 11645 11646 switch (Opcode) { 11647 case AMDGPU::V_DIV_SCALE_F32_e64: 11648 case AMDGPU::V_DIV_SCALE_F64_e64: { 11649 // Satisfy the operand register constraint when one of the inputs is 11650 // undefined. Ordinarily each undef value will have its own implicit_def of 11651 // a vreg, so force these to use a single register. 11652 SDValue Src0 = Node->getOperand(1); 11653 SDValue Src1 = Node->getOperand(3); 11654 SDValue Src2 = Node->getOperand(5); 11655 11656 if ((Src0.isMachineOpcode() && 11657 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11658 (Src0 == Src1 || Src0 == Src2)) 11659 break; 11660 11661 MVT VT = Src0.getValueType().getSimpleVT(); 11662 const TargetRegisterClass *RC = 11663 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11664 11665 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11666 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11667 11668 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11669 UndefReg, Src0, SDValue()); 11670 11671 // src0 must be the same register as src1 or src2, even if the value is 11672 // undefined, so make sure we don't violate this constraint. 11673 if (Src0.isMachineOpcode() && 11674 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11675 if (Src1.isMachineOpcode() && 11676 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11677 Src0 = Src1; 11678 else if (Src2.isMachineOpcode() && 11679 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11680 Src0 = Src2; 11681 else { 11682 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11683 Src0 = UndefReg; 11684 Src1 = UndefReg; 11685 } 11686 } else 11687 break; 11688 11689 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11690 Ops[1] = Src0; 11691 Ops[3] = Src1; 11692 Ops[5] = Src2; 11693 Ops.push_back(ImpDef.getValue(1)); 11694 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11695 } 11696 default: 11697 break; 11698 } 11699 11700 return Node; 11701 } 11702 11703 // Any MIMG instructions that use tfe or lwe require an initialization of the 11704 // result register that will be written in the case of a memory access failure. 11705 // The required code is also added to tie this init code to the result of the 11706 // img instruction. 11707 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11708 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11709 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11710 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11711 MachineBasicBlock &MBB = *MI.getParent(); 11712 11713 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11714 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11715 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11716 11717 if (!TFE && !LWE) // intersect_ray 11718 return; 11719 11720 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11721 unsigned LWEVal = LWE->getImm(); 11722 unsigned D16Val = D16 ? D16->getImm() : 0; 11723 11724 if (!TFEVal && !LWEVal) 11725 return; 11726 11727 // At least one of TFE or LWE are non-zero 11728 // We have to insert a suitable initialization of the result value and 11729 // tie this to the dest of the image instruction. 11730 11731 const DebugLoc &DL = MI.getDebugLoc(); 11732 11733 int DstIdx = 11734 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11735 11736 // Calculate which dword we have to initialize to 0. 11737 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11738 11739 // check that dmask operand is found. 11740 assert(MO_Dmask && "Expected dmask operand in instruction"); 11741 11742 unsigned dmask = MO_Dmask->getImm(); 11743 // Determine the number of active lanes taking into account the 11744 // Gather4 special case 11745 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11746 11747 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11748 11749 unsigned InitIdx = 11750 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11751 11752 // Abandon attempt if the dst size isn't large enough 11753 // - this is in fact an error but this is picked up elsewhere and 11754 // reported correctly. 11755 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11756 if (DstSize < InitIdx) 11757 return; 11758 11759 // Create a register for the initialization value. 11760 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11761 unsigned NewDst = 0; // Final initialized value will be in here 11762 11763 // If PRTStrictNull feature is enabled (the default) then initialize 11764 // all the result registers to 0, otherwise just the error indication 11765 // register (VGPRn+1) 11766 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11767 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11768 11769 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11770 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11771 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11772 // Initialize dword 11773 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11774 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11775 .addImm(0); 11776 // Insert into the super-reg 11777 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11778 .addReg(PrevDst) 11779 .addReg(SubReg) 11780 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11781 11782 PrevDst = NewDst; 11783 } 11784 11785 // Add as an implicit operand 11786 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11787 11788 // Tie the just added implicit operand to the dst 11789 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11790 } 11791 11792 /// Assign the register class depending on the number of 11793 /// bits set in the writemask 11794 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11795 SDNode *Node) const { 11796 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11797 11798 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11799 11800 if (TII->isVOP3(MI.getOpcode())) { 11801 // Make sure constant bus requirements are respected. 11802 TII->legalizeOperandsVOP3(MRI, MI); 11803 11804 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11805 // This saves a chain-copy of registers and better balance register 11806 // use between vgpr and agpr as agpr tuples tend to be big. 11807 if (MI.getDesc().OpInfo) { 11808 unsigned Opc = MI.getOpcode(); 11809 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11810 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11811 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11812 if (I == -1) 11813 break; 11814 MachineOperand &Op = MI.getOperand(I); 11815 if (!Op.isReg() || !Op.getReg().isVirtual()) 11816 continue; 11817 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11818 if (!TRI->hasAGPRs(RC)) 11819 continue; 11820 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11821 if (!Src || !Src->isCopy() || 11822 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11823 continue; 11824 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11825 // All uses of agpr64 and agpr32 can also accept vgpr except for 11826 // v_accvgpr_read, but we do not produce agpr reads during selection, 11827 // so no use checks are needed. 11828 MRI.setRegClass(Op.getReg(), NewRC); 11829 } 11830 11831 // Resolve the rest of AV operands to AGPRs. 11832 if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) { 11833 if (Src2->isReg() && Src2->getReg().isVirtual()) { 11834 auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg()); 11835 if (TRI->isVectorSuperClass(RC)) { 11836 auto *NewRC = TRI->getEquivalentAGPRClass(RC); 11837 MRI.setRegClass(Src2->getReg(), NewRC); 11838 if (Src2->isTied()) 11839 MRI.setRegClass(MI.getOperand(0).getReg(), NewRC); 11840 } 11841 } 11842 } 11843 } 11844 11845 return; 11846 } 11847 11848 if (TII->isMIMG(MI) && !MI.mayStore()) 11849 AddIMGInit(MI); 11850 } 11851 11852 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11853 uint64_t Val) { 11854 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11855 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11856 } 11857 11858 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11859 const SDLoc &DL, 11860 SDValue Ptr) const { 11861 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11862 11863 // Build the half of the subregister with the constants before building the 11864 // full 128-bit register. If we are building multiple resource descriptors, 11865 // this will allow CSEing of the 2-component register. 11866 const SDValue Ops0[] = { 11867 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11868 buildSMovImm32(DAG, DL, 0), 11869 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11870 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11871 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11872 }; 11873 11874 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11875 MVT::v2i32, Ops0), 0); 11876 11877 // Combine the constants and the pointer. 11878 const SDValue Ops1[] = { 11879 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11880 Ptr, 11881 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11882 SubRegHi, 11883 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11884 }; 11885 11886 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11887 } 11888 11889 /// Return a resource descriptor with the 'Add TID' bit enabled 11890 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11891 /// of the resource descriptor) to create an offset, which is added to 11892 /// the resource pointer. 11893 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11894 SDValue Ptr, uint32_t RsrcDword1, 11895 uint64_t RsrcDword2And3) const { 11896 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11897 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11898 if (RsrcDword1) { 11899 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11900 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11901 0); 11902 } 11903 11904 SDValue DataLo = buildSMovImm32(DAG, DL, 11905 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11906 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11907 11908 const SDValue Ops[] = { 11909 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11910 PtrLo, 11911 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11912 PtrHi, 11913 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11914 DataLo, 11915 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11916 DataHi, 11917 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11918 }; 11919 11920 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11921 } 11922 11923 //===----------------------------------------------------------------------===// 11924 // SI Inline Assembly Support 11925 //===----------------------------------------------------------------------===// 11926 11927 std::pair<unsigned, const TargetRegisterClass *> 11928 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11929 StringRef Constraint, 11930 MVT VT) const { 11931 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11932 11933 const TargetRegisterClass *RC = nullptr; 11934 if (Constraint.size() == 1) { 11935 const unsigned BitWidth = VT.getSizeInBits(); 11936 switch (Constraint[0]) { 11937 default: 11938 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11939 case 's': 11940 case 'r': 11941 switch (BitWidth) { 11942 case 16: 11943 RC = &AMDGPU::SReg_32RegClass; 11944 break; 11945 case 64: 11946 RC = &AMDGPU::SGPR_64RegClass; 11947 break; 11948 default: 11949 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11950 if (!RC) 11951 return std::make_pair(0U, nullptr); 11952 break; 11953 } 11954 break; 11955 case 'v': 11956 switch (BitWidth) { 11957 case 16: 11958 RC = &AMDGPU::VGPR_32RegClass; 11959 break; 11960 default: 11961 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11962 if (!RC) 11963 return std::make_pair(0U, nullptr); 11964 break; 11965 } 11966 break; 11967 case 'a': 11968 if (!Subtarget->hasMAIInsts()) 11969 break; 11970 switch (BitWidth) { 11971 case 16: 11972 RC = &AMDGPU::AGPR_32RegClass; 11973 break; 11974 default: 11975 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11976 if (!RC) 11977 return std::make_pair(0U, nullptr); 11978 break; 11979 } 11980 break; 11981 } 11982 // We actually support i128, i16 and f16 as inline parameters 11983 // even if they are not reported as legal 11984 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11985 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11986 return std::make_pair(0U, RC); 11987 } 11988 11989 if (Constraint.startswith("{") && Constraint.endswith("}")) { 11990 StringRef RegName(Constraint.data() + 1, Constraint.size() - 2); 11991 if (RegName.consume_front("v")) { 11992 RC = &AMDGPU::VGPR_32RegClass; 11993 } else if (RegName.consume_front("s")) { 11994 RC = &AMDGPU::SGPR_32RegClass; 11995 } else if (RegName.consume_front("a")) { 11996 RC = &AMDGPU::AGPR_32RegClass; 11997 } 11998 11999 if (RC) { 12000 uint32_t Idx; 12001 if (RegName.consume_front("[")) { 12002 uint32_t End; 12003 bool Failed = RegName.consumeInteger(10, Idx); 12004 Failed |= !RegName.consume_front(":"); 12005 Failed |= RegName.consumeInteger(10, End); 12006 Failed |= !RegName.consume_back("]"); 12007 if (!Failed) { 12008 uint32_t Width = (End - Idx + 1) * 32; 12009 MCRegister Reg = RC->getRegister(Idx); 12010 if (SIRegisterInfo::isVGPRClass(RC)) 12011 RC = TRI->getVGPRClassForBitWidth(Width); 12012 else if (SIRegisterInfo::isSGPRClass(RC)) 12013 RC = TRI->getSGPRClassForBitWidth(Width); 12014 else if (SIRegisterInfo::isAGPRClass(RC)) 12015 RC = TRI->getAGPRClassForBitWidth(Width); 12016 if (RC) { 12017 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC); 12018 return std::make_pair(Reg, RC); 12019 } 12020 } 12021 } else { 12022 bool Failed = RegName.getAsInteger(10, Idx); 12023 if (!Failed && Idx < RC->getNumRegs()) 12024 return std::make_pair(RC->getRegister(Idx), RC); 12025 } 12026 } 12027 } 12028 12029 auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 12030 if (Ret.first) 12031 Ret.second = TRI->getPhysRegClass(Ret.first); 12032 12033 return Ret; 12034 } 12035 12036 static bool isImmConstraint(StringRef Constraint) { 12037 if (Constraint.size() == 1) { 12038 switch (Constraint[0]) { 12039 default: break; 12040 case 'I': 12041 case 'J': 12042 case 'A': 12043 case 'B': 12044 case 'C': 12045 return true; 12046 } 12047 } else if (Constraint == "DA" || 12048 Constraint == "DB") { 12049 return true; 12050 } 12051 return false; 12052 } 12053 12054 SITargetLowering::ConstraintType 12055 SITargetLowering::getConstraintType(StringRef Constraint) const { 12056 if (Constraint.size() == 1) { 12057 switch (Constraint[0]) { 12058 default: break; 12059 case 's': 12060 case 'v': 12061 case 'a': 12062 return C_RegisterClass; 12063 } 12064 } 12065 if (isImmConstraint(Constraint)) { 12066 return C_Other; 12067 } 12068 return TargetLowering::getConstraintType(Constraint); 12069 } 12070 12071 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 12072 if (!AMDGPU::isInlinableIntLiteral(Val)) { 12073 Val = Val & maskTrailingOnes<uint64_t>(Size); 12074 } 12075 return Val; 12076 } 12077 12078 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 12079 std::string &Constraint, 12080 std::vector<SDValue> &Ops, 12081 SelectionDAG &DAG) const { 12082 if (isImmConstraint(Constraint)) { 12083 uint64_t Val; 12084 if (getAsmOperandConstVal(Op, Val) && 12085 checkAsmConstraintVal(Op, Constraint, Val)) { 12086 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 12087 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 12088 } 12089 } else { 12090 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12091 } 12092 } 12093 12094 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 12095 unsigned Size = Op.getScalarValueSizeInBits(); 12096 if (Size > 64) 12097 return false; 12098 12099 if (Size == 16 && !Subtarget->has16BitInsts()) 12100 return false; 12101 12102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 12103 Val = C->getSExtValue(); 12104 return true; 12105 } 12106 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 12107 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12108 return true; 12109 } 12110 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 12111 if (Size != 16 || Op.getNumOperands() != 2) 12112 return false; 12113 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 12114 return false; 12115 if (ConstantSDNode *C = V->getConstantSplatNode()) { 12116 Val = C->getSExtValue(); 12117 return true; 12118 } 12119 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 12120 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 12121 return true; 12122 } 12123 } 12124 12125 return false; 12126 } 12127 12128 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 12129 const std::string &Constraint, 12130 uint64_t Val) const { 12131 if (Constraint.size() == 1) { 12132 switch (Constraint[0]) { 12133 case 'I': 12134 return AMDGPU::isInlinableIntLiteral(Val); 12135 case 'J': 12136 return isInt<16>(Val); 12137 case 'A': 12138 return checkAsmConstraintValA(Op, Val); 12139 case 'B': 12140 return isInt<32>(Val); 12141 case 'C': 12142 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 12143 AMDGPU::isInlinableIntLiteral(Val); 12144 default: 12145 break; 12146 } 12147 } else if (Constraint.size() == 2) { 12148 if (Constraint == "DA") { 12149 int64_t HiBits = static_cast<int32_t>(Val >> 32); 12150 int64_t LoBits = static_cast<int32_t>(Val); 12151 return checkAsmConstraintValA(Op, HiBits, 32) && 12152 checkAsmConstraintValA(Op, LoBits, 32); 12153 } 12154 if (Constraint == "DB") { 12155 return true; 12156 } 12157 } 12158 llvm_unreachable("Invalid asm constraint"); 12159 } 12160 12161 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 12162 uint64_t Val, 12163 unsigned MaxSize) const { 12164 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 12165 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 12166 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 12167 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 12168 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 12169 return true; 12170 } 12171 return false; 12172 } 12173 12174 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 12175 switch (UnalignedClassID) { 12176 case AMDGPU::VReg_64RegClassID: 12177 return AMDGPU::VReg_64_Align2RegClassID; 12178 case AMDGPU::VReg_96RegClassID: 12179 return AMDGPU::VReg_96_Align2RegClassID; 12180 case AMDGPU::VReg_128RegClassID: 12181 return AMDGPU::VReg_128_Align2RegClassID; 12182 case AMDGPU::VReg_160RegClassID: 12183 return AMDGPU::VReg_160_Align2RegClassID; 12184 case AMDGPU::VReg_192RegClassID: 12185 return AMDGPU::VReg_192_Align2RegClassID; 12186 case AMDGPU::VReg_224RegClassID: 12187 return AMDGPU::VReg_224_Align2RegClassID; 12188 case AMDGPU::VReg_256RegClassID: 12189 return AMDGPU::VReg_256_Align2RegClassID; 12190 case AMDGPU::VReg_512RegClassID: 12191 return AMDGPU::VReg_512_Align2RegClassID; 12192 case AMDGPU::VReg_1024RegClassID: 12193 return AMDGPU::VReg_1024_Align2RegClassID; 12194 case AMDGPU::AReg_64RegClassID: 12195 return AMDGPU::AReg_64_Align2RegClassID; 12196 case AMDGPU::AReg_96RegClassID: 12197 return AMDGPU::AReg_96_Align2RegClassID; 12198 case AMDGPU::AReg_128RegClassID: 12199 return AMDGPU::AReg_128_Align2RegClassID; 12200 case AMDGPU::AReg_160RegClassID: 12201 return AMDGPU::AReg_160_Align2RegClassID; 12202 case AMDGPU::AReg_192RegClassID: 12203 return AMDGPU::AReg_192_Align2RegClassID; 12204 case AMDGPU::AReg_256RegClassID: 12205 return AMDGPU::AReg_256_Align2RegClassID; 12206 case AMDGPU::AReg_512RegClassID: 12207 return AMDGPU::AReg_512_Align2RegClassID; 12208 case AMDGPU::AReg_1024RegClassID: 12209 return AMDGPU::AReg_1024_Align2RegClassID; 12210 default: 12211 return -1; 12212 } 12213 } 12214 12215 // Figure out which registers should be reserved for stack access. Only after 12216 // the function is legalized do we know all of the non-spill stack objects or if 12217 // calls are present. 12218 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 12219 MachineRegisterInfo &MRI = MF.getRegInfo(); 12220 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12221 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 12222 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12223 const SIInstrInfo *TII = ST.getInstrInfo(); 12224 12225 if (Info->isEntryFunction()) { 12226 // Callable functions have fixed registers used for stack access. 12227 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 12228 } 12229 12230 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 12231 Info->getStackPtrOffsetReg())); 12232 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 12233 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 12234 12235 // We need to worry about replacing the default register with itself in case 12236 // of MIR testcases missing the MFI. 12237 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 12238 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 12239 12240 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 12241 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 12242 12243 Info->limitOccupancy(MF); 12244 12245 if (ST.isWave32() && !MF.empty()) { 12246 for (auto &MBB : MF) { 12247 for (auto &MI : MBB) { 12248 TII->fixImplicitOperands(MI); 12249 } 12250 } 12251 } 12252 12253 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 12254 // classes if required. Ideally the register class constraints would differ 12255 // per-subtarget, but there's no easy way to achieve that right now. This is 12256 // not a problem for VGPRs because the correctly aligned VGPR class is implied 12257 // from using them as the register class for legal types. 12258 if (ST.needsAlignedVGPRs()) { 12259 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 12260 const Register Reg = Register::index2VirtReg(I); 12261 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 12262 if (!RC) 12263 continue; 12264 int NewClassID = getAlignedAGPRClassID(RC->getID()); 12265 if (NewClassID != -1) 12266 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 12267 } 12268 } 12269 12270 TargetLoweringBase::finalizeLowering(MF); 12271 } 12272 12273 void SITargetLowering::computeKnownBitsForFrameIndex( 12274 const int FI, KnownBits &Known, const MachineFunction &MF) const { 12275 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 12276 12277 // Set the high bits to zero based on the maximum allowed scratch size per 12278 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 12279 // calculation won't overflow, so assume the sign bit is never set. 12280 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 12281 } 12282 12283 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12284 KnownBits &Known, unsigned Dim) { 12285 unsigned MaxValue = 12286 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12287 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12288 } 12289 12290 void SITargetLowering::computeKnownBitsForTargetInstr( 12291 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12292 const MachineRegisterInfo &MRI, unsigned Depth) const { 12293 const MachineInstr *MI = MRI.getVRegDef(R); 12294 switch (MI->getOpcode()) { 12295 case AMDGPU::G_INTRINSIC: { 12296 switch (MI->getIntrinsicID()) { 12297 case Intrinsic::amdgcn_workitem_id_x: 12298 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12299 break; 12300 case Intrinsic::amdgcn_workitem_id_y: 12301 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12302 break; 12303 case Intrinsic::amdgcn_workitem_id_z: 12304 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12305 break; 12306 case Intrinsic::amdgcn_mbcnt_lo: 12307 case Intrinsic::amdgcn_mbcnt_hi: { 12308 // These return at most the wavefront size - 1. 12309 unsigned Size = MRI.getType(R).getSizeInBits(); 12310 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12311 break; 12312 } 12313 case Intrinsic::amdgcn_groupstaticsize: { 12314 // We can report everything over the maximum size as 0. We can't report 12315 // based on the actual size because we don't know if it's accurate or not 12316 // at any given point. 12317 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12318 break; 12319 } 12320 } 12321 break; 12322 } 12323 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12324 Known.Zero.setHighBits(24); 12325 break; 12326 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12327 Known.Zero.setHighBits(16); 12328 break; 12329 } 12330 } 12331 12332 Align SITargetLowering::computeKnownAlignForTargetInstr( 12333 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12334 unsigned Depth) const { 12335 const MachineInstr *MI = MRI.getVRegDef(R); 12336 switch (MI->getOpcode()) { 12337 case AMDGPU::G_INTRINSIC: 12338 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12339 // FIXME: Can this move to generic code? What about the case where the call 12340 // site specifies a lower alignment? 12341 Intrinsic::ID IID = MI->getIntrinsicID(); 12342 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12343 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12344 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12345 return *RetAlign; 12346 return Align(1); 12347 } 12348 default: 12349 return Align(1); 12350 } 12351 } 12352 12353 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12354 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12355 const Align CacheLineAlign = Align(64); 12356 12357 // Pre-GFX10 target did not benefit from loop alignment 12358 if (!ML || DisableLoopAlignment || 12359 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12360 getSubtarget()->hasInstFwdPrefetchBug()) 12361 return PrefAlign; 12362 12363 // On GFX10 I$ is 4 x 64 bytes cache lines. 12364 // By default prefetcher keeps one cache line behind and reads two ahead. 12365 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12366 // behind and one ahead. 12367 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12368 // If loop fits 64 bytes it always spans no more than two cache lines and 12369 // does not need an alignment. 12370 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12371 // Else if loop is less or equal 192 bytes we need two lines behind. 12372 12373 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12374 const MachineBasicBlock *Header = ML->getHeader(); 12375 if (Header->getAlignment() != PrefAlign) 12376 return Header->getAlignment(); // Already processed. 12377 12378 unsigned LoopSize = 0; 12379 for (const MachineBasicBlock *MBB : ML->blocks()) { 12380 // If inner loop block is aligned assume in average half of the alignment 12381 // size to be added as nops. 12382 if (MBB != Header) 12383 LoopSize += MBB->getAlignment().value() / 2; 12384 12385 for (const MachineInstr &MI : *MBB) { 12386 LoopSize += TII->getInstSizeInBytes(MI); 12387 if (LoopSize > 192) 12388 return PrefAlign; 12389 } 12390 } 12391 12392 if (LoopSize <= 64) 12393 return PrefAlign; 12394 12395 if (LoopSize <= 128) 12396 return CacheLineAlign; 12397 12398 // If any of parent loops is surrounded by prefetch instructions do not 12399 // insert new for inner loop, which would reset parent's settings. 12400 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12401 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12402 auto I = Exit->getFirstNonDebugInstr(); 12403 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12404 return CacheLineAlign; 12405 } 12406 } 12407 12408 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12409 MachineBasicBlock *Exit = ML->getExitBlock(); 12410 12411 if (Pre && Exit) { 12412 auto PreTerm = Pre->getFirstTerminator(); 12413 if (PreTerm == Pre->begin() || 12414 std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH) 12415 BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12416 .addImm(1); // prefetch 2 lines behind PC 12417 12418 auto ExitHead = Exit->getFirstNonDebugInstr(); 12419 if (ExitHead == Exit->end() || 12420 ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH) 12421 BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH)) 12422 .addImm(2); // prefetch 1 line behind PC 12423 } 12424 12425 return CacheLineAlign; 12426 } 12427 12428 LLVM_ATTRIBUTE_UNUSED 12429 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12430 assert(N->getOpcode() == ISD::CopyFromReg); 12431 do { 12432 // Follow the chain until we find an INLINEASM node. 12433 N = N->getOperand(0).getNode(); 12434 if (N->getOpcode() == ISD::INLINEASM || 12435 N->getOpcode() == ISD::INLINEASM_BR) 12436 return true; 12437 } while (N->getOpcode() == ISD::CopyFromReg); 12438 return false; 12439 } 12440 12441 bool SITargetLowering::isSDNodeSourceOfDivergence( 12442 const SDNode *N, FunctionLoweringInfo *FLI, 12443 LegacyDivergenceAnalysis *KDA) const { 12444 switch (N->getOpcode()) { 12445 case ISD::CopyFromReg: { 12446 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12447 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12448 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12449 Register Reg = R->getReg(); 12450 12451 // FIXME: Why does this need to consider isLiveIn? 12452 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12453 return !TRI->isSGPRReg(MRI, Reg); 12454 12455 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12456 return KDA->isDivergent(V); 12457 12458 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12459 return !TRI->isSGPRReg(MRI, Reg); 12460 } 12461 case ISD::LOAD: { 12462 const LoadSDNode *L = cast<LoadSDNode>(N); 12463 unsigned AS = L->getAddressSpace(); 12464 // A flat load may access private memory. 12465 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12466 } 12467 case ISD::CALLSEQ_END: 12468 return true; 12469 case ISD::INTRINSIC_WO_CHAIN: 12470 return AMDGPU::isIntrinsicSourceOfDivergence( 12471 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12472 case ISD::INTRINSIC_W_CHAIN: 12473 return AMDGPU::isIntrinsicSourceOfDivergence( 12474 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12475 case AMDGPUISD::ATOMIC_CMP_SWAP: 12476 case AMDGPUISD::ATOMIC_INC: 12477 case AMDGPUISD::ATOMIC_DEC: 12478 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12479 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12480 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12481 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12482 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12483 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12484 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12485 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12486 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12487 case AMDGPUISD::BUFFER_ATOMIC_AND: 12488 case AMDGPUISD::BUFFER_ATOMIC_OR: 12489 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12490 case AMDGPUISD::BUFFER_ATOMIC_INC: 12491 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12492 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12493 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12494 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12495 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12496 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12497 // Target-specific read-modify-write atomics are sources of divergence. 12498 return true; 12499 default: 12500 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12501 // Generic read-modify-write atomics are sources of divergence. 12502 return A->readMem() && A->writeMem(); 12503 } 12504 return false; 12505 } 12506 } 12507 12508 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12509 EVT VT) const { 12510 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12511 case MVT::f32: 12512 return hasFP32Denormals(DAG.getMachineFunction()); 12513 case MVT::f64: 12514 case MVT::f16: 12515 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12516 default: 12517 return false; 12518 } 12519 } 12520 12521 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12522 MachineFunction &MF) const { 12523 switch (Ty.getScalarSizeInBits()) { 12524 case 32: 12525 return hasFP32Denormals(MF); 12526 case 64: 12527 case 16: 12528 return hasFP64FP16Denormals(MF); 12529 default: 12530 return false; 12531 } 12532 } 12533 12534 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12535 const SelectionDAG &DAG, 12536 bool SNaN, 12537 unsigned Depth) const { 12538 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12539 const MachineFunction &MF = DAG.getMachineFunction(); 12540 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12541 12542 if (Info->getMode().DX10Clamp) 12543 return true; // Clamped to 0. 12544 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12545 } 12546 12547 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12548 SNaN, Depth); 12549 } 12550 12551 // Global FP atomic instructions have a hardcoded FP mode and do not support 12552 // FP32 denormals, and only support v2f16 denormals. 12553 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12554 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12555 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12556 if (&Flt == &APFloat::IEEEsingle()) 12557 return DenormMode == DenormalMode::getPreserveSign(); 12558 return DenormMode == DenormalMode::getIEEE(); 12559 } 12560 12561 TargetLowering::AtomicExpansionKind 12562 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12563 unsigned AS = RMW->getPointerAddressSpace(); 12564 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 12565 return AtomicExpansionKind::NotAtomic; 12566 12567 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12568 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12569 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12570 SmallVector<StringRef> SSNs; 12571 Ctx.getSyncScopeNames(SSNs); 12572 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12573 ? "system" 12574 : SSNs[RMW->getSyncScopeID()]; 12575 ORE.emit([&]() { 12576 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12577 << "Hardware instruction generated for atomic " 12578 << RMW->getOperationName(RMW->getOperation()) 12579 << " operation at memory scope " << MemScope 12580 << " due to an unsafe request."; 12581 }); 12582 return Kind; 12583 }; 12584 12585 switch (RMW->getOperation()) { 12586 case AtomicRMWInst::FAdd: { 12587 Type *Ty = RMW->getType(); 12588 12589 // We don't have a way to support 16-bit atomics now, so just leave them 12590 // as-is. 12591 if (Ty->isHalfTy()) 12592 return AtomicExpansionKind::None; 12593 12594 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12595 return AtomicExpansionKind::CmpXChg; 12596 12597 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12598 Subtarget->hasAtomicFaddInsts()) { 12599 if (Subtarget->hasGFX940Insts()) 12600 return AtomicExpansionKind::None; 12601 12602 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12603 // floating point atomic instructions. May generate more efficient code, 12604 // but may not respect rounding and denormal modes, and may give incorrect 12605 // results for certain memory destinations. 12606 if (RMW->getFunction() 12607 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12608 .getValueAsString() != "true") 12609 return AtomicExpansionKind::CmpXChg; 12610 12611 if (Subtarget->hasGFX90AInsts()) { 12612 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12613 return AtomicExpansionKind::CmpXChg; 12614 12615 auto SSID = RMW->getSyncScopeID(); 12616 if (SSID == SyncScope::System || 12617 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12618 return AtomicExpansionKind::CmpXChg; 12619 12620 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12621 } 12622 12623 if (AS == AMDGPUAS::FLAT_ADDRESS) 12624 return AtomicExpansionKind::CmpXChg; 12625 12626 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12627 : AtomicExpansionKind::CmpXChg; 12628 } 12629 12630 // DS FP atomics do respect the denormal mode, but the rounding mode is 12631 // fixed to round-to-nearest-even. 12632 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12633 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12634 if (!Ty->isDoubleTy()) 12635 return AtomicExpansionKind::None; 12636 12637 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12638 return AtomicExpansionKind::None; 12639 12640 return RMW->getFunction() 12641 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12642 .getValueAsString() == "true" 12643 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12644 : AtomicExpansionKind::CmpXChg; 12645 } 12646 12647 return AtomicExpansionKind::CmpXChg; 12648 } 12649 default: 12650 break; 12651 } 12652 12653 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12654 } 12655 12656 TargetLowering::AtomicExpansionKind 12657 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 12658 return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12659 ? AtomicExpansionKind::NotAtomic 12660 : AtomicExpansionKind::None; 12661 } 12662 12663 TargetLowering::AtomicExpansionKind 12664 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 12665 return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12666 ? AtomicExpansionKind::NotAtomic 12667 : AtomicExpansionKind::None; 12668 } 12669 12670 TargetLowering::AtomicExpansionKind 12671 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const { 12672 return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS 12673 ? AtomicExpansionKind::NotAtomic 12674 : AtomicExpansionKind::None; 12675 } 12676 12677 const TargetRegisterClass * 12678 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12679 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12680 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12681 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12682 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12683 : &AMDGPU::SReg_32RegClass; 12684 if (!TRI->isSGPRClass(RC) && !isDivergent) 12685 return TRI->getEquivalentSGPRClass(RC); 12686 else if (TRI->isSGPRClass(RC) && isDivergent) 12687 return TRI->getEquivalentVGPRClass(RC); 12688 12689 return RC; 12690 } 12691 12692 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12693 // uniform values (as produced by the mask results of control flow intrinsics) 12694 // used outside of divergent blocks. The phi users need to also be treated as 12695 // always uniform. 12696 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12697 unsigned WaveSize) { 12698 // FIXME: We assume we never cast the mask results of a control flow 12699 // intrinsic. 12700 // Early exit if the type won't be consistent as a compile time hack. 12701 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12702 if (!IT || IT->getBitWidth() != WaveSize) 12703 return false; 12704 12705 if (!isa<Instruction>(V)) 12706 return false; 12707 if (!Visited.insert(V).second) 12708 return false; 12709 bool Result = false; 12710 for (auto U : V->users()) { 12711 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12712 if (V == U->getOperand(1)) { 12713 switch (Intrinsic->getIntrinsicID()) { 12714 default: 12715 Result = false; 12716 break; 12717 case Intrinsic::amdgcn_if_break: 12718 case Intrinsic::amdgcn_if: 12719 case Intrinsic::amdgcn_else: 12720 Result = true; 12721 break; 12722 } 12723 } 12724 if (V == U->getOperand(0)) { 12725 switch (Intrinsic->getIntrinsicID()) { 12726 default: 12727 Result = false; 12728 break; 12729 case Intrinsic::amdgcn_end_cf: 12730 case Intrinsic::amdgcn_loop: 12731 Result = true; 12732 break; 12733 } 12734 } 12735 } else { 12736 Result = hasCFUser(U, Visited, WaveSize); 12737 } 12738 if (Result) 12739 break; 12740 } 12741 return Result; 12742 } 12743 12744 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12745 const Value *V) const { 12746 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12747 if (CI->isInlineAsm()) { 12748 // FIXME: This cannot give a correct answer. This should only trigger in 12749 // the case where inline asm returns mixed SGPR and VGPR results, used 12750 // outside the defining block. We don't have a specific result to 12751 // consider, so this assumes if any value is SGPR, the overall register 12752 // also needs to be SGPR. 12753 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12754 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12755 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12756 for (auto &TC : TargetConstraints) { 12757 if (TC.Type == InlineAsm::isOutput) { 12758 ComputeConstraintToUse(TC, SDValue()); 12759 const TargetRegisterClass *RC = getRegForInlineAsmConstraint( 12760 SIRI, TC.ConstraintCode, TC.ConstraintVT).second; 12761 if (RC && SIRI->isSGPRClass(RC)) 12762 return true; 12763 } 12764 } 12765 } 12766 } 12767 SmallPtrSet<const Value *, 16> Visited; 12768 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12769 } 12770 12771 std::pair<InstructionCost, MVT> 12772 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12773 Type *Ty) const { 12774 std::pair<InstructionCost, MVT> Cost = 12775 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12776 auto Size = DL.getTypeSizeInBits(Ty); 12777 // Maximum load or store can handle 8 dwords for scalar and 4 for 12778 // vector ALU. Let's assume anything above 8 dwords is expensive 12779 // even if legal. 12780 if (Size <= 256) 12781 return Cost; 12782 12783 Cost.first += (Size + 255) / 256; 12784 return Cost; 12785 } 12786 12787 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const { 12788 SDNode::use_iterator I = N->use_begin(), E = N->use_end(); 12789 for (; I != E; ++I) { 12790 if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) { 12791 if (getBasePtrIndex(M) == I.getOperandNo()) 12792 return true; 12793 } 12794 } 12795 return false; 12796 } 12797 12798 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0, 12799 SDValue N1) const { 12800 if (!N0.hasOneUse()) 12801 return false; 12802 // Take care of the opportunity to keep N0 uniform 12803 if (N0->isDivergent() || !N1->isDivergent()) 12804 return true; 12805 // Check if we have a good chance to form the memory access pattern with the 12806 // base and offset 12807 return (DAG.isBaseWithConstantOffset(N0) && 12808 hasMemSDNodeUser(*N0->use_begin())); 12809 } 12810 12811 MachineMemOperand::Flags 12812 SITargetLowering::getTargetMMOFlags(const Instruction &I) const { 12813 // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load. 12814 if (I.getMetadata("amdgpu.noclobber")) 12815 return MONoClobber; 12816 return MachineMemOperand::MONone; 12817 } 12818