1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/BinaryFormat/ELF.h" 24 #include "llvm/CodeGen/Analysis.h" 25 #include "llvm/CodeGen/FunctionLoweringInfo.h" 26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h" 28 #include "llvm/CodeGen/MachineFunction.h" 29 #include "llvm/CodeGen/MachineLoopInfo.h" 30 #include "llvm/IR/DiagnosticInfo.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/IntrinsicsAMDGPU.h" 33 #include "llvm/IR/IntrinsicsR600.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/KnownBits.h" 36 37 using namespace llvm; 38 39 #define DEBUG_TYPE "si-lower" 40 41 STATISTIC(NumTailCalls, "Number of tail calls"); 42 43 static cl::opt<bool> DisableLoopAlignment( 44 "amdgpu-disable-loop-alignment", 45 cl::desc("Do not align and prefetch loops"), 46 cl::init(false)); 47 48 static cl::opt<bool> UseDivergentRegisterIndexing( 49 "amdgpu-use-divergent-register-indexing", 50 cl::Hidden, 51 cl::desc("Use indirect register addressing for divergent indexes"), 52 cl::init(false)); 53 54 static bool hasFP32Denormals(const MachineFunction &MF) { 55 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 56 return Info->getMode().allFP32Denormals(); 57 } 58 59 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 60 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 61 return Info->getMode().allFP64FP16Denormals(); 62 } 63 64 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 65 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 66 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 67 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 68 return AMDGPU::SGPR0 + Reg; 69 } 70 } 71 llvm_unreachable("Cannot allocate sgpr"); 72 } 73 74 SITargetLowering::SITargetLowering(const TargetMachine &TM, 75 const GCNSubtarget &STI) 76 : AMDGPUTargetLowering(TM, STI), 77 Subtarget(&STI) { 78 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 79 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 80 81 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 82 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 83 84 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 85 86 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 87 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 88 89 addRegisterClass(MVT::f64, V64RegClass); 90 addRegisterClass(MVT::v2f32, V64RegClass); 91 92 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 93 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 94 95 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 96 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 97 98 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 99 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 100 101 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 102 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 103 104 addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass); 105 addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192)); 106 107 addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass); 108 addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192)); 109 110 addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass); 111 addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224)); 112 113 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 114 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 115 116 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 117 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 118 119 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 120 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 121 122 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 123 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 124 125 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 126 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 127 128 if (Subtarget->has16BitInsts()) { 129 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 130 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 131 132 // Unless there are also VOP3P operations, not operations are really legal. 133 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 134 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 135 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 136 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 137 } 138 139 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 140 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 141 142 computeRegisterProperties(Subtarget->getRegisterInfo()); 143 144 // The boolean content concept here is too inflexible. Compares only ever 145 // really produce a 1-bit result. Any copy/extend from these will turn into a 146 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 147 // it's what most targets use. 148 setBooleanContents(ZeroOrOneBooleanContent); 149 setBooleanVectorContents(ZeroOrOneBooleanContent); 150 151 // We need to custom lower vector stores from local memory 152 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 153 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 156 setOperationAction(ISD::LOAD, MVT::v6i32, Custom); 157 setOperationAction(ISD::LOAD, MVT::v7i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::i1, Custom); 161 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 162 163 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 164 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 165 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 166 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v6i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v7i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 171 setOperationAction(ISD::STORE, MVT::i1, Custom); 172 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 173 174 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 175 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 176 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 177 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 178 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 179 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 180 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 181 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 182 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 183 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 184 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 185 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 186 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 187 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 188 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 189 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 190 191 setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand); 192 setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand); 193 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 194 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 195 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 196 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 197 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 198 199 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 200 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 201 202 setOperationAction(ISD::SELECT, MVT::i1, Promote); 203 setOperationAction(ISD::SELECT, MVT::i64, Custom); 204 setOperationAction(ISD::SELECT, MVT::f64, Promote); 205 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 206 207 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 208 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 209 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 210 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 211 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 212 213 setOperationAction(ISD::SETCC, MVT::i1, Promote); 214 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 215 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 216 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 217 218 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 219 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 220 setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand); 221 setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand); 222 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 223 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 224 setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand); 225 setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand); 226 setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand); 227 setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand); 228 setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand); 229 setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand); 230 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 232 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 233 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 234 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 241 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 243 244 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 245 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 246 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 247 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 248 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 249 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 250 251 setOperationAction(ISD::UADDO, MVT::i32, Legal); 252 setOperationAction(ISD::USUBO, MVT::i32, Legal); 253 254 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 255 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 256 257 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 258 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 259 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 260 261 #if 0 262 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 263 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 264 #endif 265 266 // We only support LOAD/STORE and vector manipulation ops for vectors 267 // with > 4 elements. 268 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 269 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 270 MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32, 271 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 272 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 273 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 274 switch (Op) { 275 case ISD::LOAD: 276 case ISD::STORE: 277 case ISD::BUILD_VECTOR: 278 case ISD::BITCAST: 279 case ISD::EXTRACT_VECTOR_ELT: 280 case ISD::INSERT_VECTOR_ELT: 281 case ISD::EXTRACT_SUBVECTOR: 282 case ISD::SCALAR_TO_VECTOR: 283 break; 284 case ISD::INSERT_SUBVECTOR: 285 case ISD::CONCAT_VECTORS: 286 setOperationAction(Op, VT, Custom); 287 break; 288 default: 289 setOperationAction(Op, VT, Expand); 290 break; 291 } 292 } 293 } 294 295 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 296 297 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 298 // is expanded to avoid having two separate loops in case the index is a VGPR. 299 300 // Most operations are naturally 32-bit vector operations. We only support 301 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 302 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 303 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 305 306 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 307 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 311 312 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 313 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 314 } 315 316 for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) { 317 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 318 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32); 319 320 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 321 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32); 322 323 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32); 325 326 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 327 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32); 328 } 329 330 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 331 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 332 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 333 334 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 335 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 338 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 339 340 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 341 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 342 } 343 344 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 345 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 346 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 347 348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 349 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 352 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 353 354 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 355 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 356 } 357 358 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 359 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 360 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 361 362 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 363 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 364 365 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 366 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 367 368 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 369 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 370 } 371 372 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 373 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 375 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 376 377 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 378 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 379 380 // Avoid stack access for these. 381 // TODO: Generalize to more vector types. 382 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 383 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 384 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 385 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 386 387 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 390 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 391 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 392 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 393 394 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 395 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 396 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 397 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 398 399 // Deal with vec3 vector operations when widened to vec4. 400 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 401 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 402 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 403 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 404 405 // Deal with vec5/6/7 vector operations when widened to vec8. 406 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 407 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 408 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom); 409 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom); 410 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom); 411 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom); 412 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 413 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 414 415 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 416 // and output demarshalling 417 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 418 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 419 420 // We can't return success/failure, only the old value, 421 // let LLVM add the comparison 422 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 423 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 424 425 if (Subtarget->hasFlatAddressSpace()) { 426 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 427 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 428 } 429 430 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 431 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 432 433 // FIXME: This should be narrowed to i32, but that only happens if i64 is 434 // illegal. 435 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 436 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 437 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 438 439 // On SI this is s_memtime and s_memrealtime on VI. 440 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 441 setOperationAction(ISD::TRAP, MVT::Other, Custom); 442 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 443 444 if (Subtarget->has16BitInsts()) { 445 setOperationAction(ISD::FPOW, MVT::f16, Promote); 446 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 447 setOperationAction(ISD::FLOG, MVT::f16, Custom); 448 setOperationAction(ISD::FEXP, MVT::f16, Custom); 449 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 450 } 451 452 if (Subtarget->hasMadMacF32Insts()) 453 setOperationAction(ISD::FMAD, MVT::f32, Legal); 454 455 if (!Subtarget->hasBFI()) { 456 // fcopysign can be done in a single instruction with BFI. 457 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 458 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 459 } 460 461 if (!Subtarget->hasBCNT(32)) 462 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 463 464 if (!Subtarget->hasBCNT(64)) 465 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 466 467 if (Subtarget->hasFFBH()) { 468 setOperationAction(ISD::CTLZ, MVT::i32, Custom); 469 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 470 } 471 472 if (Subtarget->hasFFBL()) { 473 setOperationAction(ISD::CTTZ, MVT::i32, Custom); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 475 } 476 477 // We only really have 32-bit BFE instructions (and 16-bit on VI). 478 // 479 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 480 // effort to match them now. We want this to be false for i64 cases when the 481 // extraction isn't restricted to the upper or lower half. Ideally we would 482 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 483 // span the midpoint are probably relatively rare, so don't worry about them 484 // for now. 485 if (Subtarget->hasBFE()) 486 setHasExtractBitsInsn(true); 487 488 // Clamp modifier on add/sub 489 if (Subtarget->hasIntClamp()) { 490 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 491 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 492 } 493 494 if (Subtarget->hasAddNoCarry()) { 495 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 496 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 497 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 498 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 499 } 500 501 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 502 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 503 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 504 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 505 506 507 // These are really only legal for ieee_mode functions. We should be avoiding 508 // them for functions that don't have ieee_mode enabled, so just say they are 509 // legal. 510 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 511 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 512 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 513 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 514 515 516 if (Subtarget->haveRoundOpsF64()) { 517 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 518 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 519 setOperationAction(ISD::FRINT, MVT::f64, Legal); 520 } else { 521 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 522 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 523 setOperationAction(ISD::FRINT, MVT::f64, Custom); 524 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 525 } 526 527 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 528 529 setOperationAction(ISD::FSIN, MVT::f32, Custom); 530 setOperationAction(ISD::FCOS, MVT::f32, Custom); 531 setOperationAction(ISD::FDIV, MVT::f32, Custom); 532 setOperationAction(ISD::FDIV, MVT::f64, Custom); 533 534 if (Subtarget->has16BitInsts()) { 535 setOperationAction(ISD::Constant, MVT::i16, Legal); 536 537 setOperationAction(ISD::SMIN, MVT::i16, Legal); 538 setOperationAction(ISD::SMAX, MVT::i16, Legal); 539 540 setOperationAction(ISD::UMIN, MVT::i16, Legal); 541 setOperationAction(ISD::UMAX, MVT::i16, Legal); 542 543 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 544 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 545 546 setOperationAction(ISD::ROTR, MVT::i16, Expand); 547 setOperationAction(ISD::ROTL, MVT::i16, Expand); 548 549 setOperationAction(ISD::SDIV, MVT::i16, Promote); 550 setOperationAction(ISD::UDIV, MVT::i16, Promote); 551 setOperationAction(ISD::SREM, MVT::i16, Promote); 552 setOperationAction(ISD::UREM, MVT::i16, Promote); 553 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 554 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 555 556 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 557 558 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 559 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 560 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 561 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 562 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 563 564 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 565 566 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 567 568 setOperationAction(ISD::LOAD, MVT::i16, Custom); 569 570 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 571 572 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 573 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 574 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 575 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 576 577 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom); 578 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom); 579 580 // F16 - Constant Actions. 581 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 582 583 // F16 - Load/Store Actions. 584 setOperationAction(ISD::LOAD, MVT::f16, Promote); 585 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 586 setOperationAction(ISD::STORE, MVT::f16, Promote); 587 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 588 589 // F16 - VOP1 Actions. 590 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 591 setOperationAction(ISD::FCOS, MVT::f16, Custom); 592 setOperationAction(ISD::FSIN, MVT::f16, Custom); 593 594 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 595 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 596 597 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 598 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 599 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 600 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 601 setOperationAction(ISD::FROUND, MVT::f16, Custom); 602 603 // F16 - VOP2 Actions. 604 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 605 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 606 607 setOperationAction(ISD::FDIV, MVT::f16, Custom); 608 609 // F16 - VOP3 Actions. 610 setOperationAction(ISD::FMA, MVT::f16, Legal); 611 if (STI.hasMadF16()) 612 setOperationAction(ISD::FMAD, MVT::f16, Legal); 613 614 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 615 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 616 switch (Op) { 617 case ISD::LOAD: 618 case ISD::STORE: 619 case ISD::BUILD_VECTOR: 620 case ISD::BITCAST: 621 case ISD::EXTRACT_VECTOR_ELT: 622 case ISD::INSERT_VECTOR_ELT: 623 case ISD::INSERT_SUBVECTOR: 624 case ISD::EXTRACT_SUBVECTOR: 625 case ISD::SCALAR_TO_VECTOR: 626 break; 627 case ISD::CONCAT_VECTORS: 628 setOperationAction(Op, VT, Custom); 629 break; 630 default: 631 setOperationAction(Op, VT, Expand); 632 break; 633 } 634 } 635 } 636 637 // v_perm_b32 can handle either of these. 638 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 639 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 640 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 641 642 // XXX - Do these do anything? Vector constants turn into build_vector. 643 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 644 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 645 646 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 647 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 648 649 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 650 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 651 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 652 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 653 654 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 655 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 656 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 657 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 658 659 setOperationAction(ISD::AND, MVT::v2i16, Promote); 660 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 661 setOperationAction(ISD::OR, MVT::v2i16, Promote); 662 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 663 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 664 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 665 666 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 667 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 668 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 669 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 670 671 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 672 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 673 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 674 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 675 676 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 677 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 678 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 679 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 680 681 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 682 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 683 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 684 685 if (!Subtarget->hasVOP3PInsts()) { 686 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 687 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 688 } 689 690 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 691 // This isn't really legal, but this avoids the legalizer unrolling it (and 692 // allows matching fneg (fabs x) patterns) 693 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 694 695 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 696 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 697 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 698 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 699 700 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 701 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 702 703 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 704 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 705 } 706 707 if (Subtarget->hasVOP3PInsts()) { 708 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 709 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 710 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 711 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 712 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 713 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 714 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 715 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 716 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 717 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 718 719 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 720 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 721 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 722 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 723 724 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 725 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 726 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 727 728 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 729 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 730 731 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 732 733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 734 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 735 736 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 737 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 738 739 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 740 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 741 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 742 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 743 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 744 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 745 746 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 747 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 748 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 749 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 750 751 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 752 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 753 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 754 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 755 756 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 757 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 758 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 759 760 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 761 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 762 763 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 764 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 765 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 766 767 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 768 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 769 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 770 771 if (Subtarget->hasPackedFP32Ops()) { 772 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 773 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 774 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 775 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 776 777 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 778 setOperationAction(ISD::FADD, VT, Custom); 779 setOperationAction(ISD::FMUL, VT, Custom); 780 setOperationAction(ISD::FMA, VT, Custom); 781 } 782 } 783 } 784 785 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 786 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 787 788 if (Subtarget->has16BitInsts()) { 789 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 790 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 791 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 792 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 793 } else { 794 // Legalization hack. 795 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 796 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 797 798 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 799 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 800 } 801 802 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 803 setOperationAction(ISD::SELECT, VT, Custom); 804 } 805 806 setOperationAction(ISD::SMULO, MVT::i64, Custom); 807 setOperationAction(ISD::UMULO, MVT::i64, Custom); 808 809 if (Subtarget->hasMad64_32()) { 810 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom); 811 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom); 812 } 813 814 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 815 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 816 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 817 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 818 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 819 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 821 822 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 823 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 824 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 825 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 826 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 827 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 828 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 829 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 830 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 831 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 832 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 833 834 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 835 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 836 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 837 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 838 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 839 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 840 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 841 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 842 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 843 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 844 845 setTargetDAGCombine(ISD::ADD); 846 setTargetDAGCombine(ISD::ADDCARRY); 847 setTargetDAGCombine(ISD::SUB); 848 setTargetDAGCombine(ISD::SUBCARRY); 849 setTargetDAGCombine(ISD::FADD); 850 setTargetDAGCombine(ISD::FSUB); 851 setTargetDAGCombine(ISD::FMINNUM); 852 setTargetDAGCombine(ISD::FMAXNUM); 853 setTargetDAGCombine(ISD::FMINNUM_IEEE); 854 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 855 setTargetDAGCombine(ISD::FMA); 856 setTargetDAGCombine(ISD::SMIN); 857 setTargetDAGCombine(ISD::SMAX); 858 setTargetDAGCombine(ISD::UMIN); 859 setTargetDAGCombine(ISD::UMAX); 860 setTargetDAGCombine(ISD::SETCC); 861 setTargetDAGCombine(ISD::AND); 862 setTargetDAGCombine(ISD::OR); 863 setTargetDAGCombine(ISD::XOR); 864 setTargetDAGCombine(ISD::SINT_TO_FP); 865 setTargetDAGCombine(ISD::UINT_TO_FP); 866 setTargetDAGCombine(ISD::FCANONICALIZE); 867 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 868 setTargetDAGCombine(ISD::ZERO_EXTEND); 869 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 870 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 871 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 872 873 // All memory operations. Some folding on the pointer operand is done to help 874 // matching the constant offsets in the addressing modes. 875 setTargetDAGCombine(ISD::LOAD); 876 setTargetDAGCombine(ISD::STORE); 877 setTargetDAGCombine(ISD::ATOMIC_LOAD); 878 setTargetDAGCombine(ISD::ATOMIC_STORE); 879 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 880 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 881 setTargetDAGCombine(ISD::ATOMIC_SWAP); 882 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 883 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 884 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 885 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 886 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 887 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 888 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 889 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 890 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 891 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 892 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 893 setTargetDAGCombine(ISD::INTRINSIC_VOID); 894 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 895 896 // FIXME: In other contexts we pretend this is a per-function property. 897 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 898 899 setSchedulingPreference(Sched::RegPressure); 900 } 901 902 const GCNSubtarget *SITargetLowering::getSubtarget() const { 903 return Subtarget; 904 } 905 906 //===----------------------------------------------------------------------===// 907 // TargetLowering queries 908 //===----------------------------------------------------------------------===// 909 910 // v_mad_mix* support a conversion from f16 to f32. 911 // 912 // There is only one special case when denormals are enabled we don't currently, 913 // where this is OK to use. 914 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 915 EVT DestVT, EVT SrcVT) const { 916 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 917 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 918 DestVT.getScalarType() == MVT::f32 && 919 SrcVT.getScalarType() == MVT::f16 && 920 // TODO: This probably only requires no input flushing? 921 !hasFP32Denormals(DAG.getMachineFunction()); 922 } 923 924 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode, 925 LLT DestTy, LLT SrcTy) const { 926 return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) || 927 (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) && 928 DestTy.getScalarSizeInBits() == 32 && 929 SrcTy.getScalarSizeInBits() == 16 && 930 // TODO: This probably only requires no input flushing? 931 !hasFP32Denormals(*MI.getMF()); 932 } 933 934 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 935 // SI has some legal vector types, but no legal vector operations. Say no 936 // shuffles are legal in order to prefer scalarizing some vector operations. 937 return false; 938 } 939 940 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 941 CallingConv::ID CC, 942 EVT VT) const { 943 if (CC == CallingConv::AMDGPU_KERNEL) 944 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 945 946 if (VT.isVector()) { 947 EVT ScalarVT = VT.getScalarType(); 948 unsigned Size = ScalarVT.getSizeInBits(); 949 if (Size == 16) { 950 if (Subtarget->has16BitInsts()) 951 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 952 return VT.isInteger() ? MVT::i32 : MVT::f32; 953 } 954 955 if (Size < 16) 956 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 957 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 958 } 959 960 if (VT.getSizeInBits() > 32) 961 return MVT::i32; 962 963 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 964 } 965 966 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 967 CallingConv::ID CC, 968 EVT VT) const { 969 if (CC == CallingConv::AMDGPU_KERNEL) 970 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 971 972 if (VT.isVector()) { 973 unsigned NumElts = VT.getVectorNumElements(); 974 EVT ScalarVT = VT.getScalarType(); 975 unsigned Size = ScalarVT.getSizeInBits(); 976 977 // FIXME: Should probably promote 8-bit vectors to i16. 978 if (Size == 16 && Subtarget->has16BitInsts()) 979 return (NumElts + 1) / 2; 980 981 if (Size <= 32) 982 return NumElts; 983 984 if (Size > 32) 985 return NumElts * ((Size + 31) / 32); 986 } else if (VT.getSizeInBits() > 32) 987 return (VT.getSizeInBits() + 31) / 32; 988 989 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 990 } 991 992 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 993 LLVMContext &Context, CallingConv::ID CC, 994 EVT VT, EVT &IntermediateVT, 995 unsigned &NumIntermediates, MVT &RegisterVT) const { 996 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 997 unsigned NumElts = VT.getVectorNumElements(); 998 EVT ScalarVT = VT.getScalarType(); 999 unsigned Size = ScalarVT.getSizeInBits(); 1000 // FIXME: We should fix the ABI to be the same on targets without 16-bit 1001 // support, but unless we can properly handle 3-vectors, it will be still be 1002 // inconsistent. 1003 if (Size == 16 && Subtarget->has16BitInsts()) { 1004 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 1005 IntermediateVT = RegisterVT; 1006 NumIntermediates = (NumElts + 1) / 2; 1007 return NumIntermediates; 1008 } 1009 1010 if (Size == 32) { 1011 RegisterVT = ScalarVT.getSimpleVT(); 1012 IntermediateVT = RegisterVT; 1013 NumIntermediates = NumElts; 1014 return NumIntermediates; 1015 } 1016 1017 if (Size < 16 && Subtarget->has16BitInsts()) { 1018 // FIXME: Should probably form v2i16 pieces 1019 RegisterVT = MVT::i16; 1020 IntermediateVT = ScalarVT; 1021 NumIntermediates = NumElts; 1022 return NumIntermediates; 1023 } 1024 1025 1026 if (Size != 16 && Size <= 32) { 1027 RegisterVT = MVT::i32; 1028 IntermediateVT = ScalarVT; 1029 NumIntermediates = NumElts; 1030 return NumIntermediates; 1031 } 1032 1033 if (Size > 32) { 1034 RegisterVT = MVT::i32; 1035 IntermediateVT = RegisterVT; 1036 NumIntermediates = NumElts * ((Size + 31) / 32); 1037 return NumIntermediates; 1038 } 1039 } 1040 1041 return TargetLowering::getVectorTypeBreakdownForCallingConv( 1042 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 1043 } 1044 1045 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 1046 assert(DMaskLanes != 0); 1047 1048 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 1049 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 1050 return EVT::getVectorVT(Ty->getContext(), 1051 EVT::getEVT(VT->getElementType()), 1052 NumElts); 1053 } 1054 1055 return EVT::getEVT(Ty); 1056 } 1057 1058 // Peek through TFE struct returns to only use the data size. 1059 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1060 auto *ST = dyn_cast<StructType>(Ty); 1061 if (!ST) 1062 return memVTFromImageData(Ty, DMaskLanes); 1063 1064 // Some intrinsics return an aggregate type - special case to work out the 1065 // correct memVT. 1066 // 1067 // Only limited forms of aggregate type currently expected. 1068 if (ST->getNumContainedTypes() != 2 || 1069 !ST->getContainedType(1)->isIntegerTy(32)) 1070 return EVT(); 1071 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1072 } 1073 1074 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1075 const CallInst &CI, 1076 MachineFunction &MF, 1077 unsigned IntrID) const { 1078 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1079 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1080 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1081 (Intrinsic::ID)IntrID); 1082 if (Attr.hasFnAttr(Attribute::ReadNone)) 1083 return false; 1084 1085 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1086 1087 if (RsrcIntr->IsImage) { 1088 Info.ptrVal = 1089 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1090 Info.align.reset(); 1091 } else { 1092 Info.ptrVal = 1093 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1094 } 1095 1096 Info.flags = MachineMemOperand::MODereferenceable; 1097 if (Attr.hasFnAttr(Attribute::ReadOnly)) { 1098 unsigned DMaskLanes = 4; 1099 1100 if (RsrcIntr->IsImage) { 1101 const AMDGPU::ImageDimIntrinsicInfo *Intr 1102 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1103 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1104 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1105 1106 if (!BaseOpcode->Gather4) { 1107 // If this isn't a gather, we may have excess loaded elements in the 1108 // IR type. Check the dmask for the real number of elements loaded. 1109 unsigned DMask 1110 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1111 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1112 } 1113 1114 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1115 } else 1116 Info.memVT = EVT::getEVT(CI.getType()); 1117 1118 // FIXME: What does alignment mean for an image? 1119 Info.opc = ISD::INTRINSIC_W_CHAIN; 1120 Info.flags |= MachineMemOperand::MOLoad; 1121 } else if (Attr.hasFnAttr(Attribute::WriteOnly)) { 1122 Info.opc = ISD::INTRINSIC_VOID; 1123 1124 Type *DataTy = CI.getArgOperand(0)->getType(); 1125 if (RsrcIntr->IsImage) { 1126 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1127 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1128 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1129 } else 1130 Info.memVT = EVT::getEVT(DataTy); 1131 1132 Info.flags |= MachineMemOperand::MOStore; 1133 } else { 1134 // Atomic 1135 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1136 ISD::INTRINSIC_W_CHAIN; 1137 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1138 Info.flags = MachineMemOperand::MOLoad | 1139 MachineMemOperand::MOStore | 1140 MachineMemOperand::MODereferenceable; 1141 1142 // XXX - Should this be volatile without known ordering? 1143 Info.flags |= MachineMemOperand::MOVolatile; 1144 } 1145 return true; 1146 } 1147 1148 switch (IntrID) { 1149 case Intrinsic::amdgcn_atomic_inc: 1150 case Intrinsic::amdgcn_atomic_dec: 1151 case Intrinsic::amdgcn_ds_ordered_add: 1152 case Intrinsic::amdgcn_ds_ordered_swap: 1153 case Intrinsic::amdgcn_ds_fadd: 1154 case Intrinsic::amdgcn_ds_fmin: 1155 case Intrinsic::amdgcn_ds_fmax: { 1156 Info.opc = ISD::INTRINSIC_W_CHAIN; 1157 Info.memVT = MVT::getVT(CI.getType()); 1158 Info.ptrVal = CI.getOperand(0); 1159 Info.align.reset(); 1160 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1161 1162 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1163 if (!Vol->isZero()) 1164 Info.flags |= MachineMemOperand::MOVolatile; 1165 1166 return true; 1167 } 1168 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1169 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1170 1171 Info.opc = ISD::INTRINSIC_W_CHAIN; 1172 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1173 Info.ptrVal = 1174 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1175 Info.align.reset(); 1176 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1177 1178 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1179 if (!Vol || !Vol->isZero()) 1180 Info.flags |= MachineMemOperand::MOVolatile; 1181 1182 return true; 1183 } 1184 case Intrinsic::amdgcn_ds_append: 1185 case Intrinsic::amdgcn_ds_consume: { 1186 Info.opc = ISD::INTRINSIC_W_CHAIN; 1187 Info.memVT = MVT::getVT(CI.getType()); 1188 Info.ptrVal = CI.getOperand(0); 1189 Info.align.reset(); 1190 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1191 1192 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1193 if (!Vol->isZero()) 1194 Info.flags |= MachineMemOperand::MOVolatile; 1195 1196 return true; 1197 } 1198 case Intrinsic::amdgcn_global_atomic_csub: { 1199 Info.opc = ISD::INTRINSIC_W_CHAIN; 1200 Info.memVT = MVT::getVT(CI.getType()); 1201 Info.ptrVal = CI.getOperand(0); 1202 Info.align.reset(); 1203 Info.flags = MachineMemOperand::MOLoad | 1204 MachineMemOperand::MOStore | 1205 MachineMemOperand::MOVolatile; 1206 return true; 1207 } 1208 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1209 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1210 Info.opc = ISD::INTRINSIC_W_CHAIN; 1211 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1212 Info.ptrVal = 1213 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1214 Info.align.reset(); 1215 Info.flags = MachineMemOperand::MOLoad | 1216 MachineMemOperand::MODereferenceable; 1217 return true; 1218 } 1219 case Intrinsic::amdgcn_global_atomic_fadd: 1220 case Intrinsic::amdgcn_global_atomic_fmin: 1221 case Intrinsic::amdgcn_global_atomic_fmax: 1222 case Intrinsic::amdgcn_flat_atomic_fadd: 1223 case Intrinsic::amdgcn_flat_atomic_fmin: 1224 case Intrinsic::amdgcn_flat_atomic_fmax: { 1225 Info.opc = ISD::INTRINSIC_W_CHAIN; 1226 Info.memVT = MVT::getVT(CI.getType()); 1227 Info.ptrVal = CI.getOperand(0); 1228 Info.align.reset(); 1229 Info.flags = MachineMemOperand::MOLoad | 1230 MachineMemOperand::MOStore | 1231 MachineMemOperand::MODereferenceable | 1232 MachineMemOperand::MOVolatile; 1233 return true; 1234 } 1235 case Intrinsic::amdgcn_ds_gws_init: 1236 case Intrinsic::amdgcn_ds_gws_barrier: 1237 case Intrinsic::amdgcn_ds_gws_sema_v: 1238 case Intrinsic::amdgcn_ds_gws_sema_br: 1239 case Intrinsic::amdgcn_ds_gws_sema_p: 1240 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1241 Info.opc = ISD::INTRINSIC_VOID; 1242 1243 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1244 Info.ptrVal = 1245 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1246 1247 // This is an abstract access, but we need to specify a type and size. 1248 Info.memVT = MVT::i32; 1249 Info.size = 4; 1250 Info.align = Align(4); 1251 1252 Info.flags = MachineMemOperand::MOStore; 1253 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1254 Info.flags = MachineMemOperand::MOLoad; 1255 return true; 1256 } 1257 default: 1258 return false; 1259 } 1260 } 1261 1262 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1263 SmallVectorImpl<Value*> &Ops, 1264 Type *&AccessTy) const { 1265 switch (II->getIntrinsicID()) { 1266 case Intrinsic::amdgcn_atomic_inc: 1267 case Intrinsic::amdgcn_atomic_dec: 1268 case Intrinsic::amdgcn_ds_ordered_add: 1269 case Intrinsic::amdgcn_ds_ordered_swap: 1270 case Intrinsic::amdgcn_ds_append: 1271 case Intrinsic::amdgcn_ds_consume: 1272 case Intrinsic::amdgcn_ds_fadd: 1273 case Intrinsic::amdgcn_ds_fmin: 1274 case Intrinsic::amdgcn_ds_fmax: 1275 case Intrinsic::amdgcn_global_atomic_fadd: 1276 case Intrinsic::amdgcn_flat_atomic_fadd: 1277 case Intrinsic::amdgcn_flat_atomic_fmin: 1278 case Intrinsic::amdgcn_flat_atomic_fmax: 1279 case Intrinsic::amdgcn_global_atomic_csub: { 1280 Value *Ptr = II->getArgOperand(0); 1281 AccessTy = II->getType(); 1282 Ops.push_back(Ptr); 1283 return true; 1284 } 1285 default: 1286 return false; 1287 } 1288 } 1289 1290 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1291 if (!Subtarget->hasFlatInstOffsets()) { 1292 // Flat instructions do not have offsets, and only have the register 1293 // address. 1294 return AM.BaseOffs == 0 && AM.Scale == 0; 1295 } 1296 1297 return AM.Scale == 0 && 1298 (AM.BaseOffs == 0 || 1299 Subtarget->getInstrInfo()->isLegalFLATOffset( 1300 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT)); 1301 } 1302 1303 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1304 if (Subtarget->hasFlatGlobalInsts()) 1305 return AM.Scale == 0 && 1306 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1307 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1308 SIInstrFlags::FlatGlobal)); 1309 1310 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1311 // Assume the we will use FLAT for all global memory accesses 1312 // on VI. 1313 // FIXME: This assumption is currently wrong. On VI we still use 1314 // MUBUF instructions for the r + i addressing mode. As currently 1315 // implemented, the MUBUF instructions only work on buffer < 4GB. 1316 // It may be possible to support > 4GB buffers with MUBUF instructions, 1317 // by setting the stride value in the resource descriptor which would 1318 // increase the size limit to (stride * 4GB). However, this is risky, 1319 // because it has never been validated. 1320 return isLegalFlatAddressingMode(AM); 1321 } 1322 1323 return isLegalMUBUFAddressingMode(AM); 1324 } 1325 1326 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1327 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1328 // additionally can do r + r + i with addr64. 32-bit has more addressing 1329 // mode options. Depending on the resource constant, it can also do 1330 // (i64 r0) + (i32 r1) * (i14 i). 1331 // 1332 // Private arrays end up using a scratch buffer most of the time, so also 1333 // assume those use MUBUF instructions. Scratch loads / stores are currently 1334 // implemented as mubuf instructions with offen bit set, so slightly 1335 // different than the normal addr64. 1336 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1337 return false; 1338 1339 // FIXME: Since we can split immediate into soffset and immediate offset, 1340 // would it make sense to allow any immediate? 1341 1342 switch (AM.Scale) { 1343 case 0: // r + i or just i, depending on HasBaseReg. 1344 return true; 1345 case 1: 1346 return true; // We have r + r or r + i. 1347 case 2: 1348 if (AM.HasBaseReg) { 1349 // Reject 2 * r + r. 1350 return false; 1351 } 1352 1353 // Allow 2 * r as r + r 1354 // Or 2 * r + i is allowed as r + r + i. 1355 return true; 1356 default: // Don't allow n * r 1357 return false; 1358 } 1359 } 1360 1361 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1362 const AddrMode &AM, Type *Ty, 1363 unsigned AS, Instruction *I) const { 1364 // No global is ever allowed as a base. 1365 if (AM.BaseGV) 1366 return false; 1367 1368 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1369 return isLegalGlobalAddressingMode(AM); 1370 1371 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1372 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1373 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1374 // If the offset isn't a multiple of 4, it probably isn't going to be 1375 // correctly aligned. 1376 // FIXME: Can we get the real alignment here? 1377 if (AM.BaseOffs % 4 != 0) 1378 return isLegalMUBUFAddressingMode(AM); 1379 1380 // There are no SMRD extloads, so if we have to do a small type access we 1381 // will use a MUBUF load. 1382 // FIXME?: We also need to do this if unaligned, but we don't know the 1383 // alignment here. 1384 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1385 return isLegalGlobalAddressingMode(AM); 1386 1387 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1388 // SMRD instructions have an 8-bit, dword offset on SI. 1389 if (!isUInt<8>(AM.BaseOffs / 4)) 1390 return false; 1391 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1392 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1393 // in 8-bits, it can use a smaller encoding. 1394 if (!isUInt<32>(AM.BaseOffs / 4)) 1395 return false; 1396 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1397 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1398 if (!isUInt<20>(AM.BaseOffs)) 1399 return false; 1400 } else 1401 llvm_unreachable("unhandled generation"); 1402 1403 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1404 return true; 1405 1406 if (AM.Scale == 1 && AM.HasBaseReg) 1407 return true; 1408 1409 return false; 1410 1411 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1412 return isLegalMUBUFAddressingMode(AM); 1413 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1414 AS == AMDGPUAS::REGION_ADDRESS) { 1415 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1416 // field. 1417 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1418 // an 8-bit dword offset but we don't know the alignment here. 1419 if (!isUInt<16>(AM.BaseOffs)) 1420 return false; 1421 1422 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1423 return true; 1424 1425 if (AM.Scale == 1 && AM.HasBaseReg) 1426 return true; 1427 1428 return false; 1429 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1430 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1431 // For an unknown address space, this usually means that this is for some 1432 // reason being used for pure arithmetic, and not based on some addressing 1433 // computation. We don't have instructions that compute pointers with any 1434 // addressing modes, so treat them as having no offset like flat 1435 // instructions. 1436 return isLegalFlatAddressingMode(AM); 1437 } 1438 1439 // Assume a user alias of global for unknown address spaces. 1440 return isLegalGlobalAddressingMode(AM); 1441 } 1442 1443 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1444 const MachineFunction &MF) const { 1445 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1446 return (MemVT.getSizeInBits() <= 4 * 32); 1447 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1448 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1449 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1450 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1451 return (MemVT.getSizeInBits() <= 2 * 32); 1452 } 1453 return true; 1454 } 1455 1456 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1457 unsigned Size, unsigned AddrSpace, Align Alignment, 1458 MachineMemOperand::Flags Flags, bool *IsFast) const { 1459 if (IsFast) 1460 *IsFast = false; 1461 1462 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1463 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1464 // Check if alignment requirements for ds_read/write instructions are 1465 // disabled. 1466 if (Subtarget->hasUnalignedDSAccessEnabled() && 1467 !Subtarget->hasLDSMisalignedBug()) { 1468 if (IsFast) 1469 *IsFast = Alignment != Align(2); 1470 return true; 1471 } 1472 1473 // Either, the alignment requirements are "enabled", or there is an 1474 // unaligned LDS access related hardware bug though alignment requirements 1475 // are "disabled". In either case, we need to check for proper alignment 1476 // requirements. 1477 // 1478 if (Size == 64) { 1479 // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we 1480 // can do a 4 byte aligned, 8 byte access in a single operation using 1481 // ds_read2/write2_b32 with adjacent offsets. 1482 bool AlignedBy4 = Alignment >= Align(4); 1483 if (IsFast) 1484 *IsFast = AlignedBy4; 1485 1486 return AlignedBy4; 1487 } 1488 if (Size == 96) { 1489 // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on 1490 // gfx8 and older. 1491 bool AlignedBy16 = Alignment >= Align(16); 1492 if (IsFast) 1493 *IsFast = AlignedBy16; 1494 1495 return AlignedBy16; 1496 } 1497 if (Size == 128) { 1498 // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on 1499 // gfx8 and older, but we can do a 8 byte aligned, 16 byte access in a 1500 // single operation using ds_read2/write2_b64. 1501 bool AlignedBy8 = Alignment >= Align(8); 1502 if (IsFast) 1503 *IsFast = AlignedBy8; 1504 1505 return AlignedBy8; 1506 } 1507 } 1508 1509 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1510 bool AlignedBy4 = Alignment >= Align(4); 1511 if (IsFast) 1512 *IsFast = AlignedBy4; 1513 1514 return AlignedBy4 || 1515 Subtarget->enableFlatScratch() || 1516 Subtarget->hasUnalignedScratchAccess(); 1517 } 1518 1519 // FIXME: We have to be conservative here and assume that flat operations 1520 // will access scratch. If we had access to the IR function, then we 1521 // could determine if any private memory was used in the function. 1522 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1523 !Subtarget->hasUnalignedScratchAccess()) { 1524 bool AlignedBy4 = Alignment >= Align(4); 1525 if (IsFast) 1526 *IsFast = AlignedBy4; 1527 1528 return AlignedBy4; 1529 } 1530 1531 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1532 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1533 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1534 // If we have an uniform constant load, it still requires using a slow 1535 // buffer instruction if unaligned. 1536 if (IsFast) { 1537 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1538 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1539 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1540 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1541 Alignment >= Align(4) : Alignment != Align(2); 1542 } 1543 1544 return true; 1545 } 1546 1547 // Smaller than dword value must be aligned. 1548 if (Size < 32) 1549 return false; 1550 1551 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1552 // byte-address are ignored, thus forcing Dword alignment. 1553 // This applies to private, global, and constant memory. 1554 if (IsFast) 1555 *IsFast = true; 1556 1557 return Size >= 32 && Alignment >= Align(4); 1558 } 1559 1560 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1561 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1562 bool *IsFast) const { 1563 if (IsFast) 1564 *IsFast = false; 1565 1566 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1567 // which isn't a simple VT. 1568 // Until MVT is extended to handle this, simply check for the size and 1569 // rely on the condition below: allow accesses if the size is a multiple of 4. 1570 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1571 VT.getStoreSize() > 16)) { 1572 return false; 1573 } 1574 1575 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1576 Alignment, Flags, IsFast); 1577 } 1578 1579 EVT SITargetLowering::getOptimalMemOpType( 1580 const MemOp &Op, const AttributeList &FuncAttributes) const { 1581 // FIXME: Should account for address space here. 1582 1583 // The default fallback uses the private pointer size as a guess for a type to 1584 // use. Make sure we switch these to 64-bit accesses. 1585 1586 if (Op.size() >= 16 && 1587 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1588 return MVT::v4i32; 1589 1590 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1591 return MVT::v2i32; 1592 1593 // Use the default. 1594 return MVT::Other; 1595 } 1596 1597 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1598 const MemSDNode *MemNode = cast<MemSDNode>(N); 1599 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1600 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1601 return I && I->getMetadata("amdgpu.noclobber"); 1602 } 1603 1604 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1605 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1606 AS == AMDGPUAS::PRIVATE_ADDRESS; 1607 } 1608 1609 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1610 unsigned DestAS) const { 1611 // Flat -> private/local is a simple truncate. 1612 // Flat -> global is no-op 1613 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1614 return true; 1615 1616 const GCNTargetMachine &TM = 1617 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1618 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1619 } 1620 1621 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1622 const MemSDNode *MemNode = cast<MemSDNode>(N); 1623 1624 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1625 } 1626 1627 TargetLoweringBase::LegalizeTypeAction 1628 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1629 if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 && 1630 VT.getScalarType().bitsLE(MVT::i16)) 1631 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1632 return TargetLoweringBase::getPreferredVectorAction(VT); 1633 } 1634 1635 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1636 Type *Ty) const { 1637 // FIXME: Could be smarter if called for vector constants. 1638 return true; 1639 } 1640 1641 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1642 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1643 switch (Op) { 1644 case ISD::LOAD: 1645 case ISD::STORE: 1646 1647 // These operations are done with 32-bit instructions anyway. 1648 case ISD::AND: 1649 case ISD::OR: 1650 case ISD::XOR: 1651 case ISD::SELECT: 1652 // TODO: Extensions? 1653 return true; 1654 default: 1655 return false; 1656 } 1657 } 1658 1659 // SimplifySetCC uses this function to determine whether or not it should 1660 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1661 if (VT == MVT::i1 && Op == ISD::SETCC) 1662 return false; 1663 1664 return TargetLowering::isTypeDesirableForOp(Op, VT); 1665 } 1666 1667 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1668 const SDLoc &SL, 1669 SDValue Chain, 1670 uint64_t Offset) const { 1671 const DataLayout &DL = DAG.getDataLayout(); 1672 MachineFunction &MF = DAG.getMachineFunction(); 1673 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1674 1675 const ArgDescriptor *InputPtrReg; 1676 const TargetRegisterClass *RC; 1677 LLT ArgTy; 1678 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1679 1680 std::tie(InputPtrReg, RC, ArgTy) = 1681 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1682 1683 // We may not have the kernarg segment argument if we have no kernel 1684 // arguments. 1685 if (!InputPtrReg) 1686 return DAG.getConstant(0, SL, PtrVT); 1687 1688 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1689 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1690 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1691 1692 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1693 } 1694 1695 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1696 const SDLoc &SL) const { 1697 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1698 FIRST_IMPLICIT); 1699 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1700 } 1701 1702 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1703 const SDLoc &SL, SDValue Val, 1704 bool Signed, 1705 const ISD::InputArg *Arg) const { 1706 // First, if it is a widened vector, narrow it. 1707 if (VT.isVector() && 1708 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1709 EVT NarrowedVT = 1710 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1711 VT.getVectorNumElements()); 1712 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1713 DAG.getConstant(0, SL, MVT::i32)); 1714 } 1715 1716 // Then convert the vector elements or scalar value. 1717 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1718 VT.bitsLT(MemVT)) { 1719 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1720 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1721 } 1722 1723 if (MemVT.isFloatingPoint()) 1724 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1725 else if (Signed) 1726 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1727 else 1728 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1729 1730 return Val; 1731 } 1732 1733 SDValue SITargetLowering::lowerKernargMemParameter( 1734 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1735 uint64_t Offset, Align Alignment, bool Signed, 1736 const ISD::InputArg *Arg) const { 1737 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1738 1739 // Try to avoid using an extload by loading earlier than the argument address, 1740 // and extracting the relevant bits. The load should hopefully be merged with 1741 // the previous argument. 1742 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1743 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1744 int64_t AlignDownOffset = alignDown(Offset, 4); 1745 int64_t OffsetDiff = Offset - AlignDownOffset; 1746 1747 EVT IntVT = MemVT.changeTypeToInteger(); 1748 1749 // TODO: If we passed in the base kernel offset we could have a better 1750 // alignment than 4, but we don't really need it. 1751 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1752 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1753 MachineMemOperand::MODereferenceable | 1754 MachineMemOperand::MOInvariant); 1755 1756 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1757 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1758 1759 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1760 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1761 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1762 1763 1764 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1765 } 1766 1767 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1768 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1769 MachineMemOperand::MODereferenceable | 1770 MachineMemOperand::MOInvariant); 1771 1772 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1773 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1774 } 1775 1776 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1777 const SDLoc &SL, SDValue Chain, 1778 const ISD::InputArg &Arg) const { 1779 MachineFunction &MF = DAG.getMachineFunction(); 1780 MachineFrameInfo &MFI = MF.getFrameInfo(); 1781 1782 if (Arg.Flags.isByVal()) { 1783 unsigned Size = Arg.Flags.getByValSize(); 1784 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1785 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1786 } 1787 1788 unsigned ArgOffset = VA.getLocMemOffset(); 1789 unsigned ArgSize = VA.getValVT().getStoreSize(); 1790 1791 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1792 1793 // Create load nodes to retrieve arguments from the stack. 1794 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1795 SDValue ArgValue; 1796 1797 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1798 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1799 MVT MemVT = VA.getValVT(); 1800 1801 switch (VA.getLocInfo()) { 1802 default: 1803 break; 1804 case CCValAssign::BCvt: 1805 MemVT = VA.getLocVT(); 1806 break; 1807 case CCValAssign::SExt: 1808 ExtType = ISD::SEXTLOAD; 1809 break; 1810 case CCValAssign::ZExt: 1811 ExtType = ISD::ZEXTLOAD; 1812 break; 1813 case CCValAssign::AExt: 1814 ExtType = ISD::EXTLOAD; 1815 break; 1816 } 1817 1818 ArgValue = DAG.getExtLoad( 1819 ExtType, SL, VA.getLocVT(), Chain, FIN, 1820 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1821 MemVT); 1822 return ArgValue; 1823 } 1824 1825 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1826 const SIMachineFunctionInfo &MFI, 1827 EVT VT, 1828 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1829 const ArgDescriptor *Reg; 1830 const TargetRegisterClass *RC; 1831 LLT Ty; 1832 1833 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1834 if (!Reg) { 1835 if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) { 1836 // It's possible for a kernarg intrinsic call to appear in a kernel with 1837 // no allocated segment, in which case we do not add the user sgpr 1838 // argument, so just return null. 1839 return DAG.getConstant(0, SDLoc(), VT); 1840 } 1841 1842 // It's undefined behavior if a function marked with the amdgpu-no-* 1843 // attributes uses the corresponding intrinsic. 1844 return DAG.getUNDEF(VT); 1845 } 1846 1847 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1848 } 1849 1850 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1851 CallingConv::ID CallConv, 1852 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1853 FunctionType *FType, 1854 SIMachineFunctionInfo *Info) { 1855 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1856 const ISD::InputArg *Arg = &Ins[I]; 1857 1858 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1859 "vector type argument should have been split"); 1860 1861 // First check if it's a PS input addr. 1862 if (CallConv == CallingConv::AMDGPU_PS && 1863 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1864 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1865 1866 // Inconveniently only the first part of the split is marked as isSplit, 1867 // so skip to the end. We only want to increment PSInputNum once for the 1868 // entire split argument. 1869 if (Arg->Flags.isSplit()) { 1870 while (!Arg->Flags.isSplitEnd()) { 1871 assert((!Arg->VT.isVector() || 1872 Arg->VT.getScalarSizeInBits() == 16) && 1873 "unexpected vector split in ps argument type"); 1874 if (!SkipArg) 1875 Splits.push_back(*Arg); 1876 Arg = &Ins[++I]; 1877 } 1878 } 1879 1880 if (SkipArg) { 1881 // We can safely skip PS inputs. 1882 Skipped.set(Arg->getOrigArgIndex()); 1883 ++PSInputNum; 1884 continue; 1885 } 1886 1887 Info->markPSInputAllocated(PSInputNum); 1888 if (Arg->Used) 1889 Info->markPSInputEnabled(PSInputNum); 1890 1891 ++PSInputNum; 1892 } 1893 1894 Splits.push_back(*Arg); 1895 } 1896 } 1897 1898 // Allocate special inputs passed in VGPRs. 1899 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1900 MachineFunction &MF, 1901 const SIRegisterInfo &TRI, 1902 SIMachineFunctionInfo &Info) const { 1903 const LLT S32 = LLT::scalar(32); 1904 MachineRegisterInfo &MRI = MF.getRegInfo(); 1905 1906 if (Info.hasWorkItemIDX()) { 1907 Register Reg = AMDGPU::VGPR0; 1908 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1909 1910 CCInfo.AllocateReg(Reg); 1911 unsigned Mask = (Subtarget->hasPackedTID() && 1912 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1913 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1914 } 1915 1916 if (Info.hasWorkItemIDY()) { 1917 assert(Info.hasWorkItemIDX()); 1918 if (Subtarget->hasPackedTID()) { 1919 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1920 0x3ff << 10)); 1921 } else { 1922 unsigned Reg = AMDGPU::VGPR1; 1923 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1924 1925 CCInfo.AllocateReg(Reg); 1926 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1927 } 1928 } 1929 1930 if (Info.hasWorkItemIDZ()) { 1931 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1932 if (Subtarget->hasPackedTID()) { 1933 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1934 0x3ff << 20)); 1935 } else { 1936 unsigned Reg = AMDGPU::VGPR2; 1937 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1938 1939 CCInfo.AllocateReg(Reg); 1940 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1941 } 1942 } 1943 } 1944 1945 // Try to allocate a VGPR at the end of the argument list, or if no argument 1946 // VGPRs are left allocating a stack slot. 1947 // If \p Mask is is given it indicates bitfield position in the register. 1948 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1949 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1950 ArgDescriptor Arg = ArgDescriptor()) { 1951 if (Arg.isSet()) 1952 return ArgDescriptor::createArg(Arg, Mask); 1953 1954 ArrayRef<MCPhysReg> ArgVGPRs 1955 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1956 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1957 if (RegIdx == ArgVGPRs.size()) { 1958 // Spill to stack required. 1959 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1960 1961 return ArgDescriptor::createStack(Offset, Mask); 1962 } 1963 1964 unsigned Reg = ArgVGPRs[RegIdx]; 1965 Reg = CCInfo.AllocateReg(Reg); 1966 assert(Reg != AMDGPU::NoRegister); 1967 1968 MachineFunction &MF = CCInfo.getMachineFunction(); 1969 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1970 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1971 return ArgDescriptor::createRegister(Reg, Mask); 1972 } 1973 1974 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1975 const TargetRegisterClass *RC, 1976 unsigned NumArgRegs) { 1977 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1978 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1979 if (RegIdx == ArgSGPRs.size()) 1980 report_fatal_error("ran out of SGPRs for arguments"); 1981 1982 unsigned Reg = ArgSGPRs[RegIdx]; 1983 Reg = CCInfo.AllocateReg(Reg); 1984 assert(Reg != AMDGPU::NoRegister); 1985 1986 MachineFunction &MF = CCInfo.getMachineFunction(); 1987 MF.addLiveIn(Reg, RC); 1988 return ArgDescriptor::createRegister(Reg); 1989 } 1990 1991 // If this has a fixed position, we still should allocate the register in the 1992 // CCInfo state. Technically we could get away with this for values passed 1993 // outside of the normal argument range. 1994 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1995 const TargetRegisterClass *RC, 1996 MCRegister Reg) { 1997 Reg = CCInfo.AllocateReg(Reg); 1998 assert(Reg != AMDGPU::NoRegister); 1999 MachineFunction &MF = CCInfo.getMachineFunction(); 2000 MF.addLiveIn(Reg, RC); 2001 } 2002 2003 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 2004 if (Arg) { 2005 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 2006 Arg.getRegister()); 2007 } else 2008 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 2009 } 2010 2011 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 2012 if (Arg) { 2013 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 2014 Arg.getRegister()); 2015 } else 2016 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 2017 } 2018 2019 /// Allocate implicit function VGPR arguments at the end of allocated user 2020 /// arguments. 2021 void SITargetLowering::allocateSpecialInputVGPRs( 2022 CCState &CCInfo, MachineFunction &MF, 2023 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2024 const unsigned Mask = 0x3ff; 2025 ArgDescriptor Arg; 2026 2027 if (Info.hasWorkItemIDX()) { 2028 Arg = allocateVGPR32Input(CCInfo, Mask); 2029 Info.setWorkItemIDX(Arg); 2030 } 2031 2032 if (Info.hasWorkItemIDY()) { 2033 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 2034 Info.setWorkItemIDY(Arg); 2035 } 2036 2037 if (Info.hasWorkItemIDZ()) 2038 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 2039 } 2040 2041 /// Allocate implicit function VGPR arguments in fixed registers. 2042 void SITargetLowering::allocateSpecialInputVGPRsFixed( 2043 CCState &CCInfo, MachineFunction &MF, 2044 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 2045 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 2046 if (!Reg) 2047 report_fatal_error("failed to allocated VGPR for implicit arguments"); 2048 2049 const unsigned Mask = 0x3ff; 2050 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 2051 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 2052 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 2053 } 2054 2055 void SITargetLowering::allocateSpecialInputSGPRs( 2056 CCState &CCInfo, 2057 MachineFunction &MF, 2058 const SIRegisterInfo &TRI, 2059 SIMachineFunctionInfo &Info) const { 2060 auto &ArgInfo = Info.getArgInfo(); 2061 2062 // TODO: Unify handling with private memory pointers. 2063 if (Info.hasDispatchPtr()) 2064 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 2065 2066 if (Info.hasQueuePtr()) 2067 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 2068 2069 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 2070 // constant offset from the kernarg segment. 2071 if (Info.hasImplicitArgPtr()) 2072 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 2073 2074 if (Info.hasDispatchID()) 2075 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 2076 2077 // flat_scratch_init is not applicable for non-kernel functions. 2078 2079 if (Info.hasWorkGroupIDX()) 2080 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 2081 2082 if (Info.hasWorkGroupIDY()) 2083 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2084 2085 if (Info.hasWorkGroupIDZ()) 2086 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2087 } 2088 2089 // Allocate special inputs passed in user SGPRs. 2090 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2091 MachineFunction &MF, 2092 const SIRegisterInfo &TRI, 2093 SIMachineFunctionInfo &Info) const { 2094 if (Info.hasImplicitBufferPtr()) { 2095 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2096 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2097 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2098 } 2099 2100 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2101 if (Info.hasPrivateSegmentBuffer()) { 2102 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2103 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2104 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2105 } 2106 2107 if (Info.hasDispatchPtr()) { 2108 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2109 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2110 CCInfo.AllocateReg(DispatchPtrReg); 2111 } 2112 2113 if (Info.hasQueuePtr()) { 2114 Register QueuePtrReg = Info.addQueuePtr(TRI); 2115 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2116 CCInfo.AllocateReg(QueuePtrReg); 2117 } 2118 2119 if (Info.hasKernargSegmentPtr()) { 2120 MachineRegisterInfo &MRI = MF.getRegInfo(); 2121 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2122 CCInfo.AllocateReg(InputPtrReg); 2123 2124 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2125 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2126 } 2127 2128 if (Info.hasDispatchID()) { 2129 Register DispatchIDReg = Info.addDispatchID(TRI); 2130 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2131 CCInfo.AllocateReg(DispatchIDReg); 2132 } 2133 2134 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2135 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2136 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2137 CCInfo.AllocateReg(FlatScratchInitReg); 2138 } 2139 2140 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2141 // these from the dispatch pointer. 2142 } 2143 2144 // Allocate special input registers that are initialized per-wave. 2145 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2146 MachineFunction &MF, 2147 SIMachineFunctionInfo &Info, 2148 CallingConv::ID CallConv, 2149 bool IsShader) const { 2150 if (Info.hasWorkGroupIDX()) { 2151 Register Reg = Info.addWorkGroupIDX(); 2152 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2153 CCInfo.AllocateReg(Reg); 2154 } 2155 2156 if (Info.hasWorkGroupIDY()) { 2157 Register Reg = Info.addWorkGroupIDY(); 2158 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2159 CCInfo.AllocateReg(Reg); 2160 } 2161 2162 if (Info.hasWorkGroupIDZ()) { 2163 Register Reg = Info.addWorkGroupIDZ(); 2164 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2165 CCInfo.AllocateReg(Reg); 2166 } 2167 2168 if (Info.hasWorkGroupInfo()) { 2169 Register Reg = Info.addWorkGroupInfo(); 2170 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2171 CCInfo.AllocateReg(Reg); 2172 } 2173 2174 if (Info.hasPrivateSegmentWaveByteOffset()) { 2175 // Scratch wave offset passed in system SGPR. 2176 unsigned PrivateSegmentWaveByteOffsetReg; 2177 2178 if (IsShader) { 2179 PrivateSegmentWaveByteOffsetReg = 2180 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2181 2182 // This is true if the scratch wave byte offset doesn't have a fixed 2183 // location. 2184 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2185 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2186 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2187 } 2188 } else 2189 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2190 2191 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2192 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2193 } 2194 } 2195 2196 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2197 MachineFunction &MF, 2198 const SIRegisterInfo &TRI, 2199 SIMachineFunctionInfo &Info) { 2200 // Now that we've figured out where the scratch register inputs are, see if 2201 // should reserve the arguments and use them directly. 2202 MachineFrameInfo &MFI = MF.getFrameInfo(); 2203 bool HasStackObjects = MFI.hasStackObjects(); 2204 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2205 2206 // Record that we know we have non-spill stack objects so we don't need to 2207 // check all stack objects later. 2208 if (HasStackObjects) 2209 Info.setHasNonSpillStackObjects(true); 2210 2211 // Everything live out of a block is spilled with fast regalloc, so it's 2212 // almost certain that spilling will be required. 2213 if (TM.getOptLevel() == CodeGenOpt::None) 2214 HasStackObjects = true; 2215 2216 // For now assume stack access is needed in any callee functions, so we need 2217 // the scratch registers to pass in. 2218 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2219 2220 if (!ST.enableFlatScratch()) { 2221 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2222 // If we have stack objects, we unquestionably need the private buffer 2223 // resource. For the Code Object V2 ABI, this will be the first 4 user 2224 // SGPR inputs. We can reserve those and use them directly. 2225 2226 Register PrivateSegmentBufferReg = 2227 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2228 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2229 } else { 2230 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2231 // We tentatively reserve the last registers (skipping the last registers 2232 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2233 // we'll replace these with the ones immediately after those which were 2234 // really allocated. In the prologue copies will be inserted from the 2235 // argument to these reserved registers. 2236 2237 // Without HSA, relocations are used for the scratch pointer and the 2238 // buffer resource setup is always inserted in the prologue. Scratch wave 2239 // offset is still in an input SGPR. 2240 Info.setScratchRSrcReg(ReservedBufferReg); 2241 } 2242 } 2243 2244 MachineRegisterInfo &MRI = MF.getRegInfo(); 2245 2246 // For entry functions we have to set up the stack pointer if we use it, 2247 // whereas non-entry functions get this "for free". This means there is no 2248 // intrinsic advantage to using S32 over S34 in cases where we do not have 2249 // calls but do need a frame pointer (i.e. if we are requested to have one 2250 // because frame pointer elimination is disabled). To keep things simple we 2251 // only ever use S32 as the call ABI stack pointer, and so using it does not 2252 // imply we need a separate frame pointer. 2253 // 2254 // Try to use s32 as the SP, but move it if it would interfere with input 2255 // arguments. This won't work with calls though. 2256 // 2257 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2258 // registers. 2259 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2260 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2261 } else { 2262 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2263 2264 if (MFI.hasCalls()) 2265 report_fatal_error("call in graphics shader with too many input SGPRs"); 2266 2267 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2268 if (!MRI.isLiveIn(Reg)) { 2269 Info.setStackPtrOffsetReg(Reg); 2270 break; 2271 } 2272 } 2273 2274 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2275 report_fatal_error("failed to find register for SP"); 2276 } 2277 2278 // hasFP should be accurate for entry functions even before the frame is 2279 // finalized, because it does not rely on the known stack size, only 2280 // properties like whether variable sized objects are present. 2281 if (ST.getFrameLowering()->hasFP(MF)) { 2282 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2283 } 2284 } 2285 2286 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2287 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2288 return !Info->isEntryFunction(); 2289 } 2290 2291 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2292 2293 } 2294 2295 void SITargetLowering::insertCopiesSplitCSR( 2296 MachineBasicBlock *Entry, 2297 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2298 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2299 2300 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2301 if (!IStart) 2302 return; 2303 2304 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2305 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2306 MachineBasicBlock::iterator MBBI = Entry->begin(); 2307 for (const MCPhysReg *I = IStart; *I; ++I) { 2308 const TargetRegisterClass *RC = nullptr; 2309 if (AMDGPU::SReg_64RegClass.contains(*I)) 2310 RC = &AMDGPU::SGPR_64RegClass; 2311 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2312 RC = &AMDGPU::SGPR_32RegClass; 2313 else 2314 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2315 2316 Register NewVR = MRI->createVirtualRegister(RC); 2317 // Create copy from CSR to a virtual register. 2318 Entry->addLiveIn(*I); 2319 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2320 .addReg(*I); 2321 2322 // Insert the copy-back instructions right before the terminator. 2323 for (auto *Exit : Exits) 2324 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2325 TII->get(TargetOpcode::COPY), *I) 2326 .addReg(NewVR); 2327 } 2328 } 2329 2330 SDValue SITargetLowering::LowerFormalArguments( 2331 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2332 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2333 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2334 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2335 2336 MachineFunction &MF = DAG.getMachineFunction(); 2337 const Function &Fn = MF.getFunction(); 2338 FunctionType *FType = MF.getFunction().getFunctionType(); 2339 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2340 2341 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2342 DiagnosticInfoUnsupported NoGraphicsHSA( 2343 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2344 DAG.getContext()->diagnose(NoGraphicsHSA); 2345 return DAG.getEntryNode(); 2346 } 2347 2348 Info->allocateModuleLDSGlobal(Fn.getParent()); 2349 2350 SmallVector<ISD::InputArg, 16> Splits; 2351 SmallVector<CCValAssign, 16> ArgLocs; 2352 BitVector Skipped(Ins.size()); 2353 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2354 *DAG.getContext()); 2355 2356 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2357 bool IsKernel = AMDGPU::isKernel(CallConv); 2358 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2359 2360 if (IsGraphics) { 2361 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2362 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2363 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2364 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2365 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2366 !Info->hasWorkItemIDZ()); 2367 } 2368 2369 if (CallConv == CallingConv::AMDGPU_PS) { 2370 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2371 2372 // At least one interpolation mode must be enabled or else the GPU will 2373 // hang. 2374 // 2375 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2376 // set PSInputAddr, the user wants to enable some bits after the compilation 2377 // based on run-time states. Since we can't know what the final PSInputEna 2378 // will look like, so we shouldn't do anything here and the user should take 2379 // responsibility for the correct programming. 2380 // 2381 // Otherwise, the following restrictions apply: 2382 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2383 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2384 // enabled too. 2385 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2386 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2387 CCInfo.AllocateReg(AMDGPU::VGPR0); 2388 CCInfo.AllocateReg(AMDGPU::VGPR1); 2389 Info->markPSInputAllocated(0); 2390 Info->markPSInputEnabled(0); 2391 } 2392 if (Subtarget->isAmdPalOS()) { 2393 // For isAmdPalOS, the user does not enable some bits after compilation 2394 // based on run-time states; the register values being generated here are 2395 // the final ones set in hardware. Therefore we need to apply the 2396 // workaround to PSInputAddr and PSInputEnable together. (The case where 2397 // a bit is set in PSInputAddr but not PSInputEnable is where the 2398 // frontend set up an input arg for a particular interpolation mode, but 2399 // nothing uses that input arg. Really we should have an earlier pass 2400 // that removes such an arg.) 2401 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2402 if ((PsInputBits & 0x7F) == 0 || 2403 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2404 Info->markPSInputEnabled( 2405 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2406 } 2407 } else if (IsKernel) { 2408 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2409 } else { 2410 Splits.append(Ins.begin(), Ins.end()); 2411 } 2412 2413 if (IsEntryFunc) { 2414 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2415 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2416 } else if (!IsGraphics) { 2417 // For the fixed ABI, pass workitem IDs in the last argument register. 2418 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2419 } 2420 2421 if (IsKernel) { 2422 analyzeFormalArgumentsCompute(CCInfo, Ins); 2423 } else { 2424 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2425 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2426 } 2427 2428 SmallVector<SDValue, 16> Chains; 2429 2430 // FIXME: This is the minimum kernel argument alignment. We should improve 2431 // this to the maximum alignment of the arguments. 2432 // 2433 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2434 // kern arg offset. 2435 const Align KernelArgBaseAlign = Align(16); 2436 2437 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2438 const ISD::InputArg &Arg = Ins[i]; 2439 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2440 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2441 continue; 2442 } 2443 2444 CCValAssign &VA = ArgLocs[ArgIdx++]; 2445 MVT VT = VA.getLocVT(); 2446 2447 if (IsEntryFunc && VA.isMemLoc()) { 2448 VT = Ins[i].VT; 2449 EVT MemVT = VA.getLocVT(); 2450 2451 const uint64_t Offset = VA.getLocMemOffset(); 2452 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2453 2454 if (Arg.Flags.isByRef()) { 2455 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2456 2457 const GCNTargetMachine &TM = 2458 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2459 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2460 Arg.Flags.getPointerAddrSpace())) { 2461 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2462 Arg.Flags.getPointerAddrSpace()); 2463 } 2464 2465 InVals.push_back(Ptr); 2466 continue; 2467 } 2468 2469 SDValue Arg = lowerKernargMemParameter( 2470 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2471 Chains.push_back(Arg.getValue(1)); 2472 2473 auto *ParamTy = 2474 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2475 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2476 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2477 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2478 // On SI local pointers are just offsets into LDS, so they are always 2479 // less than 16-bits. On CI and newer they could potentially be 2480 // real pointers, so we can't guarantee their size. 2481 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2482 DAG.getValueType(MVT::i16)); 2483 } 2484 2485 InVals.push_back(Arg); 2486 continue; 2487 } else if (!IsEntryFunc && VA.isMemLoc()) { 2488 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2489 InVals.push_back(Val); 2490 if (!Arg.Flags.isByVal()) 2491 Chains.push_back(Val.getValue(1)); 2492 continue; 2493 } 2494 2495 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2496 2497 Register Reg = VA.getLocReg(); 2498 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2499 EVT ValVT = VA.getValVT(); 2500 2501 Reg = MF.addLiveIn(Reg, RC); 2502 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2503 2504 if (Arg.Flags.isSRet()) { 2505 // The return object should be reasonably addressable. 2506 2507 // FIXME: This helps when the return is a real sret. If it is a 2508 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2509 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2510 unsigned NumBits 2511 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2512 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2513 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2514 } 2515 2516 // If this is an 8 or 16-bit value, it is really passed promoted 2517 // to 32 bits. Insert an assert[sz]ext to capture this, then 2518 // truncate to the right size. 2519 switch (VA.getLocInfo()) { 2520 case CCValAssign::Full: 2521 break; 2522 case CCValAssign::BCvt: 2523 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2524 break; 2525 case CCValAssign::SExt: 2526 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2527 DAG.getValueType(ValVT)); 2528 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2529 break; 2530 case CCValAssign::ZExt: 2531 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2532 DAG.getValueType(ValVT)); 2533 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2534 break; 2535 case CCValAssign::AExt: 2536 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2537 break; 2538 default: 2539 llvm_unreachable("Unknown loc info!"); 2540 } 2541 2542 InVals.push_back(Val); 2543 } 2544 2545 // Start adding system SGPRs. 2546 if (IsEntryFunc) { 2547 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2548 } else { 2549 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2550 if (!IsGraphics) 2551 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2552 } 2553 2554 auto &ArgUsageInfo = 2555 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2556 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2557 2558 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2559 Info->setBytesInStackArgArea(StackArgSize); 2560 2561 return Chains.empty() ? Chain : 2562 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2563 } 2564 2565 // TODO: If return values can't fit in registers, we should return as many as 2566 // possible in registers before passing on stack. 2567 bool SITargetLowering::CanLowerReturn( 2568 CallingConv::ID CallConv, 2569 MachineFunction &MF, bool IsVarArg, 2570 const SmallVectorImpl<ISD::OutputArg> &Outs, 2571 LLVMContext &Context) const { 2572 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2573 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2574 // for shaders. Vector types should be explicitly handled by CC. 2575 if (AMDGPU::isEntryFunctionCC(CallConv)) 2576 return true; 2577 2578 SmallVector<CCValAssign, 16> RVLocs; 2579 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2580 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2581 } 2582 2583 SDValue 2584 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2585 bool isVarArg, 2586 const SmallVectorImpl<ISD::OutputArg> &Outs, 2587 const SmallVectorImpl<SDValue> &OutVals, 2588 const SDLoc &DL, SelectionDAG &DAG) const { 2589 MachineFunction &MF = DAG.getMachineFunction(); 2590 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2591 2592 if (AMDGPU::isKernel(CallConv)) { 2593 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2594 OutVals, DL, DAG); 2595 } 2596 2597 bool IsShader = AMDGPU::isShader(CallConv); 2598 2599 Info->setIfReturnsVoid(Outs.empty()); 2600 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2601 2602 // CCValAssign - represent the assignment of the return value to a location. 2603 SmallVector<CCValAssign, 48> RVLocs; 2604 SmallVector<ISD::OutputArg, 48> Splits; 2605 2606 // CCState - Info about the registers and stack slots. 2607 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2608 *DAG.getContext()); 2609 2610 // Analyze outgoing return values. 2611 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2612 2613 SDValue Flag; 2614 SmallVector<SDValue, 48> RetOps; 2615 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2616 2617 // Add return address for callable functions. 2618 if (!Info->isEntryFunction()) { 2619 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2620 SDValue ReturnAddrReg = CreateLiveInRegister( 2621 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2622 2623 SDValue ReturnAddrVirtualReg = 2624 DAG.getRegister(MF.getRegInfo().createVirtualRegister( 2625 CallConv != CallingConv::AMDGPU_Gfx 2626 ? &AMDGPU::CCR_SGPR_64RegClass 2627 : &AMDGPU::Gfx_CCR_SGPR_64RegClass), 2628 MVT::i64); 2629 Chain = 2630 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2631 Flag = Chain.getValue(1); 2632 RetOps.push_back(ReturnAddrVirtualReg); 2633 } 2634 2635 // Copy the result values into the output registers. 2636 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2637 ++I, ++RealRVLocIdx) { 2638 CCValAssign &VA = RVLocs[I]; 2639 assert(VA.isRegLoc() && "Can only return in registers!"); 2640 // TODO: Partially return in registers if return values don't fit. 2641 SDValue Arg = OutVals[RealRVLocIdx]; 2642 2643 // Copied from other backends. 2644 switch (VA.getLocInfo()) { 2645 case CCValAssign::Full: 2646 break; 2647 case CCValAssign::BCvt: 2648 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2649 break; 2650 case CCValAssign::SExt: 2651 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2652 break; 2653 case CCValAssign::ZExt: 2654 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2655 break; 2656 case CCValAssign::AExt: 2657 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2658 break; 2659 default: 2660 llvm_unreachable("Unknown loc info!"); 2661 } 2662 2663 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2664 Flag = Chain.getValue(1); 2665 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2666 } 2667 2668 // FIXME: Does sret work properly? 2669 if (!Info->isEntryFunction()) { 2670 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2671 const MCPhysReg *I = 2672 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2673 if (I) { 2674 for (; *I; ++I) { 2675 if (AMDGPU::SReg_64RegClass.contains(*I)) 2676 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2677 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2678 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2679 else 2680 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2681 } 2682 } 2683 } 2684 2685 // Update chain and glue. 2686 RetOps[0] = Chain; 2687 if (Flag.getNode()) 2688 RetOps.push_back(Flag); 2689 2690 unsigned Opc = AMDGPUISD::ENDPGM; 2691 if (!IsWaveEnd) { 2692 if (IsShader) 2693 Opc = AMDGPUISD::RETURN_TO_EPILOG; 2694 else if (CallConv == CallingConv::AMDGPU_Gfx) 2695 Opc = AMDGPUISD::RET_GFX_FLAG; 2696 else 2697 Opc = AMDGPUISD::RET_FLAG; 2698 } 2699 2700 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2701 } 2702 2703 SDValue SITargetLowering::LowerCallResult( 2704 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2705 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2706 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2707 SDValue ThisVal) const { 2708 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2709 2710 // Assign locations to each value returned by this call. 2711 SmallVector<CCValAssign, 16> RVLocs; 2712 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2713 *DAG.getContext()); 2714 CCInfo.AnalyzeCallResult(Ins, RetCC); 2715 2716 // Copy all of the result registers out of their specified physreg. 2717 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2718 CCValAssign VA = RVLocs[i]; 2719 SDValue Val; 2720 2721 if (VA.isRegLoc()) { 2722 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2723 Chain = Val.getValue(1); 2724 InFlag = Val.getValue(2); 2725 } else if (VA.isMemLoc()) { 2726 report_fatal_error("TODO: return values in memory"); 2727 } else 2728 llvm_unreachable("unknown argument location type"); 2729 2730 switch (VA.getLocInfo()) { 2731 case CCValAssign::Full: 2732 break; 2733 case CCValAssign::BCvt: 2734 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2735 break; 2736 case CCValAssign::ZExt: 2737 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2738 DAG.getValueType(VA.getValVT())); 2739 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2740 break; 2741 case CCValAssign::SExt: 2742 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2743 DAG.getValueType(VA.getValVT())); 2744 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2745 break; 2746 case CCValAssign::AExt: 2747 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2748 break; 2749 default: 2750 llvm_unreachable("Unknown loc info!"); 2751 } 2752 2753 InVals.push_back(Val); 2754 } 2755 2756 return Chain; 2757 } 2758 2759 // Add code to pass special inputs required depending on used features separate 2760 // from the explicit user arguments present in the IR. 2761 void SITargetLowering::passSpecialInputs( 2762 CallLoweringInfo &CLI, 2763 CCState &CCInfo, 2764 const SIMachineFunctionInfo &Info, 2765 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2766 SmallVectorImpl<SDValue> &MemOpChains, 2767 SDValue Chain) const { 2768 // If we don't have a call site, this was a call inserted by 2769 // legalization. These can never use special inputs. 2770 if (!CLI.CB) 2771 return; 2772 2773 SelectionDAG &DAG = CLI.DAG; 2774 const SDLoc &DL = CLI.DL; 2775 2776 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2777 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2778 2779 const AMDGPUFunctionArgInfo *CalleeArgInfo 2780 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2781 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2782 auto &ArgUsageInfo = 2783 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2784 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2785 } 2786 2787 // TODO: Unify with private memory register handling. This is complicated by 2788 // the fact that at least in kernels, the input argument is not necessarily 2789 // in the same location as the input. 2790 static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue, 2791 StringLiteral> ImplicitAttrs[] = { 2792 {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"}, 2793 {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" }, 2794 {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"}, 2795 {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"}, 2796 {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"}, 2797 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"}, 2798 {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"} 2799 }; 2800 2801 for (auto Attr : ImplicitAttrs) { 2802 const ArgDescriptor *OutgoingArg; 2803 const TargetRegisterClass *ArgRC; 2804 LLT ArgTy; 2805 2806 AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first; 2807 2808 // If the callee does not use the attribute value, skip copying the value. 2809 if (CLI.CB->hasFnAttr(Attr.second)) 2810 continue; 2811 2812 std::tie(OutgoingArg, ArgRC, ArgTy) = 2813 CalleeArgInfo->getPreloadedValue(InputID); 2814 if (!OutgoingArg) 2815 continue; 2816 2817 const ArgDescriptor *IncomingArg; 2818 const TargetRegisterClass *IncomingArgRC; 2819 LLT Ty; 2820 std::tie(IncomingArg, IncomingArgRC, Ty) = 2821 CallerArgInfo.getPreloadedValue(InputID); 2822 assert(IncomingArgRC == ArgRC); 2823 2824 // All special arguments are ints for now. 2825 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2826 SDValue InputReg; 2827 2828 if (IncomingArg) { 2829 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2830 } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) { 2831 // The implicit arg ptr is special because it doesn't have a corresponding 2832 // input for kernels, and is computed from the kernarg segment pointer. 2833 InputReg = getImplicitArgPtr(DAG, DL); 2834 } else { 2835 // We may have proven the input wasn't needed, although the ABI is 2836 // requiring it. We just need to allocate the register appropriately. 2837 InputReg = DAG.getUNDEF(ArgVT); 2838 } 2839 2840 if (OutgoingArg->isRegister()) { 2841 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2842 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2843 report_fatal_error("failed to allocate implicit input argument"); 2844 } else { 2845 unsigned SpecialArgOffset = 2846 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2847 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2848 SpecialArgOffset); 2849 MemOpChains.push_back(ArgStore); 2850 } 2851 } 2852 2853 // Pack workitem IDs into a single register or pass it as is if already 2854 // packed. 2855 const ArgDescriptor *OutgoingArg; 2856 const TargetRegisterClass *ArgRC; 2857 LLT Ty; 2858 2859 std::tie(OutgoingArg, ArgRC, Ty) = 2860 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2861 if (!OutgoingArg) 2862 std::tie(OutgoingArg, ArgRC, Ty) = 2863 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2864 if (!OutgoingArg) 2865 std::tie(OutgoingArg, ArgRC, Ty) = 2866 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2867 if (!OutgoingArg) 2868 return; 2869 2870 const ArgDescriptor *IncomingArgX = std::get<0>( 2871 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2872 const ArgDescriptor *IncomingArgY = std::get<0>( 2873 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2874 const ArgDescriptor *IncomingArgZ = std::get<0>( 2875 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2876 2877 SDValue InputReg; 2878 SDLoc SL; 2879 2880 const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x"); 2881 const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y"); 2882 const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z"); 2883 2884 // If incoming ids are not packed we need to pack them. 2885 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX && 2886 NeedWorkItemIDX) 2887 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2888 2889 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY && 2890 NeedWorkItemIDY) { 2891 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2892 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2893 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2894 InputReg = InputReg.getNode() ? 2895 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2896 } 2897 2898 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ && 2899 NeedWorkItemIDZ) { 2900 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2901 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2902 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2903 InputReg = InputReg.getNode() ? 2904 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2905 } 2906 2907 if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) { 2908 // Workitem ids are already packed, any of present incoming arguments 2909 // will carry all required fields. 2910 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2911 IncomingArgX ? *IncomingArgX : 2912 IncomingArgY ? *IncomingArgY : 2913 *IncomingArgZ, ~0u); 2914 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2915 } 2916 2917 if (OutgoingArg->isRegister()) { 2918 if (InputReg) 2919 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2920 2921 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2922 } else { 2923 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2924 if (InputReg) { 2925 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2926 SpecialArgOffset); 2927 MemOpChains.push_back(ArgStore); 2928 } 2929 } 2930 } 2931 2932 static bool canGuaranteeTCO(CallingConv::ID CC) { 2933 return CC == CallingConv::Fast; 2934 } 2935 2936 /// Return true if we might ever do TCO for calls with this calling convention. 2937 static bool mayTailCallThisCC(CallingConv::ID CC) { 2938 switch (CC) { 2939 case CallingConv::C: 2940 case CallingConv::AMDGPU_Gfx: 2941 return true; 2942 default: 2943 return canGuaranteeTCO(CC); 2944 } 2945 } 2946 2947 bool SITargetLowering::isEligibleForTailCallOptimization( 2948 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2949 const SmallVectorImpl<ISD::OutputArg> &Outs, 2950 const SmallVectorImpl<SDValue> &OutVals, 2951 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2952 if (!mayTailCallThisCC(CalleeCC)) 2953 return false; 2954 2955 // For a divergent call target, we need to do a waterfall loop over the 2956 // possible callees which precludes us from using a simple jump. 2957 if (Callee->isDivergent()) 2958 return false; 2959 2960 MachineFunction &MF = DAG.getMachineFunction(); 2961 const Function &CallerF = MF.getFunction(); 2962 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2963 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2964 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2965 2966 // Kernels aren't callable, and don't have a live in return address so it 2967 // doesn't make sense to do a tail call with entry functions. 2968 if (!CallerPreserved) 2969 return false; 2970 2971 bool CCMatch = CallerCC == CalleeCC; 2972 2973 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2974 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2975 return true; 2976 return false; 2977 } 2978 2979 // TODO: Can we handle var args? 2980 if (IsVarArg) 2981 return false; 2982 2983 for (const Argument &Arg : CallerF.args()) { 2984 if (Arg.hasByValAttr()) 2985 return false; 2986 } 2987 2988 LLVMContext &Ctx = *DAG.getContext(); 2989 2990 // Check that the call results are passed in the same way. 2991 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2992 CCAssignFnForCall(CalleeCC, IsVarArg), 2993 CCAssignFnForCall(CallerCC, IsVarArg))) 2994 return false; 2995 2996 // The callee has to preserve all registers the caller needs to preserve. 2997 if (!CCMatch) { 2998 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2999 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3000 return false; 3001 } 3002 3003 // Nothing more to check if the callee is taking no arguments. 3004 if (Outs.empty()) 3005 return true; 3006 3007 SmallVector<CCValAssign, 16> ArgLocs; 3008 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 3009 3010 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 3011 3012 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 3013 // If the stack arguments for this call do not fit into our own save area then 3014 // the call cannot be made tail. 3015 // TODO: Is this really necessary? 3016 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3017 return false; 3018 3019 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3020 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 3021 } 3022 3023 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 3024 if (!CI->isTailCall()) 3025 return false; 3026 3027 const Function *ParentFn = CI->getParent()->getParent(); 3028 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 3029 return false; 3030 return true; 3031 } 3032 3033 // The wave scratch offset register is used as the global base pointer. 3034 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 3035 SmallVectorImpl<SDValue> &InVals) const { 3036 SelectionDAG &DAG = CLI.DAG; 3037 const SDLoc &DL = CLI.DL; 3038 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3039 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3040 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3041 SDValue Chain = CLI.Chain; 3042 SDValue Callee = CLI.Callee; 3043 bool &IsTailCall = CLI.IsTailCall; 3044 CallingConv::ID CallConv = CLI.CallConv; 3045 bool IsVarArg = CLI.IsVarArg; 3046 bool IsSibCall = false; 3047 bool IsThisReturn = false; 3048 MachineFunction &MF = DAG.getMachineFunction(); 3049 3050 if (Callee.isUndef() || isNullConstant(Callee)) { 3051 if (!CLI.IsTailCall) { 3052 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 3053 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 3054 } 3055 3056 return Chain; 3057 } 3058 3059 if (IsVarArg) { 3060 return lowerUnhandledCall(CLI, InVals, 3061 "unsupported call to variadic function "); 3062 } 3063 3064 if (!CLI.CB) 3065 report_fatal_error("unsupported libcall legalization"); 3066 3067 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 3068 return lowerUnhandledCall(CLI, InVals, 3069 "unsupported required tail call to function "); 3070 } 3071 3072 if (AMDGPU::isShader(CallConv)) { 3073 // Note the issue is with the CC of the called function, not of the call 3074 // itself. 3075 return lowerUnhandledCall(CLI, InVals, 3076 "unsupported call to a shader function "); 3077 } 3078 3079 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 3080 CallConv != CallingConv::AMDGPU_Gfx) { 3081 // Only allow calls with specific calling conventions. 3082 return lowerUnhandledCall(CLI, InVals, 3083 "unsupported calling convention for call from " 3084 "graphics shader of function "); 3085 } 3086 3087 if (IsTailCall) { 3088 IsTailCall = isEligibleForTailCallOptimization( 3089 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3090 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 3091 report_fatal_error("failed to perform tail call elimination on a call " 3092 "site marked musttail"); 3093 } 3094 3095 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3096 3097 // A sibling call is one where we're under the usual C ABI and not planning 3098 // to change that but can still do a tail call: 3099 if (!TailCallOpt && IsTailCall) 3100 IsSibCall = true; 3101 3102 if (IsTailCall) 3103 ++NumTailCalls; 3104 } 3105 3106 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3107 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3108 SmallVector<SDValue, 8> MemOpChains; 3109 3110 // Analyze operands of the call, assigning locations to each operand. 3111 SmallVector<CCValAssign, 16> ArgLocs; 3112 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3113 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3114 3115 if (CallConv != CallingConv::AMDGPU_Gfx) { 3116 // With a fixed ABI, allocate fixed registers before user arguments. 3117 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3118 } 3119 3120 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3121 3122 // Get a count of how many bytes are to be pushed on the stack. 3123 unsigned NumBytes = CCInfo.getNextStackOffset(); 3124 3125 if (IsSibCall) { 3126 // Since we're not changing the ABI to make this a tail call, the memory 3127 // operands are already available in the caller's incoming argument space. 3128 NumBytes = 0; 3129 } 3130 3131 // FPDiff is the byte offset of the call's argument area from the callee's. 3132 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3133 // by this amount for a tail call. In a sibling call it must be 0 because the 3134 // caller will deallocate the entire stack and the callee still expects its 3135 // arguments to begin at SP+0. Completely unused for non-tail calls. 3136 int32_t FPDiff = 0; 3137 MachineFrameInfo &MFI = MF.getFrameInfo(); 3138 3139 // Adjust the stack pointer for the new arguments... 3140 // These operations are automatically eliminated by the prolog/epilog pass 3141 if (!IsSibCall) { 3142 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3143 3144 if (!Subtarget->enableFlatScratch()) { 3145 SmallVector<SDValue, 4> CopyFromChains; 3146 3147 // In the HSA case, this should be an identity copy. 3148 SDValue ScratchRSrcReg 3149 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3150 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3151 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3152 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3153 } 3154 } 3155 3156 MVT PtrVT = MVT::i32; 3157 3158 // Walk the register/memloc assignments, inserting copies/loads. 3159 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3160 CCValAssign &VA = ArgLocs[i]; 3161 SDValue Arg = OutVals[i]; 3162 3163 // Promote the value if needed. 3164 switch (VA.getLocInfo()) { 3165 case CCValAssign::Full: 3166 break; 3167 case CCValAssign::BCvt: 3168 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3169 break; 3170 case CCValAssign::ZExt: 3171 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3172 break; 3173 case CCValAssign::SExt: 3174 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3175 break; 3176 case CCValAssign::AExt: 3177 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3178 break; 3179 case CCValAssign::FPExt: 3180 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3181 break; 3182 default: 3183 llvm_unreachable("Unknown loc info!"); 3184 } 3185 3186 if (VA.isRegLoc()) { 3187 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3188 } else { 3189 assert(VA.isMemLoc()); 3190 3191 SDValue DstAddr; 3192 MachinePointerInfo DstInfo; 3193 3194 unsigned LocMemOffset = VA.getLocMemOffset(); 3195 int32_t Offset = LocMemOffset; 3196 3197 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3198 MaybeAlign Alignment; 3199 3200 if (IsTailCall) { 3201 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3202 unsigned OpSize = Flags.isByVal() ? 3203 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3204 3205 // FIXME: We can have better than the minimum byval required alignment. 3206 Alignment = 3207 Flags.isByVal() 3208 ? Flags.getNonZeroByValAlign() 3209 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3210 3211 Offset = Offset + FPDiff; 3212 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3213 3214 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3215 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3216 3217 // Make sure any stack arguments overlapping with where we're storing 3218 // are loaded before this eventual operation. Otherwise they'll be 3219 // clobbered. 3220 3221 // FIXME: Why is this really necessary? This seems to just result in a 3222 // lot of code to copy the stack and write them back to the same 3223 // locations, which are supposed to be immutable? 3224 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3225 } else { 3226 // Stores to the argument stack area are relative to the stack pointer. 3227 SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(), 3228 MVT::i32); 3229 DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff); 3230 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3231 Alignment = 3232 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3233 } 3234 3235 if (Outs[i].Flags.isByVal()) { 3236 SDValue SizeNode = 3237 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3238 SDValue Cpy = 3239 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3240 Outs[i].Flags.getNonZeroByValAlign(), 3241 /*isVol = */ false, /*AlwaysInline = */ true, 3242 /*isTailCall = */ false, DstInfo, 3243 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3244 3245 MemOpChains.push_back(Cpy); 3246 } else { 3247 SDValue Store = 3248 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3249 MemOpChains.push_back(Store); 3250 } 3251 } 3252 } 3253 3254 if (!MemOpChains.empty()) 3255 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3256 3257 // Build a sequence of copy-to-reg nodes chained together with token chain 3258 // and flag operands which copy the outgoing args into the appropriate regs. 3259 SDValue InFlag; 3260 for (auto &RegToPass : RegsToPass) { 3261 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3262 RegToPass.second, InFlag); 3263 InFlag = Chain.getValue(1); 3264 } 3265 3266 3267 SDValue PhysReturnAddrReg; 3268 if (IsTailCall) { 3269 // Since the return is being combined with the call, we need to pass on the 3270 // return address. 3271 3272 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3273 SDValue ReturnAddrReg = CreateLiveInRegister( 3274 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3275 3276 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3277 MVT::i64); 3278 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3279 InFlag = Chain.getValue(1); 3280 } 3281 3282 // We don't usually want to end the call-sequence here because we would tidy 3283 // the frame up *after* the call, however in the ABI-changing tail-call case 3284 // we've carefully laid out the parameters so that when sp is reset they'll be 3285 // in the correct location. 3286 if (IsTailCall && !IsSibCall) { 3287 Chain = DAG.getCALLSEQ_END(Chain, 3288 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3289 DAG.getTargetConstant(0, DL, MVT::i32), 3290 InFlag, DL); 3291 InFlag = Chain.getValue(1); 3292 } 3293 3294 std::vector<SDValue> Ops; 3295 Ops.push_back(Chain); 3296 Ops.push_back(Callee); 3297 // Add a redundant copy of the callee global which will not be legalized, as 3298 // we need direct access to the callee later. 3299 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3300 const GlobalValue *GV = GSD->getGlobal(); 3301 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3302 } else { 3303 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3304 } 3305 3306 if (IsTailCall) { 3307 // Each tail call may have to adjust the stack by a different amount, so 3308 // this information must travel along with the operation for eventual 3309 // consumption by emitEpilogue. 3310 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3311 3312 Ops.push_back(PhysReturnAddrReg); 3313 } 3314 3315 // Add argument registers to the end of the list so that they are known live 3316 // into the call. 3317 for (auto &RegToPass : RegsToPass) { 3318 Ops.push_back(DAG.getRegister(RegToPass.first, 3319 RegToPass.second.getValueType())); 3320 } 3321 3322 // Add a register mask operand representing the call-preserved registers. 3323 3324 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3325 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3326 assert(Mask && "Missing call preserved mask for calling convention"); 3327 Ops.push_back(DAG.getRegisterMask(Mask)); 3328 3329 if (InFlag.getNode()) 3330 Ops.push_back(InFlag); 3331 3332 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3333 3334 // If we're doing a tall call, use a TC_RETURN here rather than an 3335 // actual call instruction. 3336 if (IsTailCall) { 3337 MFI.setHasTailCall(); 3338 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3339 } 3340 3341 // Returns a chain and a flag for retval copy to use. 3342 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3343 Chain = Call.getValue(0); 3344 InFlag = Call.getValue(1); 3345 3346 uint64_t CalleePopBytes = NumBytes; 3347 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3348 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3349 InFlag, DL); 3350 if (!Ins.empty()) 3351 InFlag = Chain.getValue(1); 3352 3353 // Handle result values, copying them out of physregs into vregs that we 3354 // return. 3355 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3356 InVals, IsThisReturn, 3357 IsThisReturn ? OutVals[0] : SDValue()); 3358 } 3359 3360 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3361 // except for applying the wave size scale to the increment amount. 3362 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3363 SDValue Op, SelectionDAG &DAG) const { 3364 const MachineFunction &MF = DAG.getMachineFunction(); 3365 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3366 3367 SDLoc dl(Op); 3368 EVT VT = Op.getValueType(); 3369 SDValue Tmp1 = Op; 3370 SDValue Tmp2 = Op.getValue(1); 3371 SDValue Tmp3 = Op.getOperand(2); 3372 SDValue Chain = Tmp1.getOperand(0); 3373 3374 Register SPReg = Info->getStackPtrOffsetReg(); 3375 3376 // Chain the dynamic stack allocation so that it doesn't modify the stack 3377 // pointer when other instructions are using the stack. 3378 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3379 3380 SDValue Size = Tmp2.getOperand(1); 3381 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3382 Chain = SP.getValue(1); 3383 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3384 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3385 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3386 unsigned Opc = 3387 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3388 ISD::ADD : ISD::SUB; 3389 3390 SDValue ScaledSize = DAG.getNode( 3391 ISD::SHL, dl, VT, Size, 3392 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3393 3394 Align StackAlign = TFL->getStackAlign(); 3395 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3396 if (Alignment && *Alignment > StackAlign) { 3397 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3398 DAG.getConstant(-(uint64_t)Alignment->value() 3399 << ST.getWavefrontSizeLog2(), 3400 dl, VT)); 3401 } 3402 3403 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3404 Tmp2 = DAG.getCALLSEQ_END( 3405 Chain, DAG.getIntPtrConstant(0, dl, true), 3406 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3407 3408 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3409 } 3410 3411 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3412 SelectionDAG &DAG) const { 3413 // We only handle constant sizes here to allow non-entry block, static sized 3414 // allocas. A truly dynamic value is more difficult to support because we 3415 // don't know if the size value is uniform or not. If the size isn't uniform, 3416 // we would need to do a wave reduction to get the maximum size to know how 3417 // much to increment the uniform stack pointer. 3418 SDValue Size = Op.getOperand(1); 3419 if (isa<ConstantSDNode>(Size)) 3420 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3421 3422 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3423 } 3424 3425 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3426 const MachineFunction &MF) const { 3427 Register Reg = StringSwitch<Register>(RegName) 3428 .Case("m0", AMDGPU::M0) 3429 .Case("exec", AMDGPU::EXEC) 3430 .Case("exec_lo", AMDGPU::EXEC_LO) 3431 .Case("exec_hi", AMDGPU::EXEC_HI) 3432 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3433 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3434 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3435 .Default(Register()); 3436 3437 if (Reg == AMDGPU::NoRegister) { 3438 report_fatal_error(Twine("invalid register name \"" 3439 + StringRef(RegName) + "\".")); 3440 3441 } 3442 3443 if (!Subtarget->hasFlatScrRegister() && 3444 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3445 report_fatal_error(Twine("invalid register \"" 3446 + StringRef(RegName) + "\" for subtarget.")); 3447 } 3448 3449 switch (Reg) { 3450 case AMDGPU::M0: 3451 case AMDGPU::EXEC_LO: 3452 case AMDGPU::EXEC_HI: 3453 case AMDGPU::FLAT_SCR_LO: 3454 case AMDGPU::FLAT_SCR_HI: 3455 if (VT.getSizeInBits() == 32) 3456 return Reg; 3457 break; 3458 case AMDGPU::EXEC: 3459 case AMDGPU::FLAT_SCR: 3460 if (VT.getSizeInBits() == 64) 3461 return Reg; 3462 break; 3463 default: 3464 llvm_unreachable("missing register type checking"); 3465 } 3466 3467 report_fatal_error(Twine("invalid type for register \"" 3468 + StringRef(RegName) + "\".")); 3469 } 3470 3471 // If kill is not the last instruction, split the block so kill is always a 3472 // proper terminator. 3473 MachineBasicBlock * 3474 SITargetLowering::splitKillBlock(MachineInstr &MI, 3475 MachineBasicBlock *BB) const { 3476 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3477 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3478 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3479 return SplitBB; 3480 } 3481 3482 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3483 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3484 // be the first instruction in the remainder block. 3485 // 3486 /// \returns { LoopBody, Remainder } 3487 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3488 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3489 MachineFunction *MF = MBB.getParent(); 3490 MachineBasicBlock::iterator I(&MI); 3491 3492 // To insert the loop we need to split the block. Move everything after this 3493 // point to a new block, and insert a new empty block between the two. 3494 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3495 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3496 MachineFunction::iterator MBBI(MBB); 3497 ++MBBI; 3498 3499 MF->insert(MBBI, LoopBB); 3500 MF->insert(MBBI, RemainderBB); 3501 3502 LoopBB->addSuccessor(LoopBB); 3503 LoopBB->addSuccessor(RemainderBB); 3504 3505 // Move the rest of the block into a new block. 3506 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3507 3508 if (InstInLoop) { 3509 auto Next = std::next(I); 3510 3511 // Move instruction to loop body. 3512 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3513 3514 // Move the rest of the block. 3515 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3516 } else { 3517 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3518 } 3519 3520 MBB.addSuccessor(LoopBB); 3521 3522 return std::make_pair(LoopBB, RemainderBB); 3523 } 3524 3525 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3526 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3527 MachineBasicBlock *MBB = MI.getParent(); 3528 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3529 auto I = MI.getIterator(); 3530 auto E = std::next(I); 3531 3532 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3533 .addImm(0); 3534 3535 MIBundleBuilder Bundler(*MBB, I, E); 3536 finalizeBundle(*MBB, Bundler.begin()); 3537 } 3538 3539 MachineBasicBlock * 3540 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3541 MachineBasicBlock *BB) const { 3542 const DebugLoc &DL = MI.getDebugLoc(); 3543 3544 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3545 3546 MachineBasicBlock *LoopBB; 3547 MachineBasicBlock *RemainderBB; 3548 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3549 3550 // Apparently kill flags are only valid if the def is in the same block? 3551 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3552 Src->setIsKill(false); 3553 3554 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3555 3556 MachineBasicBlock::iterator I = LoopBB->end(); 3557 3558 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3559 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3560 3561 // Clear TRAP_STS.MEM_VIOL 3562 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3563 .addImm(0) 3564 .addImm(EncodedReg); 3565 3566 bundleInstWithWaitcnt(MI); 3567 3568 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3569 3570 // Load and check TRAP_STS.MEM_VIOL 3571 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3572 .addImm(EncodedReg); 3573 3574 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3575 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3576 .addReg(Reg, RegState::Kill) 3577 .addImm(0); 3578 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3579 .addMBB(LoopBB); 3580 3581 return RemainderBB; 3582 } 3583 3584 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3585 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3586 // will only do one iteration. In the worst case, this will loop 64 times. 3587 // 3588 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3589 static MachineBasicBlock::iterator 3590 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3591 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3592 const DebugLoc &DL, const MachineOperand &Idx, 3593 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3594 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3595 Register &SGPRIdxReg) { 3596 3597 MachineFunction *MF = OrigBB.getParent(); 3598 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3599 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3600 MachineBasicBlock::iterator I = LoopBB.begin(); 3601 3602 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3603 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3604 Register NewExec = MRI.createVirtualRegister(BoolRC); 3605 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3606 Register CondReg = MRI.createVirtualRegister(BoolRC); 3607 3608 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3609 .addReg(InitReg) 3610 .addMBB(&OrigBB) 3611 .addReg(ResultReg) 3612 .addMBB(&LoopBB); 3613 3614 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3615 .addReg(InitSaveExecReg) 3616 .addMBB(&OrigBB) 3617 .addReg(NewExec) 3618 .addMBB(&LoopBB); 3619 3620 // Read the next variant <- also loop target. 3621 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3622 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3623 3624 // Compare the just read M0 value to all possible Idx values. 3625 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3626 .addReg(CurrentIdxReg) 3627 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3628 3629 // Update EXEC, save the original EXEC value to VCC. 3630 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3631 : AMDGPU::S_AND_SAVEEXEC_B64), 3632 NewExec) 3633 .addReg(CondReg, RegState::Kill); 3634 3635 MRI.setSimpleHint(NewExec, CondReg); 3636 3637 if (UseGPRIdxMode) { 3638 if (Offset == 0) { 3639 SGPRIdxReg = CurrentIdxReg; 3640 } else { 3641 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3642 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3643 .addReg(CurrentIdxReg, RegState::Kill) 3644 .addImm(Offset); 3645 } 3646 } else { 3647 // Move index from VCC into M0 3648 if (Offset == 0) { 3649 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3650 .addReg(CurrentIdxReg, RegState::Kill); 3651 } else { 3652 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3653 .addReg(CurrentIdxReg, RegState::Kill) 3654 .addImm(Offset); 3655 } 3656 } 3657 3658 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3659 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3660 MachineInstr *InsertPt = 3661 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3662 : AMDGPU::S_XOR_B64_term), Exec) 3663 .addReg(Exec) 3664 .addReg(NewExec); 3665 3666 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3667 // s_cbranch_scc0? 3668 3669 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3670 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3671 .addMBB(&LoopBB); 3672 3673 return InsertPt->getIterator(); 3674 } 3675 3676 // This has slightly sub-optimal regalloc when the source vector is killed by 3677 // the read. The register allocator does not understand that the kill is 3678 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3679 // subregister from it, using 1 more VGPR than necessary. This was saved when 3680 // this was expanded after register allocation. 3681 static MachineBasicBlock::iterator 3682 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3683 unsigned InitResultReg, unsigned PhiReg, int Offset, 3684 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3685 MachineFunction *MF = MBB.getParent(); 3686 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3687 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3688 MachineRegisterInfo &MRI = MF->getRegInfo(); 3689 const DebugLoc &DL = MI.getDebugLoc(); 3690 MachineBasicBlock::iterator I(&MI); 3691 3692 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3693 Register DstReg = MI.getOperand(0).getReg(); 3694 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3695 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3696 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3697 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3698 3699 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3700 3701 // Save the EXEC mask 3702 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3703 .addReg(Exec); 3704 3705 MachineBasicBlock *LoopBB; 3706 MachineBasicBlock *RemainderBB; 3707 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3708 3709 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3710 3711 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3712 InitResultReg, DstReg, PhiReg, TmpExec, 3713 Offset, UseGPRIdxMode, SGPRIdxReg); 3714 3715 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3716 MachineFunction::iterator MBBI(LoopBB); 3717 ++MBBI; 3718 MF->insert(MBBI, LandingPad); 3719 LoopBB->removeSuccessor(RemainderBB); 3720 LandingPad->addSuccessor(RemainderBB); 3721 LoopBB->addSuccessor(LandingPad); 3722 MachineBasicBlock::iterator First = LandingPad->begin(); 3723 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3724 .addReg(SaveExec); 3725 3726 return InsPt; 3727 } 3728 3729 // Returns subreg index, offset 3730 static std::pair<unsigned, int> 3731 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3732 const TargetRegisterClass *SuperRC, 3733 unsigned VecReg, 3734 int Offset) { 3735 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3736 3737 // Skip out of bounds offsets, or else we would end up using an undefined 3738 // register. 3739 if (Offset >= NumElts || Offset < 0) 3740 return std::make_pair(AMDGPU::sub0, Offset); 3741 3742 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3743 } 3744 3745 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3746 MachineRegisterInfo &MRI, MachineInstr &MI, 3747 int Offset) { 3748 MachineBasicBlock *MBB = MI.getParent(); 3749 const DebugLoc &DL = MI.getDebugLoc(); 3750 MachineBasicBlock::iterator I(&MI); 3751 3752 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3753 3754 assert(Idx->getReg() != AMDGPU::NoRegister); 3755 3756 if (Offset == 0) { 3757 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3758 } else { 3759 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3760 .add(*Idx) 3761 .addImm(Offset); 3762 } 3763 } 3764 3765 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3766 MachineRegisterInfo &MRI, MachineInstr &MI, 3767 int Offset) { 3768 MachineBasicBlock *MBB = MI.getParent(); 3769 const DebugLoc &DL = MI.getDebugLoc(); 3770 MachineBasicBlock::iterator I(&MI); 3771 3772 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3773 3774 if (Offset == 0) 3775 return Idx->getReg(); 3776 3777 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3778 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3779 .add(*Idx) 3780 .addImm(Offset); 3781 return Tmp; 3782 } 3783 3784 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3785 MachineBasicBlock &MBB, 3786 const GCNSubtarget &ST) { 3787 const SIInstrInfo *TII = ST.getInstrInfo(); 3788 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3789 MachineFunction *MF = MBB.getParent(); 3790 MachineRegisterInfo &MRI = MF->getRegInfo(); 3791 3792 Register Dst = MI.getOperand(0).getReg(); 3793 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3794 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3795 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3796 3797 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3798 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3799 3800 unsigned SubReg; 3801 std::tie(SubReg, Offset) 3802 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3803 3804 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3805 3806 // Check for a SGPR index. 3807 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3808 MachineBasicBlock::iterator I(&MI); 3809 const DebugLoc &DL = MI.getDebugLoc(); 3810 3811 if (UseGPRIdxMode) { 3812 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3813 // to avoid interfering with other uses, so probably requires a new 3814 // optimization pass. 3815 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3816 3817 const MCInstrDesc &GPRIDXDesc = 3818 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3819 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3820 .addReg(SrcReg) 3821 .addReg(Idx) 3822 .addImm(SubReg); 3823 } else { 3824 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3825 3826 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3827 .addReg(SrcReg, 0, SubReg) 3828 .addReg(SrcReg, RegState::Implicit); 3829 } 3830 3831 MI.eraseFromParent(); 3832 3833 return &MBB; 3834 } 3835 3836 // Control flow needs to be inserted if indexing with a VGPR. 3837 const DebugLoc &DL = MI.getDebugLoc(); 3838 MachineBasicBlock::iterator I(&MI); 3839 3840 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3841 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3842 3843 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3844 3845 Register SGPRIdxReg; 3846 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3847 UseGPRIdxMode, SGPRIdxReg); 3848 3849 MachineBasicBlock *LoopBB = InsPt->getParent(); 3850 3851 if (UseGPRIdxMode) { 3852 const MCInstrDesc &GPRIDXDesc = 3853 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3854 3855 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3856 .addReg(SrcReg) 3857 .addReg(SGPRIdxReg) 3858 .addImm(SubReg); 3859 } else { 3860 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3861 .addReg(SrcReg, 0, SubReg) 3862 .addReg(SrcReg, RegState::Implicit); 3863 } 3864 3865 MI.eraseFromParent(); 3866 3867 return LoopBB; 3868 } 3869 3870 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3871 MachineBasicBlock &MBB, 3872 const GCNSubtarget &ST) { 3873 const SIInstrInfo *TII = ST.getInstrInfo(); 3874 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3875 MachineFunction *MF = MBB.getParent(); 3876 MachineRegisterInfo &MRI = MF->getRegInfo(); 3877 3878 Register Dst = MI.getOperand(0).getReg(); 3879 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3880 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3881 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3882 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3883 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3884 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3885 3886 // This can be an immediate, but will be folded later. 3887 assert(Val->getReg()); 3888 3889 unsigned SubReg; 3890 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3891 SrcVec->getReg(), 3892 Offset); 3893 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3894 3895 if (Idx->getReg() == AMDGPU::NoRegister) { 3896 MachineBasicBlock::iterator I(&MI); 3897 const DebugLoc &DL = MI.getDebugLoc(); 3898 3899 assert(Offset == 0); 3900 3901 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3902 .add(*SrcVec) 3903 .add(*Val) 3904 .addImm(SubReg); 3905 3906 MI.eraseFromParent(); 3907 return &MBB; 3908 } 3909 3910 // Check for a SGPR index. 3911 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3912 MachineBasicBlock::iterator I(&MI); 3913 const DebugLoc &DL = MI.getDebugLoc(); 3914 3915 if (UseGPRIdxMode) { 3916 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3917 3918 const MCInstrDesc &GPRIDXDesc = 3919 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3920 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3921 .addReg(SrcVec->getReg()) 3922 .add(*Val) 3923 .addReg(Idx) 3924 .addImm(SubReg); 3925 } else { 3926 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3927 3928 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3929 TRI.getRegSizeInBits(*VecRC), 32, false); 3930 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3931 .addReg(SrcVec->getReg()) 3932 .add(*Val) 3933 .addImm(SubReg); 3934 } 3935 MI.eraseFromParent(); 3936 return &MBB; 3937 } 3938 3939 // Control flow needs to be inserted if indexing with a VGPR. 3940 if (Val->isReg()) 3941 MRI.clearKillFlags(Val->getReg()); 3942 3943 const DebugLoc &DL = MI.getDebugLoc(); 3944 3945 Register PhiReg = MRI.createVirtualRegister(VecRC); 3946 3947 Register SGPRIdxReg; 3948 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3949 UseGPRIdxMode, SGPRIdxReg); 3950 MachineBasicBlock *LoopBB = InsPt->getParent(); 3951 3952 if (UseGPRIdxMode) { 3953 const MCInstrDesc &GPRIDXDesc = 3954 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3955 3956 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3957 .addReg(PhiReg) 3958 .add(*Val) 3959 .addReg(SGPRIdxReg) 3960 .addImm(AMDGPU::sub0); 3961 } else { 3962 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3963 TRI.getRegSizeInBits(*VecRC), 32, false); 3964 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3965 .addReg(PhiReg) 3966 .add(*Val) 3967 .addImm(AMDGPU::sub0); 3968 } 3969 3970 MI.eraseFromParent(); 3971 return LoopBB; 3972 } 3973 3974 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3975 MachineInstr &MI, MachineBasicBlock *BB) const { 3976 3977 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3978 MachineFunction *MF = BB->getParent(); 3979 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3980 3981 switch (MI.getOpcode()) { 3982 case AMDGPU::S_UADDO_PSEUDO: 3983 case AMDGPU::S_USUBO_PSEUDO: { 3984 const DebugLoc &DL = MI.getDebugLoc(); 3985 MachineOperand &Dest0 = MI.getOperand(0); 3986 MachineOperand &Dest1 = MI.getOperand(1); 3987 MachineOperand &Src0 = MI.getOperand(2); 3988 MachineOperand &Src1 = MI.getOperand(3); 3989 3990 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3991 ? AMDGPU::S_ADD_I32 3992 : AMDGPU::S_SUB_I32; 3993 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3994 3995 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3996 .addImm(1) 3997 .addImm(0); 3998 3999 MI.eraseFromParent(); 4000 return BB; 4001 } 4002 case AMDGPU::S_ADD_U64_PSEUDO: 4003 case AMDGPU::S_SUB_U64_PSEUDO: { 4004 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4005 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4006 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4007 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 4008 const DebugLoc &DL = MI.getDebugLoc(); 4009 4010 MachineOperand &Dest = MI.getOperand(0); 4011 MachineOperand &Src0 = MI.getOperand(1); 4012 MachineOperand &Src1 = MI.getOperand(2); 4013 4014 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4015 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4016 4017 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 4018 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4019 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 4020 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4021 4022 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 4023 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 4024 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 4025 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 4026 4027 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 4028 4029 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 4030 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 4031 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 4032 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 4033 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4034 .addReg(DestSub0) 4035 .addImm(AMDGPU::sub0) 4036 .addReg(DestSub1) 4037 .addImm(AMDGPU::sub1); 4038 MI.eraseFromParent(); 4039 return BB; 4040 } 4041 case AMDGPU::V_ADD_U64_PSEUDO: 4042 case AMDGPU::V_SUB_U64_PSEUDO: { 4043 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4044 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4045 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4046 const DebugLoc &DL = MI.getDebugLoc(); 4047 4048 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 4049 4050 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4051 4052 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4053 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4054 4055 Register CarryReg = MRI.createVirtualRegister(CarryRC); 4056 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 4057 4058 MachineOperand &Dest = MI.getOperand(0); 4059 MachineOperand &Src0 = MI.getOperand(1); 4060 MachineOperand &Src1 = MI.getOperand(2); 4061 4062 const TargetRegisterClass *Src0RC = Src0.isReg() 4063 ? MRI.getRegClass(Src0.getReg()) 4064 : &AMDGPU::VReg_64RegClass; 4065 const TargetRegisterClass *Src1RC = Src1.isReg() 4066 ? MRI.getRegClass(Src1.getReg()) 4067 : &AMDGPU::VReg_64RegClass; 4068 4069 const TargetRegisterClass *Src0SubRC = 4070 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 4071 const TargetRegisterClass *Src1SubRC = 4072 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 4073 4074 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 4075 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 4076 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 4077 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 4078 4079 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 4080 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 4081 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 4082 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 4083 4084 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 4085 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 4086 .addReg(CarryReg, RegState::Define) 4087 .add(SrcReg0Sub0) 4088 .add(SrcReg1Sub0) 4089 .addImm(0); // clamp bit 4090 4091 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 4092 MachineInstr *HiHalf = 4093 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 4094 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 4095 .add(SrcReg0Sub1) 4096 .add(SrcReg1Sub1) 4097 .addReg(CarryReg, RegState::Kill) 4098 .addImm(0); // clamp bit 4099 4100 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 4101 .addReg(DestSub0) 4102 .addImm(AMDGPU::sub0) 4103 .addReg(DestSub1) 4104 .addImm(AMDGPU::sub1); 4105 TII->legalizeOperands(*LoHalf); 4106 TII->legalizeOperands(*HiHalf); 4107 MI.eraseFromParent(); 4108 return BB; 4109 } 4110 case AMDGPU::S_ADD_CO_PSEUDO: 4111 case AMDGPU::S_SUB_CO_PSEUDO: { 4112 // This pseudo has a chance to be selected 4113 // only from uniform add/subcarry node. All the VGPR operands 4114 // therefore assumed to be splat vectors. 4115 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4116 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4117 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4118 MachineBasicBlock::iterator MII = MI; 4119 const DebugLoc &DL = MI.getDebugLoc(); 4120 MachineOperand &Dest = MI.getOperand(0); 4121 MachineOperand &CarryDest = MI.getOperand(1); 4122 MachineOperand &Src0 = MI.getOperand(2); 4123 MachineOperand &Src1 = MI.getOperand(3); 4124 MachineOperand &Src2 = MI.getOperand(4); 4125 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4126 ? AMDGPU::S_ADDC_U32 4127 : AMDGPU::S_SUBB_U32; 4128 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4129 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4130 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4131 .addReg(Src0.getReg()); 4132 Src0.setReg(RegOp0); 4133 } 4134 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4135 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4136 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4137 .addReg(Src1.getReg()); 4138 Src1.setReg(RegOp1); 4139 } 4140 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4141 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4142 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4143 .addReg(Src2.getReg()); 4144 Src2.setReg(RegOp2); 4145 } 4146 4147 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4148 unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC); 4149 assert(WaveSize == 64 || WaveSize == 32); 4150 4151 if (WaveSize == 64) { 4152 if (ST.hasScalarCompareEq64()) { 4153 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4154 .addReg(Src2.getReg()) 4155 .addImm(0); 4156 } else { 4157 const TargetRegisterClass *SubRC = 4158 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4159 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4160 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4161 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4162 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4163 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4164 4165 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4166 .add(Src2Sub0) 4167 .add(Src2Sub1); 4168 4169 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4170 .addReg(Src2_32, RegState::Kill) 4171 .addImm(0); 4172 } 4173 } else { 4174 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4175 .addReg(Src2.getReg()) 4176 .addImm(0); 4177 } 4178 4179 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4180 4181 unsigned SelOpc = 4182 (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32; 4183 4184 BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg()) 4185 .addImm(-1) 4186 .addImm(0); 4187 4188 MI.eraseFromParent(); 4189 return BB; 4190 } 4191 case AMDGPU::SI_INIT_M0: { 4192 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4193 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4194 .add(MI.getOperand(0)); 4195 MI.eraseFromParent(); 4196 return BB; 4197 } 4198 case AMDGPU::GET_GROUPSTATICSIZE: { 4199 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4200 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4201 DebugLoc DL = MI.getDebugLoc(); 4202 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4203 .add(MI.getOperand(0)) 4204 .addImm(MFI->getLDSSize()); 4205 MI.eraseFromParent(); 4206 return BB; 4207 } 4208 case AMDGPU::SI_INDIRECT_SRC_V1: 4209 case AMDGPU::SI_INDIRECT_SRC_V2: 4210 case AMDGPU::SI_INDIRECT_SRC_V4: 4211 case AMDGPU::SI_INDIRECT_SRC_V8: 4212 case AMDGPU::SI_INDIRECT_SRC_V16: 4213 case AMDGPU::SI_INDIRECT_SRC_V32: 4214 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4215 case AMDGPU::SI_INDIRECT_DST_V1: 4216 case AMDGPU::SI_INDIRECT_DST_V2: 4217 case AMDGPU::SI_INDIRECT_DST_V4: 4218 case AMDGPU::SI_INDIRECT_DST_V8: 4219 case AMDGPU::SI_INDIRECT_DST_V16: 4220 case AMDGPU::SI_INDIRECT_DST_V32: 4221 return emitIndirectDst(MI, *BB, *getSubtarget()); 4222 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4223 case AMDGPU::SI_KILL_I1_PSEUDO: 4224 return splitKillBlock(MI, BB); 4225 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4226 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4227 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4228 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4229 4230 Register Dst = MI.getOperand(0).getReg(); 4231 Register Src0 = MI.getOperand(1).getReg(); 4232 Register Src1 = MI.getOperand(2).getReg(); 4233 const DebugLoc &DL = MI.getDebugLoc(); 4234 Register SrcCond = MI.getOperand(3).getReg(); 4235 4236 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4237 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4238 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4239 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4240 4241 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4242 .addReg(SrcCond); 4243 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4244 .addImm(0) 4245 .addReg(Src0, 0, AMDGPU::sub0) 4246 .addImm(0) 4247 .addReg(Src1, 0, AMDGPU::sub0) 4248 .addReg(SrcCondCopy); 4249 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4250 .addImm(0) 4251 .addReg(Src0, 0, AMDGPU::sub1) 4252 .addImm(0) 4253 .addReg(Src1, 0, AMDGPU::sub1) 4254 .addReg(SrcCondCopy); 4255 4256 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4257 .addReg(DstLo) 4258 .addImm(AMDGPU::sub0) 4259 .addReg(DstHi) 4260 .addImm(AMDGPU::sub1); 4261 MI.eraseFromParent(); 4262 return BB; 4263 } 4264 case AMDGPU::SI_BR_UNDEF: { 4265 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4266 const DebugLoc &DL = MI.getDebugLoc(); 4267 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4268 .add(MI.getOperand(0)); 4269 Br->getOperand(1).setIsUndef(true); // read undef SCC 4270 MI.eraseFromParent(); 4271 return BB; 4272 } 4273 case AMDGPU::ADJCALLSTACKUP: 4274 case AMDGPU::ADJCALLSTACKDOWN: { 4275 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4276 MachineInstrBuilder MIB(*MF, &MI); 4277 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4278 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4279 return BB; 4280 } 4281 case AMDGPU::SI_CALL_ISEL: { 4282 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4283 const DebugLoc &DL = MI.getDebugLoc(); 4284 4285 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4286 4287 MachineInstrBuilder MIB; 4288 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4289 4290 for (const MachineOperand &MO : MI.operands()) 4291 MIB.add(MO); 4292 4293 MIB.cloneMemRefs(MI); 4294 MI.eraseFromParent(); 4295 return BB; 4296 } 4297 case AMDGPU::V_ADD_CO_U32_e32: 4298 case AMDGPU::V_SUB_CO_U32_e32: 4299 case AMDGPU::V_SUBREV_CO_U32_e32: { 4300 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4301 const DebugLoc &DL = MI.getDebugLoc(); 4302 unsigned Opc = MI.getOpcode(); 4303 4304 bool NeedClampOperand = false; 4305 if (TII->pseudoToMCOpcode(Opc) == -1) { 4306 Opc = AMDGPU::getVOPe64(Opc); 4307 NeedClampOperand = true; 4308 } 4309 4310 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4311 if (TII->isVOP3(*I)) { 4312 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4313 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4314 I.addReg(TRI->getVCC(), RegState::Define); 4315 } 4316 I.add(MI.getOperand(1)) 4317 .add(MI.getOperand(2)); 4318 if (NeedClampOperand) 4319 I.addImm(0); // clamp bit for e64 encoding 4320 4321 TII->legalizeOperands(*I); 4322 4323 MI.eraseFromParent(); 4324 return BB; 4325 } 4326 case AMDGPU::V_ADDC_U32_e32: 4327 case AMDGPU::V_SUBB_U32_e32: 4328 case AMDGPU::V_SUBBREV_U32_e32: 4329 // These instructions have an implicit use of vcc which counts towards the 4330 // constant bus limit. 4331 TII->legalizeOperands(MI); 4332 return BB; 4333 case AMDGPU::DS_GWS_INIT: 4334 case AMDGPU::DS_GWS_SEMA_BR: 4335 case AMDGPU::DS_GWS_BARRIER: 4336 if (Subtarget->needsAlignedVGPRs()) { 4337 // Add implicit aligned super-reg to force alignment on the data operand. 4338 const DebugLoc &DL = MI.getDebugLoc(); 4339 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4340 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 4341 MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 4342 Register DataReg = Op->getReg(); 4343 bool IsAGPR = TRI->isAGPR(MRI, DataReg); 4344 Register Undef = MRI.createVirtualRegister( 4345 IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass); 4346 BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef); 4347 Register NewVR = 4348 MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass 4349 : &AMDGPU::VReg_64_Align2RegClass); 4350 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR) 4351 .addReg(DataReg, 0, Op->getSubReg()) 4352 .addImm(AMDGPU::sub0) 4353 .addReg(Undef) 4354 .addImm(AMDGPU::sub1); 4355 Op->setReg(NewVR); 4356 Op->setSubReg(AMDGPU::sub0); 4357 MI.addOperand(MachineOperand::CreateReg(NewVR, false, true)); 4358 } 4359 LLVM_FALLTHROUGH; 4360 case AMDGPU::DS_GWS_SEMA_V: 4361 case AMDGPU::DS_GWS_SEMA_P: 4362 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4363 // A s_waitcnt 0 is required to be the instruction immediately following. 4364 if (getSubtarget()->hasGWSAutoReplay()) { 4365 bundleInstWithWaitcnt(MI); 4366 return BB; 4367 } 4368 4369 return emitGWSMemViolTestLoop(MI, BB); 4370 case AMDGPU::S_SETREG_B32: { 4371 // Try to optimize cases that only set the denormal mode or rounding mode. 4372 // 4373 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4374 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4375 // instead. 4376 // 4377 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4378 // allow you to have a no side effect instruction in the output of a 4379 // sideeffecting pattern. 4380 unsigned ID, Offset, Width; 4381 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4382 if (ID != AMDGPU::Hwreg::ID_MODE) 4383 return BB; 4384 4385 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4386 const unsigned SetMask = WidthMask << Offset; 4387 4388 if (getSubtarget()->hasDenormModeInst()) { 4389 unsigned SetDenormOp = 0; 4390 unsigned SetRoundOp = 0; 4391 4392 // The dedicated instructions can only set the whole denorm or round mode 4393 // at once, not a subset of bits in either. 4394 if (SetMask == 4395 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4396 // If this fully sets both the round and denorm mode, emit the two 4397 // dedicated instructions for these. 4398 SetRoundOp = AMDGPU::S_ROUND_MODE; 4399 SetDenormOp = AMDGPU::S_DENORM_MODE; 4400 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4401 SetRoundOp = AMDGPU::S_ROUND_MODE; 4402 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4403 SetDenormOp = AMDGPU::S_DENORM_MODE; 4404 } 4405 4406 if (SetRoundOp || SetDenormOp) { 4407 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4408 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4409 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4410 unsigned ImmVal = Def->getOperand(1).getImm(); 4411 if (SetRoundOp) { 4412 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4413 .addImm(ImmVal & 0xf); 4414 4415 // If we also have the denorm mode, get just the denorm mode bits. 4416 ImmVal >>= 4; 4417 } 4418 4419 if (SetDenormOp) { 4420 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4421 .addImm(ImmVal & 0xf); 4422 } 4423 4424 MI.eraseFromParent(); 4425 return BB; 4426 } 4427 } 4428 } 4429 4430 // If only FP bits are touched, used the no side effects pseudo. 4431 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4432 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4433 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4434 4435 return BB; 4436 } 4437 default: 4438 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4439 } 4440 } 4441 4442 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4443 return isTypeLegal(VT.getScalarType()); 4444 } 4445 4446 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4447 // This currently forces unfolding various combinations of fsub into fma with 4448 // free fneg'd operands. As long as we have fast FMA (controlled by 4449 // isFMAFasterThanFMulAndFAdd), we should perform these. 4450 4451 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4452 // most of these combines appear to be cycle neutral but save on instruction 4453 // count / code size. 4454 return true; 4455 } 4456 4457 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; } 4458 4459 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4460 EVT VT) const { 4461 if (!VT.isVector()) { 4462 return MVT::i1; 4463 } 4464 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4465 } 4466 4467 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4468 // TODO: Should i16 be used always if legal? For now it would force VALU 4469 // shifts. 4470 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4471 } 4472 4473 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4474 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4475 ? Ty.changeElementSize(16) 4476 : Ty.changeElementSize(32); 4477 } 4478 4479 // Answering this is somewhat tricky and depends on the specific device which 4480 // have different rates for fma or all f64 operations. 4481 // 4482 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4483 // regardless of which device (although the number of cycles differs between 4484 // devices), so it is always profitable for f64. 4485 // 4486 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4487 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4488 // which we can always do even without fused FP ops since it returns the same 4489 // result as the separate operations and since it is always full 4490 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4491 // however does not support denormals, so we do report fma as faster if we have 4492 // a fast fma device and require denormals. 4493 // 4494 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4495 EVT VT) const { 4496 VT = VT.getScalarType(); 4497 4498 switch (VT.getSimpleVT().SimpleTy) { 4499 case MVT::f32: { 4500 // If mad is not available this depends only on if f32 fma is full rate. 4501 if (!Subtarget->hasMadMacF32Insts()) 4502 return Subtarget->hasFastFMAF32(); 4503 4504 // Otherwise f32 mad is always full rate and returns the same result as 4505 // the separate operations so should be preferred over fma. 4506 // However does not support denomals. 4507 if (hasFP32Denormals(MF)) 4508 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4509 4510 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4511 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4512 } 4513 case MVT::f64: 4514 return true; 4515 case MVT::f16: 4516 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4517 default: 4518 break; 4519 } 4520 4521 return false; 4522 } 4523 4524 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4525 LLT Ty) const { 4526 switch (Ty.getScalarSizeInBits()) { 4527 case 16: 4528 return isFMAFasterThanFMulAndFAdd(MF, MVT::f16); 4529 case 32: 4530 return isFMAFasterThanFMulAndFAdd(MF, MVT::f32); 4531 case 64: 4532 return isFMAFasterThanFMulAndFAdd(MF, MVT::f64); 4533 default: 4534 break; 4535 } 4536 4537 return false; 4538 } 4539 4540 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const { 4541 if (!Ty.isScalar()) 4542 return false; 4543 4544 if (Ty.getScalarSizeInBits() == 16) 4545 return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF()); 4546 if (Ty.getScalarSizeInBits() == 32) 4547 return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF()); 4548 4549 return false; 4550 } 4551 4552 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4553 const SDNode *N) const { 4554 // TODO: Check future ftz flag 4555 // v_mad_f32/v_mac_f32 do not support denormals. 4556 EVT VT = N->getValueType(0); 4557 if (VT == MVT::f32) 4558 return Subtarget->hasMadMacF32Insts() && 4559 !hasFP32Denormals(DAG.getMachineFunction()); 4560 if (VT == MVT::f16) { 4561 return Subtarget->hasMadF16() && 4562 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4563 } 4564 4565 return false; 4566 } 4567 4568 //===----------------------------------------------------------------------===// 4569 // Custom DAG Lowering Operations 4570 //===----------------------------------------------------------------------===// 4571 4572 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4573 // wider vector type is legal. 4574 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4575 SelectionDAG &DAG) const { 4576 unsigned Opc = Op.getOpcode(); 4577 EVT VT = Op.getValueType(); 4578 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4579 4580 SDValue Lo, Hi; 4581 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4582 4583 SDLoc SL(Op); 4584 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4585 Op->getFlags()); 4586 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4587 Op->getFlags()); 4588 4589 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4590 } 4591 4592 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4593 // wider vector type is legal. 4594 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4595 SelectionDAG &DAG) const { 4596 unsigned Opc = Op.getOpcode(); 4597 EVT VT = Op.getValueType(); 4598 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4599 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4600 4601 SDValue Lo0, Hi0; 4602 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4603 SDValue Lo1, Hi1; 4604 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4605 4606 SDLoc SL(Op); 4607 4608 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4609 Op->getFlags()); 4610 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4611 Op->getFlags()); 4612 4613 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4614 } 4615 4616 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4617 SelectionDAG &DAG) const { 4618 unsigned Opc = Op.getOpcode(); 4619 EVT VT = Op.getValueType(); 4620 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4621 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4622 4623 SDValue Lo0, Hi0; 4624 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4625 SDValue Lo1, Hi1; 4626 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4627 SDValue Lo2, Hi2; 4628 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4629 4630 SDLoc SL(Op); 4631 4632 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4633 Op->getFlags()); 4634 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4635 Op->getFlags()); 4636 4637 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4638 } 4639 4640 4641 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4642 switch (Op.getOpcode()) { 4643 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4644 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4645 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4646 case ISD::LOAD: { 4647 SDValue Result = LowerLOAD(Op, DAG); 4648 assert((!Result.getNode() || 4649 Result.getNode()->getNumValues() == 2) && 4650 "Load should return a value and a chain"); 4651 return Result; 4652 } 4653 4654 case ISD::FSIN: 4655 case ISD::FCOS: 4656 return LowerTrig(Op, DAG); 4657 case ISD::SELECT: return LowerSELECT(Op, DAG); 4658 case ISD::FDIV: return LowerFDIV(Op, DAG); 4659 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4660 case ISD::STORE: return LowerSTORE(Op, DAG); 4661 case ISD::GlobalAddress: { 4662 MachineFunction &MF = DAG.getMachineFunction(); 4663 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4664 return LowerGlobalAddress(MFI, Op, DAG); 4665 } 4666 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4667 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4668 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4669 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4670 case ISD::INSERT_SUBVECTOR: 4671 return lowerINSERT_SUBVECTOR(Op, DAG); 4672 case ISD::INSERT_VECTOR_ELT: 4673 return lowerINSERT_VECTOR_ELT(Op, DAG); 4674 case ISD::EXTRACT_VECTOR_ELT: 4675 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4676 case ISD::VECTOR_SHUFFLE: 4677 return lowerVECTOR_SHUFFLE(Op, DAG); 4678 case ISD::BUILD_VECTOR: 4679 return lowerBUILD_VECTOR(Op, DAG); 4680 case ISD::FP_ROUND: 4681 return lowerFP_ROUND(Op, DAG); 4682 case ISD::TRAP: 4683 return lowerTRAP(Op, DAG); 4684 case ISD::DEBUGTRAP: 4685 return lowerDEBUGTRAP(Op, DAG); 4686 case ISD::FABS: 4687 case ISD::FNEG: 4688 case ISD::FCANONICALIZE: 4689 case ISD::BSWAP: 4690 return splitUnaryVectorOp(Op, DAG); 4691 case ISD::FMINNUM: 4692 case ISD::FMAXNUM: 4693 return lowerFMINNUM_FMAXNUM(Op, DAG); 4694 case ISD::FMA: 4695 return splitTernaryVectorOp(Op, DAG); 4696 case ISD::FP_TO_SINT: 4697 case ISD::FP_TO_UINT: 4698 return LowerFP_TO_INT(Op, DAG); 4699 case ISD::SHL: 4700 case ISD::SRA: 4701 case ISD::SRL: 4702 case ISD::ADD: 4703 case ISD::SUB: 4704 case ISD::MUL: 4705 case ISD::SMIN: 4706 case ISD::SMAX: 4707 case ISD::UMIN: 4708 case ISD::UMAX: 4709 case ISD::FADD: 4710 case ISD::FMUL: 4711 case ISD::FMINNUM_IEEE: 4712 case ISD::FMAXNUM_IEEE: 4713 case ISD::UADDSAT: 4714 case ISD::USUBSAT: 4715 case ISD::SADDSAT: 4716 case ISD::SSUBSAT: 4717 return splitBinaryVectorOp(Op, DAG); 4718 case ISD::SMULO: 4719 case ISD::UMULO: 4720 return lowerXMULO(Op, DAG); 4721 case ISD::SMUL_LOHI: 4722 case ISD::UMUL_LOHI: 4723 return lowerXMUL_LOHI(Op, DAG); 4724 case ISD::DYNAMIC_STACKALLOC: 4725 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4726 } 4727 return SDValue(); 4728 } 4729 4730 // Used for D16: Casts the result of an instruction into the right vector, 4731 // packs values if loads return unpacked values. 4732 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4733 const SDLoc &DL, 4734 SelectionDAG &DAG, bool Unpacked) { 4735 if (!LoadVT.isVector()) 4736 return Result; 4737 4738 // Cast back to the original packed type or to a larger type that is a 4739 // multiple of 32 bit for D16. Widening the return type is a required for 4740 // legalization. 4741 EVT FittingLoadVT = LoadVT; 4742 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4743 FittingLoadVT = 4744 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4745 LoadVT.getVectorNumElements() + 1); 4746 } 4747 4748 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4749 // Truncate to v2i16/v4i16. 4750 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4751 4752 // Workaround legalizer not scalarizing truncate after vector op 4753 // legalization but not creating intermediate vector trunc. 4754 SmallVector<SDValue, 4> Elts; 4755 DAG.ExtractVectorElements(Result, Elts); 4756 for (SDValue &Elt : Elts) 4757 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4758 4759 // Pad illegal v1i16/v3fi6 to v4i16 4760 if ((LoadVT.getVectorNumElements() % 2) == 1) 4761 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4762 4763 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4764 4765 // Bitcast to original type (v2f16/v4f16). 4766 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4767 } 4768 4769 // Cast back to the original packed type. 4770 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4771 } 4772 4773 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4774 MemSDNode *M, 4775 SelectionDAG &DAG, 4776 ArrayRef<SDValue> Ops, 4777 bool IsIntrinsic) const { 4778 SDLoc DL(M); 4779 4780 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4781 EVT LoadVT = M->getValueType(0); 4782 4783 EVT EquivLoadVT = LoadVT; 4784 if (LoadVT.isVector()) { 4785 if (Unpacked) { 4786 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4787 LoadVT.getVectorNumElements()); 4788 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4789 // Widen v3f16 to legal type 4790 EquivLoadVT = 4791 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4792 LoadVT.getVectorNumElements() + 1); 4793 } 4794 } 4795 4796 // Change from v4f16/v2f16 to EquivLoadVT. 4797 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4798 4799 SDValue Load 4800 = DAG.getMemIntrinsicNode( 4801 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4802 VTList, Ops, M->getMemoryVT(), 4803 M->getMemOperand()); 4804 4805 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4806 4807 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4808 } 4809 4810 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4811 SelectionDAG &DAG, 4812 ArrayRef<SDValue> Ops) const { 4813 SDLoc DL(M); 4814 EVT LoadVT = M->getValueType(0); 4815 EVT EltType = LoadVT.getScalarType(); 4816 EVT IntVT = LoadVT.changeTypeToInteger(); 4817 4818 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4819 4820 unsigned Opc = 4821 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4822 4823 if (IsD16) { 4824 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4825 } 4826 4827 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4828 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4829 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4830 4831 if (isTypeLegal(LoadVT)) { 4832 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4833 M->getMemOperand(), DAG); 4834 } 4835 4836 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4837 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4838 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4839 M->getMemOperand(), DAG); 4840 return DAG.getMergeValues( 4841 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4842 DL); 4843 } 4844 4845 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4846 SDNode *N, SelectionDAG &DAG) { 4847 EVT VT = N->getValueType(0); 4848 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4849 unsigned CondCode = CD->getZExtValue(); 4850 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4851 return DAG.getUNDEF(VT); 4852 4853 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4854 4855 SDValue LHS = N->getOperand(1); 4856 SDValue RHS = N->getOperand(2); 4857 4858 SDLoc DL(N); 4859 4860 EVT CmpVT = LHS.getValueType(); 4861 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4862 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4863 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4864 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4865 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4866 } 4867 4868 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4869 4870 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4871 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4872 4873 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4874 DAG.getCondCode(CCOpcode)); 4875 if (VT.bitsEq(CCVT)) 4876 return SetCC; 4877 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4878 } 4879 4880 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4881 SDNode *N, SelectionDAG &DAG) { 4882 EVT VT = N->getValueType(0); 4883 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4884 4885 unsigned CondCode = CD->getZExtValue(); 4886 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4887 return DAG.getUNDEF(VT); 4888 4889 SDValue Src0 = N->getOperand(1); 4890 SDValue Src1 = N->getOperand(2); 4891 EVT CmpVT = Src0.getValueType(); 4892 SDLoc SL(N); 4893 4894 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4895 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4896 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4897 } 4898 4899 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4900 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4901 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4902 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4903 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4904 Src1, DAG.getCondCode(CCOpcode)); 4905 if (VT.bitsEq(CCVT)) 4906 return SetCC; 4907 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4908 } 4909 4910 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4911 SelectionDAG &DAG) { 4912 EVT VT = N->getValueType(0); 4913 SDValue Src = N->getOperand(1); 4914 SDLoc SL(N); 4915 4916 if (Src.getOpcode() == ISD::SETCC) { 4917 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4918 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4919 Src.getOperand(1), Src.getOperand(2)); 4920 } 4921 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4922 // (ballot 0) -> 0 4923 if (Arg->isZero()) 4924 return DAG.getConstant(0, SL, VT); 4925 4926 // (ballot 1) -> EXEC/EXEC_LO 4927 if (Arg->isOne()) { 4928 Register Exec; 4929 if (VT.getScalarSizeInBits() == 32) 4930 Exec = AMDGPU::EXEC_LO; 4931 else if (VT.getScalarSizeInBits() == 64) 4932 Exec = AMDGPU::EXEC; 4933 else 4934 return SDValue(); 4935 4936 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4937 } 4938 } 4939 4940 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4941 // ISD::SETNE) 4942 return DAG.getNode( 4943 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4944 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4945 } 4946 4947 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4948 SmallVectorImpl<SDValue> &Results, 4949 SelectionDAG &DAG) const { 4950 switch (N->getOpcode()) { 4951 case ISD::INSERT_VECTOR_ELT: { 4952 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4953 Results.push_back(Res); 4954 return; 4955 } 4956 case ISD::EXTRACT_VECTOR_ELT: { 4957 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4958 Results.push_back(Res); 4959 return; 4960 } 4961 case ISD::INTRINSIC_WO_CHAIN: { 4962 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4963 switch (IID) { 4964 case Intrinsic::amdgcn_cvt_pkrtz: { 4965 SDValue Src0 = N->getOperand(1); 4966 SDValue Src1 = N->getOperand(2); 4967 SDLoc SL(N); 4968 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4969 Src0, Src1); 4970 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4971 return; 4972 } 4973 case Intrinsic::amdgcn_cvt_pknorm_i16: 4974 case Intrinsic::amdgcn_cvt_pknorm_u16: 4975 case Intrinsic::amdgcn_cvt_pk_i16: 4976 case Intrinsic::amdgcn_cvt_pk_u16: { 4977 SDValue Src0 = N->getOperand(1); 4978 SDValue Src1 = N->getOperand(2); 4979 SDLoc SL(N); 4980 unsigned Opcode; 4981 4982 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4983 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4984 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4985 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4986 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4987 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4988 else 4989 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4990 4991 EVT VT = N->getValueType(0); 4992 if (isTypeLegal(VT)) 4993 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4994 else { 4995 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4996 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4997 } 4998 return; 4999 } 5000 } 5001 break; 5002 } 5003 case ISD::INTRINSIC_W_CHAIN: { 5004 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 5005 if (Res.getOpcode() == ISD::MERGE_VALUES) { 5006 // FIXME: Hacky 5007 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 5008 Results.push_back(Res.getOperand(I)); 5009 } 5010 } else { 5011 Results.push_back(Res); 5012 Results.push_back(Res.getValue(1)); 5013 } 5014 return; 5015 } 5016 5017 break; 5018 } 5019 case ISD::SELECT: { 5020 SDLoc SL(N); 5021 EVT VT = N->getValueType(0); 5022 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 5023 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 5024 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 5025 5026 EVT SelectVT = NewVT; 5027 if (NewVT.bitsLT(MVT::i32)) { 5028 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 5029 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 5030 SelectVT = MVT::i32; 5031 } 5032 5033 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 5034 N->getOperand(0), LHS, RHS); 5035 5036 if (NewVT != SelectVT) 5037 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 5038 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 5039 return; 5040 } 5041 case ISD::FNEG: { 5042 if (N->getValueType(0) != MVT::v2f16) 5043 break; 5044 5045 SDLoc SL(N); 5046 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5047 5048 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 5049 BC, 5050 DAG.getConstant(0x80008000, SL, MVT::i32)); 5051 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5052 return; 5053 } 5054 case ISD::FABS: { 5055 if (N->getValueType(0) != MVT::v2f16) 5056 break; 5057 5058 SDLoc SL(N); 5059 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 5060 5061 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 5062 BC, 5063 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 5064 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 5065 return; 5066 } 5067 default: 5068 break; 5069 } 5070 } 5071 5072 /// Helper function for LowerBRCOND 5073 static SDNode *findUser(SDValue Value, unsigned Opcode) { 5074 5075 SDNode *Parent = Value.getNode(); 5076 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 5077 I != E; ++I) { 5078 5079 if (I.getUse().get() != Value) 5080 continue; 5081 5082 if (I->getOpcode() == Opcode) 5083 return *I; 5084 } 5085 return nullptr; 5086 } 5087 5088 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 5089 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 5090 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 5091 case Intrinsic::amdgcn_if: 5092 return AMDGPUISD::IF; 5093 case Intrinsic::amdgcn_else: 5094 return AMDGPUISD::ELSE; 5095 case Intrinsic::amdgcn_loop: 5096 return AMDGPUISD::LOOP; 5097 case Intrinsic::amdgcn_end_cf: 5098 llvm_unreachable("should not occur"); 5099 default: 5100 return 0; 5101 } 5102 } 5103 5104 // break, if_break, else_break are all only used as inputs to loop, not 5105 // directly as branch conditions. 5106 return 0; 5107 } 5108 5109 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 5110 const Triple &TT = getTargetMachine().getTargetTriple(); 5111 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5112 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5113 AMDGPU::shouldEmitConstantsToTextSection(TT); 5114 } 5115 5116 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 5117 // FIXME: Either avoid relying on address space here or change the default 5118 // address space for functions to avoid the explicit check. 5119 return (GV->getValueType()->isFunctionTy() || 5120 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 5121 !shouldEmitFixup(GV) && 5122 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 5123 } 5124 5125 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 5126 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 5127 } 5128 5129 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 5130 if (!GV->hasExternalLinkage()) 5131 return true; 5132 5133 const auto OS = getTargetMachine().getTargetTriple().getOS(); 5134 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 5135 } 5136 5137 /// This transforms the control flow intrinsics to get the branch destination as 5138 /// last parameter, also switches branch target with BR if the need arise 5139 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 5140 SelectionDAG &DAG) const { 5141 SDLoc DL(BRCOND); 5142 5143 SDNode *Intr = BRCOND.getOperand(1).getNode(); 5144 SDValue Target = BRCOND.getOperand(2); 5145 SDNode *BR = nullptr; 5146 SDNode *SetCC = nullptr; 5147 5148 if (Intr->getOpcode() == ISD::SETCC) { 5149 // As long as we negate the condition everything is fine 5150 SetCC = Intr; 5151 Intr = SetCC->getOperand(0).getNode(); 5152 5153 } else { 5154 // Get the target from BR if we don't negate the condition 5155 BR = findUser(BRCOND, ISD::BR); 5156 assert(BR && "brcond missing unconditional branch user"); 5157 Target = BR->getOperand(1); 5158 } 5159 5160 unsigned CFNode = isCFIntrinsic(Intr); 5161 if (CFNode == 0) { 5162 // This is a uniform branch so we don't need to legalize. 5163 return BRCOND; 5164 } 5165 5166 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 5167 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 5168 5169 assert(!SetCC || 5170 (SetCC->getConstantOperandVal(1) == 1 && 5171 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 5172 ISD::SETNE)); 5173 5174 // operands of the new intrinsic call 5175 SmallVector<SDValue, 4> Ops; 5176 if (HaveChain) 5177 Ops.push_back(BRCOND.getOperand(0)); 5178 5179 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5180 Ops.push_back(Target); 5181 5182 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5183 5184 // build the new intrinsic call 5185 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5186 5187 if (!HaveChain) { 5188 SDValue Ops[] = { 5189 SDValue(Result, 0), 5190 BRCOND.getOperand(0) 5191 }; 5192 5193 Result = DAG.getMergeValues(Ops, DL).getNode(); 5194 } 5195 5196 if (BR) { 5197 // Give the branch instruction our target 5198 SDValue Ops[] = { 5199 BR->getOperand(0), 5200 BRCOND.getOperand(2) 5201 }; 5202 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5203 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5204 } 5205 5206 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5207 5208 // Copy the intrinsic results to registers 5209 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5210 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5211 if (!CopyToReg) 5212 continue; 5213 5214 Chain = DAG.getCopyToReg( 5215 Chain, DL, 5216 CopyToReg->getOperand(1), 5217 SDValue(Result, i - 1), 5218 SDValue()); 5219 5220 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5221 } 5222 5223 // Remove the old intrinsic from the chain 5224 DAG.ReplaceAllUsesOfValueWith( 5225 SDValue(Intr, Intr->getNumValues() - 1), 5226 Intr->getOperand(0)); 5227 5228 return Chain; 5229 } 5230 5231 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5232 SelectionDAG &DAG) const { 5233 MVT VT = Op.getSimpleValueType(); 5234 SDLoc DL(Op); 5235 // Checking the depth 5236 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5237 return DAG.getConstant(0, DL, VT); 5238 5239 MachineFunction &MF = DAG.getMachineFunction(); 5240 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5241 // Check for kernel and shader functions 5242 if (Info->isEntryFunction()) 5243 return DAG.getConstant(0, DL, VT); 5244 5245 MachineFrameInfo &MFI = MF.getFrameInfo(); 5246 // There is a call to @llvm.returnaddress in this function 5247 MFI.setReturnAddressIsTaken(true); 5248 5249 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5250 // Get the return address reg and mark it as an implicit live-in 5251 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5252 5253 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5254 } 5255 5256 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5257 SDValue Op, 5258 const SDLoc &DL, 5259 EVT VT) const { 5260 return Op.getValueType().bitsLE(VT) ? 5261 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5262 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5263 DAG.getTargetConstant(0, DL, MVT::i32)); 5264 } 5265 5266 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5267 assert(Op.getValueType() == MVT::f16 && 5268 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5269 5270 SDValue Src = Op.getOperand(0); 5271 EVT SrcVT = Src.getValueType(); 5272 if (SrcVT != MVT::f64) 5273 return Op; 5274 5275 SDLoc DL(Op); 5276 5277 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5278 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5279 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5280 } 5281 5282 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5283 SelectionDAG &DAG) const { 5284 EVT VT = Op.getValueType(); 5285 const MachineFunction &MF = DAG.getMachineFunction(); 5286 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5287 bool IsIEEEMode = Info->getMode().IEEE; 5288 5289 // FIXME: Assert during selection that this is only selected for 5290 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5291 // mode functions, but this happens to be OK since it's only done in cases 5292 // where there is known no sNaN. 5293 if (IsIEEEMode) 5294 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5295 5296 if (VT == MVT::v4f16) 5297 return splitBinaryVectorOp(Op, DAG); 5298 return Op; 5299 } 5300 5301 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5302 EVT VT = Op.getValueType(); 5303 SDLoc SL(Op); 5304 SDValue LHS = Op.getOperand(0); 5305 SDValue RHS = Op.getOperand(1); 5306 bool isSigned = Op.getOpcode() == ISD::SMULO; 5307 5308 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5309 const APInt &C = RHSC->getAPIntValue(); 5310 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5311 if (C.isPowerOf2()) { 5312 // smulo(x, signed_min) is same as umulo(x, signed_min). 5313 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5314 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5315 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5316 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5317 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5318 SL, VT, Result, ShiftAmt), 5319 LHS, ISD::SETNE); 5320 return DAG.getMergeValues({ Result, Overflow }, SL); 5321 } 5322 } 5323 5324 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5325 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5326 SL, VT, LHS, RHS); 5327 5328 SDValue Sign = isSigned 5329 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5330 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5331 : DAG.getConstant(0, SL, VT); 5332 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5333 5334 return DAG.getMergeValues({ Result, Overflow }, SL); 5335 } 5336 5337 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const { 5338 if (Op->isDivergent()) { 5339 // Select to V_MAD_[IU]64_[IU]32. 5340 return Op; 5341 } 5342 if (Subtarget->hasSMulHi()) { 5343 // Expand to S_MUL_I32 + S_MUL_HI_[IU]32. 5344 return SDValue(); 5345 } 5346 // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to 5347 // calculate the high part, so we might as well do the whole thing with 5348 // V_MAD_[IU]64_[IU]32. 5349 return Op; 5350 } 5351 5352 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5353 if (!Subtarget->isTrapHandlerEnabled() || 5354 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) 5355 return lowerTrapEndpgm(Op, DAG); 5356 5357 if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) { 5358 switch (*HsaAbiVer) { 5359 case ELF::ELFABIVERSION_AMDGPU_HSA_V2: 5360 case ELF::ELFABIVERSION_AMDGPU_HSA_V3: 5361 return lowerTrapHsaQueuePtr(Op, DAG); 5362 case ELF::ELFABIVERSION_AMDGPU_HSA_V4: 5363 return Subtarget->supportsGetDoorbellID() ? 5364 lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG); 5365 } 5366 } 5367 5368 llvm_unreachable("Unknown trap handler"); 5369 } 5370 5371 SDValue SITargetLowering::lowerTrapEndpgm( 5372 SDValue Op, SelectionDAG &DAG) const { 5373 SDLoc SL(Op); 5374 SDValue Chain = Op.getOperand(0); 5375 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5376 } 5377 5378 SDValue SITargetLowering::lowerTrapHsaQueuePtr( 5379 SDValue Op, SelectionDAG &DAG) const { 5380 SDLoc SL(Op); 5381 SDValue Chain = Op.getOperand(0); 5382 5383 MachineFunction &MF = DAG.getMachineFunction(); 5384 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5385 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5386 5387 SDValue QueuePtr; 5388 if (UserSGPR == AMDGPU::NoRegister) { 5389 // We probably are in a function incorrectly marked with 5390 // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap, 5391 // so just use a null pointer. 5392 QueuePtr = DAG.getConstant(0, SL, MVT::i64); 5393 } else { 5394 QueuePtr = CreateLiveInRegister( 5395 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5396 } 5397 5398 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5399 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5400 QueuePtr, SDValue()); 5401 5402 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5403 SDValue Ops[] = { 5404 ToReg, 5405 DAG.getTargetConstant(TrapID, SL, MVT::i16), 5406 SGPR01, 5407 ToReg.getValue(1) 5408 }; 5409 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5410 } 5411 5412 SDValue SITargetLowering::lowerTrapHsa( 5413 SDValue Op, SelectionDAG &DAG) const { 5414 SDLoc SL(Op); 5415 SDValue Chain = Op.getOperand(0); 5416 5417 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap); 5418 SDValue Ops[] = { 5419 Chain, 5420 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5421 }; 5422 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5423 } 5424 5425 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5426 SDLoc SL(Op); 5427 SDValue Chain = Op.getOperand(0); 5428 MachineFunction &MF = DAG.getMachineFunction(); 5429 5430 if (!Subtarget->isTrapHandlerEnabled() || 5431 Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) { 5432 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5433 "debugtrap handler not supported", 5434 Op.getDebugLoc(), 5435 DS_Warning); 5436 LLVMContext &Ctx = MF.getFunction().getContext(); 5437 Ctx.diagnose(NoTrap); 5438 return Chain; 5439 } 5440 5441 uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap); 5442 SDValue Ops[] = { 5443 Chain, 5444 DAG.getTargetConstant(TrapID, SL, MVT::i16) 5445 }; 5446 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5447 } 5448 5449 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5450 SelectionDAG &DAG) const { 5451 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5452 if (Subtarget->hasApertureRegs()) { 5453 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5454 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5455 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5456 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5457 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5458 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5459 unsigned Encoding = 5460 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5461 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5462 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5463 5464 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5465 SDValue ApertureReg = SDValue( 5466 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5467 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5468 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5469 } 5470 5471 MachineFunction &MF = DAG.getMachineFunction(); 5472 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5473 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5474 if (UserSGPR == AMDGPU::NoRegister) { 5475 // We probably are in a function incorrectly marked with 5476 // amdgpu-no-queue-ptr. This is undefined. 5477 return DAG.getUNDEF(MVT::i32); 5478 } 5479 5480 SDValue QueuePtr = CreateLiveInRegister( 5481 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5482 5483 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5484 // private_segment_aperture_base_hi. 5485 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5486 5487 SDValue Ptr = 5488 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5489 5490 // TODO: Use custom target PseudoSourceValue. 5491 // TODO: We should use the value from the IR intrinsic call, but it might not 5492 // be available and how do we get it? 5493 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5494 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5495 commonAlignment(Align(64), StructOffset), 5496 MachineMemOperand::MODereferenceable | 5497 MachineMemOperand::MOInvariant); 5498 } 5499 5500 /// Return true if the value is a known valid address, such that a null check is 5501 /// not necessary. 5502 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG, 5503 const AMDGPUTargetMachine &TM, unsigned AddrSpace) { 5504 if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) || 5505 isa<BasicBlockSDNode>(Val)) 5506 return true; 5507 5508 if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val)) 5509 return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace); 5510 5511 // TODO: Search through arithmetic, handle arguments and loads 5512 // marked nonnull. 5513 return false; 5514 } 5515 5516 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5517 SelectionDAG &DAG) const { 5518 SDLoc SL(Op); 5519 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5520 5521 SDValue Src = ASC->getOperand(0); 5522 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5523 unsigned SrcAS = ASC->getSrcAddressSpace(); 5524 5525 const AMDGPUTargetMachine &TM = 5526 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5527 5528 // flat -> local/private 5529 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) { 5530 unsigned DestAS = ASC->getDestAddressSpace(); 5531 5532 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5533 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5534 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5535 5536 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5537 return Ptr; 5538 5539 unsigned NullVal = TM.getNullPointerValue(DestAS); 5540 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5541 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5542 5543 return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr, 5544 SegmentNullPtr); 5545 } 5546 } 5547 5548 // local/private -> flat 5549 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5550 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5551 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5552 5553 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5554 SDValue CvtPtr = 5555 DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5556 CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr); 5557 5558 if (isKnownNonNull(Src, DAG, TM, SrcAS)) 5559 return CvtPtr; 5560 5561 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5562 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5563 5564 SDValue NonNull 5565 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5566 5567 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr, 5568 FlatNullPtr); 5569 } 5570 } 5571 5572 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5573 Src.getValueType() == MVT::i64) 5574 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5575 5576 // global <-> flat are no-ops and never emitted. 5577 5578 const MachineFunction &MF = DAG.getMachineFunction(); 5579 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5580 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5581 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5582 5583 return DAG.getUNDEF(ASC->getValueType(0)); 5584 } 5585 5586 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5587 // the small vector and inserting them into the big vector. That is better than 5588 // the default expansion of doing it via a stack slot. Even though the use of 5589 // the stack slot would be optimized away afterwards, the stack slot itself 5590 // remains. 5591 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5592 SelectionDAG &DAG) const { 5593 SDValue Vec = Op.getOperand(0); 5594 SDValue Ins = Op.getOperand(1); 5595 SDValue Idx = Op.getOperand(2); 5596 EVT VecVT = Vec.getValueType(); 5597 EVT InsVT = Ins.getValueType(); 5598 EVT EltVT = VecVT.getVectorElementType(); 5599 unsigned InsNumElts = InsVT.getVectorNumElements(); 5600 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5601 SDLoc SL(Op); 5602 5603 for (unsigned I = 0; I != InsNumElts; ++I) { 5604 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5605 DAG.getConstant(I, SL, MVT::i32)); 5606 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5607 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5608 } 5609 return Vec; 5610 } 5611 5612 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5613 SelectionDAG &DAG) const { 5614 SDValue Vec = Op.getOperand(0); 5615 SDValue InsVal = Op.getOperand(1); 5616 SDValue Idx = Op.getOperand(2); 5617 EVT VecVT = Vec.getValueType(); 5618 EVT EltVT = VecVT.getVectorElementType(); 5619 unsigned VecSize = VecVT.getSizeInBits(); 5620 unsigned EltSize = EltVT.getSizeInBits(); 5621 5622 5623 assert(VecSize <= 64); 5624 5625 unsigned NumElts = VecVT.getVectorNumElements(); 5626 SDLoc SL(Op); 5627 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5628 5629 if (NumElts == 4 && EltSize == 16 && KIdx) { 5630 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5631 5632 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5633 DAG.getConstant(0, SL, MVT::i32)); 5634 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5635 DAG.getConstant(1, SL, MVT::i32)); 5636 5637 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5638 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5639 5640 unsigned Idx = KIdx->getZExtValue(); 5641 bool InsertLo = Idx < 2; 5642 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5643 InsertLo ? LoVec : HiVec, 5644 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5645 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5646 5647 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5648 5649 SDValue Concat = InsertLo ? 5650 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5651 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5652 5653 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5654 } 5655 5656 if (isa<ConstantSDNode>(Idx)) 5657 return SDValue(); 5658 5659 MVT IntVT = MVT::getIntegerVT(VecSize); 5660 5661 // Avoid stack access for dynamic indexing. 5662 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5663 5664 // Create a congruent vector with the target value in each element so that 5665 // the required element can be masked and ORed into the target vector. 5666 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5667 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5668 5669 assert(isPowerOf2_32(EltSize)); 5670 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5671 5672 // Convert vector index to bit-index. 5673 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5674 5675 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5676 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5677 DAG.getConstant(0xffff, SL, IntVT), 5678 ScaledIdx); 5679 5680 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5681 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5682 DAG.getNOT(SL, BFM, IntVT), BCVec); 5683 5684 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5685 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5686 } 5687 5688 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5689 SelectionDAG &DAG) const { 5690 SDLoc SL(Op); 5691 5692 EVT ResultVT = Op.getValueType(); 5693 SDValue Vec = Op.getOperand(0); 5694 SDValue Idx = Op.getOperand(1); 5695 EVT VecVT = Vec.getValueType(); 5696 unsigned VecSize = VecVT.getSizeInBits(); 5697 EVT EltVT = VecVT.getVectorElementType(); 5698 assert(VecSize <= 64); 5699 5700 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5701 5702 // Make sure we do any optimizations that will make it easier to fold 5703 // source modifiers before obscuring it with bit operations. 5704 5705 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5706 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5707 return Combined; 5708 5709 unsigned EltSize = EltVT.getSizeInBits(); 5710 assert(isPowerOf2_32(EltSize)); 5711 5712 MVT IntVT = MVT::getIntegerVT(VecSize); 5713 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5714 5715 // Convert vector index to bit-index (* EltSize) 5716 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5717 5718 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5719 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5720 5721 if (ResultVT == MVT::f16) { 5722 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5723 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5724 } 5725 5726 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5727 } 5728 5729 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5730 assert(Elt % 2 == 0); 5731 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5732 } 5733 5734 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5735 SelectionDAG &DAG) const { 5736 SDLoc SL(Op); 5737 EVT ResultVT = Op.getValueType(); 5738 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5739 5740 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5741 EVT EltVT = PackVT.getVectorElementType(); 5742 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5743 5744 // vector_shuffle <0,1,6,7> lhs, rhs 5745 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5746 // 5747 // vector_shuffle <6,7,2,3> lhs, rhs 5748 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5749 // 5750 // vector_shuffle <6,7,0,1> lhs, rhs 5751 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5752 5753 // Avoid scalarizing when both halves are reading from consecutive elements. 5754 SmallVector<SDValue, 4> Pieces; 5755 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5756 if (elementPairIsContiguous(SVN->getMask(), I)) { 5757 const int Idx = SVN->getMaskElt(I); 5758 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5759 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5760 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5761 PackVT, SVN->getOperand(VecIdx), 5762 DAG.getConstant(EltIdx, SL, MVT::i32)); 5763 Pieces.push_back(SubVec); 5764 } else { 5765 const int Idx0 = SVN->getMaskElt(I); 5766 const int Idx1 = SVN->getMaskElt(I + 1); 5767 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5768 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5769 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5770 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5771 5772 SDValue Vec0 = SVN->getOperand(VecIdx0); 5773 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5774 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5775 5776 SDValue Vec1 = SVN->getOperand(VecIdx1); 5777 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5778 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5779 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5780 } 5781 } 5782 5783 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5784 } 5785 5786 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5787 SelectionDAG &DAG) const { 5788 SDLoc SL(Op); 5789 EVT VT = Op.getValueType(); 5790 5791 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5792 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5793 5794 // Turn into pair of packed build_vectors. 5795 // TODO: Special case for constants that can be materialized with s_mov_b64. 5796 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5797 { Op.getOperand(0), Op.getOperand(1) }); 5798 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5799 { Op.getOperand(2), Op.getOperand(3) }); 5800 5801 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5802 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5803 5804 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5805 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5806 } 5807 5808 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5809 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5810 5811 SDValue Lo = Op.getOperand(0); 5812 SDValue Hi = Op.getOperand(1); 5813 5814 // Avoid adding defined bits with the zero_extend. 5815 if (Hi.isUndef()) { 5816 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5817 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5818 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5819 } 5820 5821 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5822 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5823 5824 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5825 DAG.getConstant(16, SL, MVT::i32)); 5826 if (Lo.isUndef()) 5827 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5828 5829 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5830 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5831 5832 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5833 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5834 } 5835 5836 bool 5837 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5838 // We can fold offsets for anything that doesn't require a GOT relocation. 5839 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5840 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5841 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5842 !shouldEmitGOTReloc(GA->getGlobal()); 5843 } 5844 5845 static SDValue 5846 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5847 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5848 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5849 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5850 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5851 // lowered to the following code sequence: 5852 // 5853 // For constant address space: 5854 // s_getpc_b64 s[0:1] 5855 // s_add_u32 s0, s0, $symbol 5856 // s_addc_u32 s1, s1, 0 5857 // 5858 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5859 // a fixup or relocation is emitted to replace $symbol with a literal 5860 // constant, which is a pc-relative offset from the encoding of the $symbol 5861 // operand to the global variable. 5862 // 5863 // For global address space: 5864 // s_getpc_b64 s[0:1] 5865 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5866 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5867 // 5868 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5869 // fixups or relocations are emitted to replace $symbol@*@lo and 5870 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5871 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5872 // operand to the global variable. 5873 // 5874 // What we want here is an offset from the value returned by s_getpc 5875 // (which is the address of the s_add_u32 instruction) to the global 5876 // variable, but since the encoding of $symbol starts 4 bytes after the start 5877 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5878 // small. This requires us to add 4 to the global variable offset in order to 5879 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5880 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5881 // instruction. 5882 SDValue PtrLo = 5883 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5884 SDValue PtrHi; 5885 if (GAFlags == SIInstrInfo::MO_NONE) { 5886 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5887 } else { 5888 PtrHi = 5889 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5890 } 5891 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5892 } 5893 5894 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5895 SDValue Op, 5896 SelectionDAG &DAG) const { 5897 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5898 SDLoc DL(GSD); 5899 EVT PtrVT = Op.getValueType(); 5900 5901 const GlobalValue *GV = GSD->getGlobal(); 5902 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5903 shouldUseLDSConstAddress(GV)) || 5904 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5905 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5906 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5907 GV->hasExternalLinkage()) { 5908 Type *Ty = GV->getValueType(); 5909 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5910 // zero-sized type in other languages to declare the dynamic shared 5911 // memory which size is not known at the compile time. They will be 5912 // allocated by the runtime and placed directly after the static 5913 // allocated ones. They all share the same offset. 5914 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5915 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5916 // Adjust alignment for that dynamic shared memory array. 5917 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5918 return SDValue( 5919 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5920 } 5921 } 5922 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5923 } 5924 5925 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5926 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5927 SIInstrInfo::MO_ABS32_LO); 5928 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5929 } 5930 5931 if (shouldEmitFixup(GV)) 5932 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5933 else if (shouldEmitPCReloc(GV)) 5934 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5935 SIInstrInfo::MO_REL32); 5936 5937 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5938 SIInstrInfo::MO_GOTPCREL32); 5939 5940 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5941 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5942 const DataLayout &DataLayout = DAG.getDataLayout(); 5943 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5944 MachinePointerInfo PtrInfo 5945 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5946 5947 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5948 MachineMemOperand::MODereferenceable | 5949 MachineMemOperand::MOInvariant); 5950 } 5951 5952 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5953 const SDLoc &DL, SDValue V) const { 5954 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5955 // the destination register. 5956 // 5957 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5958 // so we will end up with redundant moves to m0. 5959 // 5960 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5961 5962 // A Null SDValue creates a glue result. 5963 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5964 V, Chain); 5965 return SDValue(M0, 0); 5966 } 5967 5968 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5969 SDValue Op, 5970 MVT VT, 5971 unsigned Offset) const { 5972 SDLoc SL(Op); 5973 SDValue Param = lowerKernargMemParameter( 5974 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5975 // The local size values will have the hi 16-bits as zero. 5976 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5977 DAG.getValueType(VT)); 5978 } 5979 5980 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5981 EVT VT) { 5982 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5983 "non-hsa intrinsic with hsa target", 5984 DL.getDebugLoc()); 5985 DAG.getContext()->diagnose(BadIntrin); 5986 return DAG.getUNDEF(VT); 5987 } 5988 5989 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5990 EVT VT) { 5991 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5992 "intrinsic not supported on subtarget", 5993 DL.getDebugLoc()); 5994 DAG.getContext()->diagnose(BadIntrin); 5995 return DAG.getUNDEF(VT); 5996 } 5997 5998 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5999 ArrayRef<SDValue> Elts) { 6000 assert(!Elts.empty()); 6001 MVT Type; 6002 unsigned NumElts = Elts.size(); 6003 6004 if (NumElts <= 8) { 6005 Type = MVT::getVectorVT(MVT::f32, NumElts); 6006 } else { 6007 assert(Elts.size() <= 16); 6008 Type = MVT::v16f32; 6009 NumElts = 16; 6010 } 6011 6012 SmallVector<SDValue, 16> VecElts(NumElts); 6013 for (unsigned i = 0; i < Elts.size(); ++i) { 6014 SDValue Elt = Elts[i]; 6015 if (Elt.getValueType() != MVT::f32) 6016 Elt = DAG.getBitcast(MVT::f32, Elt); 6017 VecElts[i] = Elt; 6018 } 6019 for (unsigned i = Elts.size(); i < NumElts; ++i) 6020 VecElts[i] = DAG.getUNDEF(MVT::f32); 6021 6022 if (NumElts == 1) 6023 return VecElts[0]; 6024 return DAG.getBuildVector(Type, DL, VecElts); 6025 } 6026 6027 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 6028 SDValue Src, int ExtraElts) { 6029 EVT SrcVT = Src.getValueType(); 6030 6031 SmallVector<SDValue, 8> Elts; 6032 6033 if (SrcVT.isVector()) 6034 DAG.ExtractVectorElements(Src, Elts); 6035 else 6036 Elts.push_back(Src); 6037 6038 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 6039 while (ExtraElts--) 6040 Elts.push_back(Undef); 6041 6042 return DAG.getBuildVector(CastVT, DL, Elts); 6043 } 6044 6045 // Re-construct the required return value for a image load intrinsic. 6046 // This is more complicated due to the optional use TexFailCtrl which means the required 6047 // return type is an aggregate 6048 static SDValue constructRetValue(SelectionDAG &DAG, 6049 MachineSDNode *Result, 6050 ArrayRef<EVT> ResultTypes, 6051 bool IsTexFail, bool Unpacked, bool IsD16, 6052 int DMaskPop, int NumVDataDwords, 6053 const SDLoc &DL) { 6054 // Determine the required return type. This is the same regardless of IsTexFail flag 6055 EVT ReqRetVT = ResultTypes[0]; 6056 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 6057 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6058 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 6059 6060 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 6061 DMaskPop : (DMaskPop + 1) / 2; 6062 6063 MVT DataDwordVT = NumDataDwords == 1 ? 6064 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 6065 6066 MVT MaskPopVT = MaskPopDwords == 1 ? 6067 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 6068 6069 SDValue Data(Result, 0); 6070 SDValue TexFail; 6071 6072 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 6073 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 6074 if (MaskPopVT.isVector()) { 6075 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 6076 SDValue(Result, 0), ZeroIdx); 6077 } else { 6078 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 6079 SDValue(Result, 0), ZeroIdx); 6080 } 6081 } 6082 6083 if (DataDwordVT.isVector()) 6084 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 6085 NumDataDwords - MaskPopDwords); 6086 6087 if (IsD16) 6088 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 6089 6090 EVT LegalReqRetVT = ReqRetVT; 6091 if (!ReqRetVT.isVector()) { 6092 if (!Data.getValueType().isInteger()) 6093 Data = DAG.getNode(ISD::BITCAST, DL, 6094 Data.getValueType().changeTypeToInteger(), Data); 6095 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 6096 } else { 6097 // We need to widen the return vector to a legal type 6098 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 6099 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 6100 LegalReqRetVT = 6101 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 6102 ReqRetVT.getVectorNumElements() + 1); 6103 } 6104 } 6105 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 6106 6107 if (IsTexFail) { 6108 TexFail = 6109 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 6110 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 6111 6112 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 6113 } 6114 6115 if (Result->getNumValues() == 1) 6116 return Data; 6117 6118 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 6119 } 6120 6121 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 6122 SDValue *LWE, bool &IsTexFail) { 6123 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 6124 6125 uint64_t Value = TexFailCtrlConst->getZExtValue(); 6126 if (Value) { 6127 IsTexFail = true; 6128 } 6129 6130 SDLoc DL(TexFailCtrlConst); 6131 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 6132 Value &= ~(uint64_t)0x1; 6133 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 6134 Value &= ~(uint64_t)0x2; 6135 6136 return Value == 0; 6137 } 6138 6139 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op, 6140 MVT PackVectorVT, 6141 SmallVectorImpl<SDValue> &PackedAddrs, 6142 unsigned DimIdx, unsigned EndIdx, 6143 unsigned NumGradients) { 6144 SDLoc DL(Op); 6145 for (unsigned I = DimIdx; I < EndIdx; I++) { 6146 SDValue Addr = Op.getOperand(I); 6147 6148 // Gradients are packed with undef for each coordinate. 6149 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 6150 // 1D: undef,dx/dh; undef,dx/dv 6151 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 6152 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 6153 if (((I + 1) >= EndIdx) || 6154 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 6155 I == DimIdx + NumGradients - 1))) { 6156 if (Addr.getValueType() != MVT::i16) 6157 Addr = DAG.getBitcast(MVT::i16, Addr); 6158 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 6159 } else { 6160 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 6161 I++; 6162 } 6163 Addr = DAG.getBitcast(MVT::f32, Addr); 6164 PackedAddrs.push_back(Addr); 6165 } 6166 } 6167 6168 SDValue SITargetLowering::lowerImage(SDValue Op, 6169 const AMDGPU::ImageDimIntrinsicInfo *Intr, 6170 SelectionDAG &DAG, bool WithChain) const { 6171 SDLoc DL(Op); 6172 MachineFunction &MF = DAG.getMachineFunction(); 6173 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 6174 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 6175 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 6176 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 6177 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 6178 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 6179 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 6180 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 6181 unsigned IntrOpcode = Intr->BaseOpcode; 6182 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 6183 6184 SmallVector<EVT, 3> ResultTypes(Op->values()); 6185 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 6186 bool IsD16 = false; 6187 bool IsG16 = false; 6188 bool IsA16 = false; 6189 SDValue VData; 6190 int NumVDataDwords; 6191 bool AdjustRetType = false; 6192 6193 // Offset of intrinsic arguments 6194 const unsigned ArgOffset = WithChain ? 2 : 1; 6195 6196 unsigned DMask; 6197 unsigned DMaskLanes = 0; 6198 6199 if (BaseOpcode->Atomic) { 6200 VData = Op.getOperand(2); 6201 6202 bool Is64Bit = VData.getValueType() == MVT::i64; 6203 if (BaseOpcode->AtomicX2) { 6204 SDValue VData2 = Op.getOperand(3); 6205 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 6206 {VData, VData2}); 6207 if (Is64Bit) 6208 VData = DAG.getBitcast(MVT::v4i32, VData); 6209 6210 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 6211 DMask = Is64Bit ? 0xf : 0x3; 6212 NumVDataDwords = Is64Bit ? 4 : 2; 6213 } else { 6214 DMask = Is64Bit ? 0x3 : 0x1; 6215 NumVDataDwords = Is64Bit ? 2 : 1; 6216 } 6217 } else { 6218 auto *DMaskConst = 6219 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 6220 DMask = DMaskConst->getZExtValue(); 6221 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 6222 6223 if (BaseOpcode->Store) { 6224 VData = Op.getOperand(2); 6225 6226 MVT StoreVT = VData.getSimpleValueType(); 6227 if (StoreVT.getScalarType() == MVT::f16) { 6228 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6229 return Op; // D16 is unsupported for this instruction 6230 6231 IsD16 = true; 6232 VData = handleD16VData(VData, DAG, true); 6233 } 6234 6235 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 6236 } else { 6237 // Work out the num dwords based on the dmask popcount and underlying type 6238 // and whether packing is supported. 6239 MVT LoadVT = ResultTypes[0].getSimpleVT(); 6240 if (LoadVT.getScalarType() == MVT::f16) { 6241 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 6242 return Op; // D16 is unsupported for this instruction 6243 6244 IsD16 = true; 6245 } 6246 6247 // Confirm that the return type is large enough for the dmask specified 6248 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 6249 (!LoadVT.isVector() && DMaskLanes > 1)) 6250 return Op; 6251 6252 // The sq block of gfx8 and gfx9 do not estimate register use correctly 6253 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 6254 // instructions. 6255 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 6256 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 6257 NumVDataDwords = (DMaskLanes + 1) / 2; 6258 else 6259 NumVDataDwords = DMaskLanes; 6260 6261 AdjustRetType = true; 6262 } 6263 } 6264 6265 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6266 SmallVector<SDValue, 4> VAddrs; 6267 6268 // Optimize _L to _LZ when _L is zero 6269 if (LZMappingInfo) { 6270 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6271 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6272 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6273 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6274 VAddrEnd--; // remove 'lod' 6275 } 6276 } 6277 } 6278 6279 // Optimize _mip away, when 'lod' is zero 6280 if (MIPMappingInfo) { 6281 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6282 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6283 if (ConstantLod->isZero()) { 6284 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6285 VAddrEnd--; // remove 'mip' 6286 } 6287 } 6288 } 6289 6290 // Check for 16 bit addresses or derivatives and pack if true. 6291 MVT VAddrVT = 6292 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6293 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6294 MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6295 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6296 6297 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6298 VAddrScalarVT = VAddrVT.getScalarType(); 6299 MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6300 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6301 6302 // Push back extra arguments. 6303 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) { 6304 if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) { 6305 // Special handling of bias when A16 is on. Bias is of type half but 6306 // occupies full 32-bit. 6307 SDValue bias = DAG.getBuildVector( MVT::v2f16, DL, {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)}); 6308 VAddrs.push_back(bias); 6309 } else 6310 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6311 } 6312 6313 if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) { 6314 // 16 bit gradients are supported, but are tied to the A16 control 6315 // so both gradients and addresses must be 16 bit 6316 LLVM_DEBUG( 6317 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6318 "require 16 bit args for both gradients and addresses"); 6319 return Op; 6320 } 6321 6322 if (IsA16) { 6323 if (!ST->hasA16()) { 6324 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6325 "support 16 bit addresses\n"); 6326 return Op; 6327 } 6328 } 6329 6330 // We've dealt with incorrect input so we know that if IsA16, IsG16 6331 // are set then we have to compress/pack operands (either address, 6332 // gradient or both) 6333 // In the case where a16 and gradients are tied (no G16 support) then we 6334 // have already verified that both IsA16 and IsG16 are true 6335 if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) { 6336 // Activate g16 6337 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6338 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6339 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6340 } 6341 6342 // Add gradients (packed or unpacked) 6343 if (IsG16) { 6344 // Pack the gradients 6345 // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6346 packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs, 6347 ArgOffset + Intr->GradientStart, 6348 ArgOffset + Intr->CoordStart, Intr->NumGradients); 6349 } else { 6350 for (unsigned I = ArgOffset + Intr->GradientStart; 6351 I < ArgOffset + Intr->CoordStart; I++) 6352 VAddrs.push_back(Op.getOperand(I)); 6353 } 6354 6355 // Add addresses (packed or unpacked) 6356 if (IsA16) { 6357 packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs, 6358 ArgOffset + Intr->CoordStart, VAddrEnd, 6359 0 /* No gradients */); 6360 } else { 6361 // Add uncompressed address 6362 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6363 VAddrs.push_back(Op.getOperand(I)); 6364 } 6365 6366 // If the register allocator cannot place the address registers contiguously 6367 // without introducing moves, then using the non-sequential address encoding 6368 // is always preferable, since it saves VALU instructions and is usually a 6369 // wash in terms of code size or even better. 6370 // 6371 // However, we currently have no way of hinting to the register allocator that 6372 // MIMG addresses should be placed contiguously when it is possible to do so, 6373 // so force non-NSA for the common 2-address case as a heuristic. 6374 // 6375 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6376 // allocation when possible. 6377 bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) && 6378 VAddrs.size() >= 3 && 6379 VAddrs.size() <= (unsigned)ST->getNSAMaxSize(); 6380 SDValue VAddr; 6381 if (!UseNSA) 6382 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6383 6384 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6385 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6386 SDValue Unorm; 6387 if (!BaseOpcode->Sampler) { 6388 Unorm = True; 6389 } else { 6390 auto UnormConst = 6391 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6392 6393 Unorm = UnormConst->getZExtValue() ? True : False; 6394 } 6395 6396 SDValue TFE; 6397 SDValue LWE; 6398 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6399 bool IsTexFail = false; 6400 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6401 return Op; 6402 6403 if (IsTexFail) { 6404 if (!DMaskLanes) { 6405 // Expecting to get an error flag since TFC is on - and dmask is 0 6406 // Force dmask to be at least 1 otherwise the instruction will fail 6407 DMask = 0x1; 6408 DMaskLanes = 1; 6409 NumVDataDwords = 1; 6410 } 6411 NumVDataDwords += 1; 6412 AdjustRetType = true; 6413 } 6414 6415 // Has something earlier tagged that the return type needs adjusting 6416 // This happens if the instruction is a load or has set TexFailCtrl flags 6417 if (AdjustRetType) { 6418 // NumVDataDwords reflects the true number of dwords required in the return type 6419 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6420 // This is a no-op load. This can be eliminated 6421 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6422 if (isa<MemSDNode>(Op)) 6423 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6424 return Undef; 6425 } 6426 6427 EVT NewVT = NumVDataDwords > 1 ? 6428 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6429 : MVT::i32; 6430 6431 ResultTypes[0] = NewVT; 6432 if (ResultTypes.size() == 3) { 6433 // Original result was aggregate type used for TexFailCtrl results 6434 // The actual instruction returns as a vector type which has now been 6435 // created. Remove the aggregate result. 6436 ResultTypes.erase(&ResultTypes[1]); 6437 } 6438 } 6439 6440 unsigned CPol = cast<ConstantSDNode>( 6441 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6442 if (BaseOpcode->Atomic) 6443 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6444 if (CPol & ~AMDGPU::CPol::ALL) 6445 return Op; 6446 6447 SmallVector<SDValue, 26> Ops; 6448 if (BaseOpcode->Store || BaseOpcode->Atomic) 6449 Ops.push_back(VData); // vdata 6450 if (UseNSA) 6451 append_range(Ops, VAddrs); 6452 else 6453 Ops.push_back(VAddr); 6454 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6455 if (BaseOpcode->Sampler) 6456 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6457 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6458 if (IsGFX10Plus) 6459 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6460 Ops.push_back(Unorm); 6461 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6462 Ops.push_back(IsA16 && // r128, a16 for gfx9 6463 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6464 if (IsGFX10Plus) 6465 Ops.push_back(IsA16 ? True : False); 6466 if (!Subtarget->hasGFX90AInsts()) { 6467 Ops.push_back(TFE); //tfe 6468 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6469 report_fatal_error("TFE is not supported on this GPU"); 6470 } 6471 Ops.push_back(LWE); // lwe 6472 if (!IsGFX10Plus) 6473 Ops.push_back(DimInfo->DA ? True : False); 6474 if (BaseOpcode->HasD16) 6475 Ops.push_back(IsD16 ? True : False); 6476 if (isa<MemSDNode>(Op)) 6477 Ops.push_back(Op.getOperand(0)); // chain 6478 6479 int NumVAddrDwords = 6480 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6481 int Opcode = -1; 6482 6483 if (IsGFX10Plus) { 6484 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6485 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6486 : AMDGPU::MIMGEncGfx10Default, 6487 NumVDataDwords, NumVAddrDwords); 6488 } else { 6489 if (Subtarget->hasGFX90AInsts()) { 6490 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6491 NumVDataDwords, NumVAddrDwords); 6492 if (Opcode == -1) 6493 report_fatal_error( 6494 "requested image instruction is not supported on this GPU"); 6495 } 6496 if (Opcode == -1 && 6497 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6498 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6499 NumVDataDwords, NumVAddrDwords); 6500 if (Opcode == -1) 6501 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6502 NumVDataDwords, NumVAddrDwords); 6503 } 6504 assert(Opcode != -1); 6505 6506 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6507 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6508 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6509 DAG.setNodeMemRefs(NewNode, {MemRef}); 6510 } 6511 6512 if (BaseOpcode->AtomicX2) { 6513 SmallVector<SDValue, 1> Elt; 6514 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6515 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6516 } 6517 if (BaseOpcode->Store) 6518 return SDValue(NewNode, 0); 6519 return constructRetValue(DAG, NewNode, 6520 OrigResultTypes, IsTexFail, 6521 Subtarget->hasUnpackedD16VMem(), IsD16, 6522 DMaskLanes, NumVDataDwords, DL); 6523 } 6524 6525 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6526 SDValue Offset, SDValue CachePolicy, 6527 SelectionDAG &DAG) const { 6528 MachineFunction &MF = DAG.getMachineFunction(); 6529 6530 const DataLayout &DataLayout = DAG.getDataLayout(); 6531 Align Alignment = 6532 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6533 6534 MachineMemOperand *MMO = MF.getMachineMemOperand( 6535 MachinePointerInfo(), 6536 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6537 MachineMemOperand::MOInvariant, 6538 VT.getStoreSize(), Alignment); 6539 6540 if (!Offset->isDivergent()) { 6541 SDValue Ops[] = { 6542 Rsrc, 6543 Offset, // Offset 6544 CachePolicy 6545 }; 6546 6547 // Widen vec3 load to vec4. 6548 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6549 EVT WidenedVT = 6550 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6551 auto WidenedOp = DAG.getMemIntrinsicNode( 6552 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6553 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6554 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6555 DAG.getVectorIdxConstant(0, DL)); 6556 return Subvector; 6557 } 6558 6559 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6560 DAG.getVTList(VT), Ops, VT, MMO); 6561 } 6562 6563 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6564 // assume that the buffer is unswizzled. 6565 SmallVector<SDValue, 4> Loads; 6566 unsigned NumLoads = 1; 6567 MVT LoadVT = VT.getSimpleVT(); 6568 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6569 assert((LoadVT.getScalarType() == MVT::i32 || 6570 LoadVT.getScalarType() == MVT::f32)); 6571 6572 if (NumElts == 8 || NumElts == 16) { 6573 NumLoads = NumElts / 4; 6574 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6575 } 6576 6577 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6578 SDValue Ops[] = { 6579 DAG.getEntryNode(), // Chain 6580 Rsrc, // rsrc 6581 DAG.getConstant(0, DL, MVT::i32), // vindex 6582 {}, // voffset 6583 {}, // soffset 6584 {}, // offset 6585 CachePolicy, // cachepolicy 6586 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6587 }; 6588 6589 // Use the alignment to ensure that the required offsets will fit into the 6590 // immediate offsets. 6591 setBufferOffsets(Offset, DAG, &Ops[3], 6592 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6593 6594 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6595 for (unsigned i = 0; i < NumLoads; ++i) { 6596 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6597 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6598 LoadVT, MMO, DAG)); 6599 } 6600 6601 if (NumElts == 8 || NumElts == 16) 6602 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6603 6604 return Loads[0]; 6605 } 6606 6607 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6608 SelectionDAG &DAG) const { 6609 MachineFunction &MF = DAG.getMachineFunction(); 6610 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6611 6612 EVT VT = Op.getValueType(); 6613 SDLoc DL(Op); 6614 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6615 6616 // TODO: Should this propagate fast-math-flags? 6617 6618 switch (IntrinsicID) { 6619 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6620 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6621 return emitNonHSAIntrinsicError(DAG, DL, VT); 6622 return getPreloadedValue(DAG, *MFI, VT, 6623 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6624 } 6625 case Intrinsic::amdgcn_dispatch_ptr: 6626 case Intrinsic::amdgcn_queue_ptr: { 6627 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6628 DiagnosticInfoUnsupported BadIntrin( 6629 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6630 DL.getDebugLoc()); 6631 DAG.getContext()->diagnose(BadIntrin); 6632 return DAG.getUNDEF(VT); 6633 } 6634 6635 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6636 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6637 return getPreloadedValue(DAG, *MFI, VT, RegID); 6638 } 6639 case Intrinsic::amdgcn_implicitarg_ptr: { 6640 if (MFI->isEntryFunction()) 6641 return getImplicitArgPtr(DAG, DL); 6642 return getPreloadedValue(DAG, *MFI, VT, 6643 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6644 } 6645 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6646 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6647 // This only makes sense to call in a kernel, so just lower to null. 6648 return DAG.getConstant(0, DL, VT); 6649 } 6650 6651 return getPreloadedValue(DAG, *MFI, VT, 6652 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6653 } 6654 case Intrinsic::amdgcn_dispatch_id: { 6655 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6656 } 6657 case Intrinsic::amdgcn_rcp: 6658 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6659 case Intrinsic::amdgcn_rsq: 6660 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6661 case Intrinsic::amdgcn_rsq_legacy: 6662 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6663 return emitRemovedIntrinsicError(DAG, DL, VT); 6664 return SDValue(); 6665 case Intrinsic::amdgcn_rcp_legacy: 6666 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6667 return emitRemovedIntrinsicError(DAG, DL, VT); 6668 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6669 case Intrinsic::amdgcn_rsq_clamp: { 6670 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6671 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6672 6673 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6674 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6675 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6676 6677 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6678 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6679 DAG.getConstantFP(Max, DL, VT)); 6680 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6681 DAG.getConstantFP(Min, DL, VT)); 6682 } 6683 case Intrinsic::r600_read_ngroups_x: 6684 if (Subtarget->isAmdHsaOS()) 6685 return emitNonHSAIntrinsicError(DAG, DL, VT); 6686 6687 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6688 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6689 false); 6690 case Intrinsic::r600_read_ngroups_y: 6691 if (Subtarget->isAmdHsaOS()) 6692 return emitNonHSAIntrinsicError(DAG, DL, VT); 6693 6694 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6695 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6696 false); 6697 case Intrinsic::r600_read_ngroups_z: 6698 if (Subtarget->isAmdHsaOS()) 6699 return emitNonHSAIntrinsicError(DAG, DL, VT); 6700 6701 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6702 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6703 false); 6704 case Intrinsic::r600_read_global_size_x: 6705 if (Subtarget->isAmdHsaOS()) 6706 return emitNonHSAIntrinsicError(DAG, DL, VT); 6707 6708 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6709 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6710 Align(4), false); 6711 case Intrinsic::r600_read_global_size_y: 6712 if (Subtarget->isAmdHsaOS()) 6713 return emitNonHSAIntrinsicError(DAG, DL, VT); 6714 6715 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6716 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6717 Align(4), false); 6718 case Intrinsic::r600_read_global_size_z: 6719 if (Subtarget->isAmdHsaOS()) 6720 return emitNonHSAIntrinsicError(DAG, DL, VT); 6721 6722 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6723 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6724 Align(4), false); 6725 case Intrinsic::r600_read_local_size_x: 6726 if (Subtarget->isAmdHsaOS()) 6727 return emitNonHSAIntrinsicError(DAG, DL, VT); 6728 6729 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6730 SI::KernelInputOffsets::LOCAL_SIZE_X); 6731 case Intrinsic::r600_read_local_size_y: 6732 if (Subtarget->isAmdHsaOS()) 6733 return emitNonHSAIntrinsicError(DAG, DL, VT); 6734 6735 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6736 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6737 case Intrinsic::r600_read_local_size_z: 6738 if (Subtarget->isAmdHsaOS()) 6739 return emitNonHSAIntrinsicError(DAG, DL, VT); 6740 6741 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6742 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6743 case Intrinsic::amdgcn_workgroup_id_x: 6744 return getPreloadedValue(DAG, *MFI, VT, 6745 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6746 case Intrinsic::amdgcn_workgroup_id_y: 6747 return getPreloadedValue(DAG, *MFI, VT, 6748 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6749 case Intrinsic::amdgcn_workgroup_id_z: 6750 return getPreloadedValue(DAG, *MFI, VT, 6751 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6752 case Intrinsic::amdgcn_workitem_id_x: 6753 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6754 SDLoc(DAG.getEntryNode()), 6755 MFI->getArgInfo().WorkItemIDX); 6756 case Intrinsic::amdgcn_workitem_id_y: 6757 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6758 SDLoc(DAG.getEntryNode()), 6759 MFI->getArgInfo().WorkItemIDY); 6760 case Intrinsic::amdgcn_workitem_id_z: 6761 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6762 SDLoc(DAG.getEntryNode()), 6763 MFI->getArgInfo().WorkItemIDZ); 6764 case Intrinsic::amdgcn_wavefrontsize: 6765 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6766 SDLoc(Op), MVT::i32); 6767 case Intrinsic::amdgcn_s_buffer_load: { 6768 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6769 if (CPol & ~AMDGPU::CPol::ALL) 6770 return Op; 6771 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6772 DAG); 6773 } 6774 case Intrinsic::amdgcn_fdiv_fast: 6775 return lowerFDIV_FAST(Op, DAG); 6776 case Intrinsic::amdgcn_sin: 6777 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6778 6779 case Intrinsic::amdgcn_cos: 6780 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6781 6782 case Intrinsic::amdgcn_mul_u24: 6783 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6784 case Intrinsic::amdgcn_mul_i24: 6785 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6786 6787 case Intrinsic::amdgcn_log_clamp: { 6788 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6789 return SDValue(); 6790 6791 return emitRemovedIntrinsicError(DAG, DL, VT); 6792 } 6793 case Intrinsic::amdgcn_ldexp: 6794 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6795 Op.getOperand(1), Op.getOperand(2)); 6796 6797 case Intrinsic::amdgcn_fract: 6798 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6799 6800 case Intrinsic::amdgcn_class: 6801 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6802 Op.getOperand(1), Op.getOperand(2)); 6803 case Intrinsic::amdgcn_div_fmas: 6804 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6805 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6806 Op.getOperand(4)); 6807 6808 case Intrinsic::amdgcn_div_fixup: 6809 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6810 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6811 6812 case Intrinsic::amdgcn_div_scale: { 6813 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6814 6815 // Translate to the operands expected by the machine instruction. The 6816 // first parameter must be the same as the first instruction. 6817 SDValue Numerator = Op.getOperand(1); 6818 SDValue Denominator = Op.getOperand(2); 6819 6820 // Note this order is opposite of the machine instruction's operations, 6821 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6822 // intrinsic has the numerator as the first operand to match a normal 6823 // division operation. 6824 6825 SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator; 6826 6827 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6828 Denominator, Numerator); 6829 } 6830 case Intrinsic::amdgcn_icmp: { 6831 // There is a Pat that handles this variant, so return it as-is. 6832 if (Op.getOperand(1).getValueType() == MVT::i1 && 6833 Op.getConstantOperandVal(2) == 0 && 6834 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6835 return Op; 6836 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6837 } 6838 case Intrinsic::amdgcn_fcmp: { 6839 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6840 } 6841 case Intrinsic::amdgcn_ballot: 6842 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6843 case Intrinsic::amdgcn_fmed3: 6844 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6845 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6846 case Intrinsic::amdgcn_fdot2: 6847 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6848 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6849 Op.getOperand(4)); 6850 case Intrinsic::amdgcn_fmul_legacy: 6851 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6852 Op.getOperand(1), Op.getOperand(2)); 6853 case Intrinsic::amdgcn_sffbh: 6854 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6855 case Intrinsic::amdgcn_sbfe: 6856 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6857 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6858 case Intrinsic::amdgcn_ubfe: 6859 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6861 case Intrinsic::amdgcn_cvt_pkrtz: 6862 case Intrinsic::amdgcn_cvt_pknorm_i16: 6863 case Intrinsic::amdgcn_cvt_pknorm_u16: 6864 case Intrinsic::amdgcn_cvt_pk_i16: 6865 case Intrinsic::amdgcn_cvt_pk_u16: { 6866 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6867 EVT VT = Op.getValueType(); 6868 unsigned Opcode; 6869 6870 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6871 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6872 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6873 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6874 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6875 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6876 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6877 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6878 else 6879 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6880 6881 if (isTypeLegal(VT)) 6882 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6883 6884 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6885 Op.getOperand(1), Op.getOperand(2)); 6886 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6887 } 6888 case Intrinsic::amdgcn_fmad_ftz: 6889 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6890 Op.getOperand(2), Op.getOperand(3)); 6891 6892 case Intrinsic::amdgcn_if_break: 6893 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6894 Op->getOperand(1), Op->getOperand(2)), 0); 6895 6896 case Intrinsic::amdgcn_groupstaticsize: { 6897 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6898 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6899 return Op; 6900 6901 const Module *M = MF.getFunction().getParent(); 6902 const GlobalValue *GV = 6903 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6904 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6905 SIInstrInfo::MO_ABS32_LO); 6906 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6907 } 6908 case Intrinsic::amdgcn_is_shared: 6909 case Intrinsic::amdgcn_is_private: { 6910 SDLoc SL(Op); 6911 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6912 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6913 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6914 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6915 Op.getOperand(1)); 6916 6917 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6918 DAG.getConstant(1, SL, MVT::i32)); 6919 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6920 } 6921 case Intrinsic::amdgcn_alignbit: 6922 return DAG.getNode(ISD::FSHR, DL, VT, 6923 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6924 case Intrinsic::amdgcn_perm: 6925 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1), 6926 Op.getOperand(2), Op.getOperand(3)); 6927 case Intrinsic::amdgcn_reloc_constant: { 6928 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6929 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6930 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6931 auto RelocSymbol = cast<GlobalVariable>( 6932 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6933 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6934 SIInstrInfo::MO_ABS32_LO); 6935 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6936 } 6937 default: 6938 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6939 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6940 return lowerImage(Op, ImageDimIntr, DAG, false); 6941 6942 return Op; 6943 } 6944 } 6945 6946 /// Update \p MMO based on the offset inputs to an intrinsic. 6947 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset, 6948 SDValue SOffset, SDValue Offset, 6949 SDValue VIndex = SDValue()) { 6950 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6951 !isa<ConstantSDNode>(Offset)) { 6952 // The combined offset is not known to be constant, so we cannot represent 6953 // it in the MMO. Give up. 6954 MMO->setValue((Value *)nullptr); 6955 return; 6956 } 6957 6958 if (VIndex && (!isa<ConstantSDNode>(VIndex) || 6959 !cast<ConstantSDNode>(VIndex)->isZero())) { 6960 // The strided index component of the address is not known to be zero, so we 6961 // cannot represent it in the MMO. Give up. 6962 MMO->setValue((Value *)nullptr); 6963 return; 6964 } 6965 6966 MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() + 6967 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6968 cast<ConstantSDNode>(Offset)->getSExtValue()); 6969 } 6970 6971 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6972 SelectionDAG &DAG, 6973 unsigned NewOpcode) const { 6974 SDLoc DL(Op); 6975 6976 SDValue VData = Op.getOperand(2); 6977 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6978 SDValue Ops[] = { 6979 Op.getOperand(0), // Chain 6980 VData, // vdata 6981 Op.getOperand(3), // rsrc 6982 DAG.getConstant(0, DL, MVT::i32), // vindex 6983 Offsets.first, // voffset 6984 Op.getOperand(5), // soffset 6985 Offsets.second, // offset 6986 Op.getOperand(6), // cachepolicy 6987 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6988 }; 6989 6990 auto *M = cast<MemSDNode>(Op); 6991 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 6992 6993 EVT MemVT = VData.getValueType(); 6994 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6995 M->getMemOperand()); 6996 } 6997 6998 // Return a value to use for the idxen operand by examining the vindex operand. 6999 static unsigned getIdxEn(SDValue VIndex) { 7000 if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex)) 7001 // No need to set idxen if vindex is known to be zero. 7002 return VIndexC->getZExtValue() != 0; 7003 return 1; 7004 } 7005 7006 SDValue 7007 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 7008 unsigned NewOpcode) const { 7009 SDLoc DL(Op); 7010 7011 SDValue VData = Op.getOperand(2); 7012 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7013 SDValue Ops[] = { 7014 Op.getOperand(0), // Chain 7015 VData, // vdata 7016 Op.getOperand(3), // rsrc 7017 Op.getOperand(4), // vindex 7018 Offsets.first, // voffset 7019 Op.getOperand(6), // soffset 7020 Offsets.second, // offset 7021 Op.getOperand(7), // cachepolicy 7022 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7023 }; 7024 7025 auto *M = cast<MemSDNode>(Op); 7026 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7027 7028 EVT MemVT = VData.getValueType(); 7029 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 7030 M->getMemOperand()); 7031 } 7032 7033 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 7034 SelectionDAG &DAG) const { 7035 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7036 SDLoc DL(Op); 7037 7038 switch (IntrID) { 7039 case Intrinsic::amdgcn_ds_ordered_add: 7040 case Intrinsic::amdgcn_ds_ordered_swap: { 7041 MemSDNode *M = cast<MemSDNode>(Op); 7042 SDValue Chain = M->getOperand(0); 7043 SDValue M0 = M->getOperand(2); 7044 SDValue Value = M->getOperand(3); 7045 unsigned IndexOperand = M->getConstantOperandVal(7); 7046 unsigned WaveRelease = M->getConstantOperandVal(8); 7047 unsigned WaveDone = M->getConstantOperandVal(9); 7048 7049 unsigned OrderedCountIndex = IndexOperand & 0x3f; 7050 IndexOperand &= ~0x3f; 7051 unsigned CountDw = 0; 7052 7053 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 7054 CountDw = (IndexOperand >> 24) & 0xf; 7055 IndexOperand &= ~(0xf << 24); 7056 7057 if (CountDw < 1 || CountDw > 4) { 7058 report_fatal_error( 7059 "ds_ordered_count: dword count must be between 1 and 4"); 7060 } 7061 } 7062 7063 if (IndexOperand) 7064 report_fatal_error("ds_ordered_count: bad index operand"); 7065 7066 if (WaveDone && !WaveRelease) 7067 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 7068 7069 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 7070 unsigned ShaderType = 7071 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 7072 unsigned Offset0 = OrderedCountIndex << 2; 7073 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 7074 (Instruction << 4); 7075 7076 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 7077 Offset1 |= (CountDw - 1) << 6; 7078 7079 unsigned Offset = Offset0 | (Offset1 << 8); 7080 7081 SDValue Ops[] = { 7082 Chain, 7083 Value, 7084 DAG.getTargetConstant(Offset, DL, MVT::i16), 7085 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 7086 }; 7087 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 7088 M->getVTList(), Ops, M->getMemoryVT(), 7089 M->getMemOperand()); 7090 } 7091 case Intrinsic::amdgcn_ds_fadd: { 7092 MemSDNode *M = cast<MemSDNode>(Op); 7093 unsigned Opc; 7094 switch (IntrID) { 7095 case Intrinsic::amdgcn_ds_fadd: 7096 Opc = ISD::ATOMIC_LOAD_FADD; 7097 break; 7098 } 7099 7100 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 7101 M->getOperand(0), M->getOperand(2), M->getOperand(3), 7102 M->getMemOperand()); 7103 } 7104 case Intrinsic::amdgcn_atomic_inc: 7105 case Intrinsic::amdgcn_atomic_dec: 7106 case Intrinsic::amdgcn_ds_fmin: 7107 case Intrinsic::amdgcn_ds_fmax: { 7108 MemSDNode *M = cast<MemSDNode>(Op); 7109 unsigned Opc; 7110 switch (IntrID) { 7111 case Intrinsic::amdgcn_atomic_inc: 7112 Opc = AMDGPUISD::ATOMIC_INC; 7113 break; 7114 case Intrinsic::amdgcn_atomic_dec: 7115 Opc = AMDGPUISD::ATOMIC_DEC; 7116 break; 7117 case Intrinsic::amdgcn_ds_fmin: 7118 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 7119 break; 7120 case Intrinsic::amdgcn_ds_fmax: 7121 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 7122 break; 7123 default: 7124 llvm_unreachable("Unknown intrinsic!"); 7125 } 7126 SDValue Ops[] = { 7127 M->getOperand(0), // Chain 7128 M->getOperand(2), // Ptr 7129 M->getOperand(3) // Value 7130 }; 7131 7132 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 7133 M->getMemoryVT(), M->getMemOperand()); 7134 } 7135 case Intrinsic::amdgcn_buffer_load: 7136 case Intrinsic::amdgcn_buffer_load_format: { 7137 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 7138 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7139 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7140 SDValue Ops[] = { 7141 Op.getOperand(0), // Chain 7142 Op.getOperand(2), // rsrc 7143 Op.getOperand(3), // vindex 7144 SDValue(), // voffset -- will be set by setBufferOffsets 7145 SDValue(), // soffset -- will be set by setBufferOffsets 7146 SDValue(), // offset -- will be set by setBufferOffsets 7147 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7148 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7149 }; 7150 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 7151 7152 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 7153 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 7154 7155 EVT VT = Op.getValueType(); 7156 EVT IntVT = VT.changeTypeToInteger(); 7157 auto *M = cast<MemSDNode>(Op); 7158 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7159 EVT LoadVT = Op.getValueType(); 7160 7161 if (LoadVT.getScalarType() == MVT::f16) 7162 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 7163 M, DAG, Ops); 7164 7165 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 7166 if (LoadVT.getScalarType() == MVT::i8 || 7167 LoadVT.getScalarType() == MVT::i16) 7168 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 7169 7170 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 7171 M->getMemOperand(), DAG); 7172 } 7173 case Intrinsic::amdgcn_raw_buffer_load: 7174 case Intrinsic::amdgcn_raw_buffer_load_format: { 7175 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 7176 7177 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7178 SDValue Ops[] = { 7179 Op.getOperand(0), // Chain 7180 Op.getOperand(2), // rsrc 7181 DAG.getConstant(0, DL, MVT::i32), // vindex 7182 Offsets.first, // voffset 7183 Op.getOperand(4), // soffset 7184 Offsets.second, // offset 7185 Op.getOperand(5), // cachepolicy, swizzled buffer 7186 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7187 }; 7188 7189 auto *M = cast<MemSDNode>(Op); 7190 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]); 7191 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 7192 } 7193 case Intrinsic::amdgcn_struct_buffer_load: 7194 case Intrinsic::amdgcn_struct_buffer_load_format: { 7195 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 7196 7197 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7198 SDValue Ops[] = { 7199 Op.getOperand(0), // Chain 7200 Op.getOperand(2), // rsrc 7201 Op.getOperand(3), // vindex 7202 Offsets.first, // voffset 7203 Op.getOperand(5), // soffset 7204 Offsets.second, // offset 7205 Op.getOperand(6), // cachepolicy, swizzled buffer 7206 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7207 }; 7208 7209 auto *M = cast<MemSDNode>(Op); 7210 updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]); 7211 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 7212 } 7213 case Intrinsic::amdgcn_tbuffer_load: { 7214 MemSDNode *M = cast<MemSDNode>(Op); 7215 EVT LoadVT = Op.getValueType(); 7216 7217 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7218 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7219 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7220 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7221 unsigned IdxEn = getIdxEn(Op.getOperand(3)); 7222 SDValue Ops[] = { 7223 Op.getOperand(0), // Chain 7224 Op.getOperand(2), // rsrc 7225 Op.getOperand(3), // vindex 7226 Op.getOperand(4), // voffset 7227 Op.getOperand(5), // soffset 7228 Op.getOperand(6), // offset 7229 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7230 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7231 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 7232 }; 7233 7234 if (LoadVT.getScalarType() == MVT::f16) 7235 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7236 M, DAG, Ops); 7237 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7238 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7239 DAG); 7240 } 7241 case Intrinsic::amdgcn_raw_tbuffer_load: { 7242 MemSDNode *M = cast<MemSDNode>(Op); 7243 EVT LoadVT = Op.getValueType(); 7244 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 7245 7246 SDValue Ops[] = { 7247 Op.getOperand(0), // Chain 7248 Op.getOperand(2), // rsrc 7249 DAG.getConstant(0, DL, MVT::i32), // vindex 7250 Offsets.first, // voffset 7251 Op.getOperand(4), // soffset 7252 Offsets.second, // offset 7253 Op.getOperand(5), // format 7254 Op.getOperand(6), // cachepolicy, swizzled buffer 7255 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7256 }; 7257 7258 if (LoadVT.getScalarType() == MVT::f16) 7259 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7260 M, DAG, Ops); 7261 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7262 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7263 DAG); 7264 } 7265 case Intrinsic::amdgcn_struct_tbuffer_load: { 7266 MemSDNode *M = cast<MemSDNode>(Op); 7267 EVT LoadVT = Op.getValueType(); 7268 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7269 7270 SDValue Ops[] = { 7271 Op.getOperand(0), // Chain 7272 Op.getOperand(2), // rsrc 7273 Op.getOperand(3), // vindex 7274 Offsets.first, // voffset 7275 Op.getOperand(5), // soffset 7276 Offsets.second, // offset 7277 Op.getOperand(6), // format 7278 Op.getOperand(7), // cachepolicy, swizzled buffer 7279 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7280 }; 7281 7282 if (LoadVT.getScalarType() == MVT::f16) 7283 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7284 M, DAG, Ops); 7285 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7286 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7287 DAG); 7288 } 7289 case Intrinsic::amdgcn_buffer_atomic_swap: 7290 case Intrinsic::amdgcn_buffer_atomic_add: 7291 case Intrinsic::amdgcn_buffer_atomic_sub: 7292 case Intrinsic::amdgcn_buffer_atomic_csub: 7293 case Intrinsic::amdgcn_buffer_atomic_smin: 7294 case Intrinsic::amdgcn_buffer_atomic_umin: 7295 case Intrinsic::amdgcn_buffer_atomic_smax: 7296 case Intrinsic::amdgcn_buffer_atomic_umax: 7297 case Intrinsic::amdgcn_buffer_atomic_and: 7298 case Intrinsic::amdgcn_buffer_atomic_or: 7299 case Intrinsic::amdgcn_buffer_atomic_xor: 7300 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7301 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7302 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7303 SDValue Ops[] = { 7304 Op.getOperand(0), // Chain 7305 Op.getOperand(2), // vdata 7306 Op.getOperand(3), // rsrc 7307 Op.getOperand(4), // vindex 7308 SDValue(), // voffset -- will be set by setBufferOffsets 7309 SDValue(), // soffset -- will be set by setBufferOffsets 7310 SDValue(), // offset -- will be set by setBufferOffsets 7311 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7312 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7313 }; 7314 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7315 7316 EVT VT = Op.getValueType(); 7317 7318 auto *M = cast<MemSDNode>(Op); 7319 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7320 unsigned Opcode = 0; 7321 7322 switch (IntrID) { 7323 case Intrinsic::amdgcn_buffer_atomic_swap: 7324 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7325 break; 7326 case Intrinsic::amdgcn_buffer_atomic_add: 7327 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7328 break; 7329 case Intrinsic::amdgcn_buffer_atomic_sub: 7330 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7331 break; 7332 case Intrinsic::amdgcn_buffer_atomic_csub: 7333 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7334 break; 7335 case Intrinsic::amdgcn_buffer_atomic_smin: 7336 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7337 break; 7338 case Intrinsic::amdgcn_buffer_atomic_umin: 7339 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7340 break; 7341 case Intrinsic::amdgcn_buffer_atomic_smax: 7342 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7343 break; 7344 case Intrinsic::amdgcn_buffer_atomic_umax: 7345 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7346 break; 7347 case Intrinsic::amdgcn_buffer_atomic_and: 7348 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7349 break; 7350 case Intrinsic::amdgcn_buffer_atomic_or: 7351 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7352 break; 7353 case Intrinsic::amdgcn_buffer_atomic_xor: 7354 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7355 break; 7356 case Intrinsic::amdgcn_buffer_atomic_fadd: 7357 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7358 DiagnosticInfoUnsupported 7359 NoFpRet(DAG.getMachineFunction().getFunction(), 7360 "return versions of fp atomics not supported", 7361 DL.getDebugLoc(), DS_Error); 7362 DAG.getContext()->diagnose(NoFpRet); 7363 return SDValue(); 7364 } 7365 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7366 break; 7367 default: 7368 llvm_unreachable("unhandled atomic opcode"); 7369 } 7370 7371 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7372 M->getMemOperand()); 7373 } 7374 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7375 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7376 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7377 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7378 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7379 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7380 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7381 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7382 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7383 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7384 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7385 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7386 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7387 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7388 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7389 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7390 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7391 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7392 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7393 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7394 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7395 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7396 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7397 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7398 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7399 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7400 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7401 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7402 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7403 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7404 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7405 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7406 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7407 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7408 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7409 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7410 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7411 return lowerStructBufferAtomicIntrin(Op, DAG, 7412 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7413 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7414 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7415 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7416 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7417 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7418 return lowerStructBufferAtomicIntrin(Op, DAG, 7419 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7420 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7421 return lowerStructBufferAtomicIntrin(Op, DAG, 7422 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7423 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7424 return lowerStructBufferAtomicIntrin(Op, DAG, 7425 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7426 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7427 return lowerStructBufferAtomicIntrin(Op, DAG, 7428 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7429 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7430 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7431 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7432 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7433 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7434 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7435 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7436 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7437 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7438 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7439 7440 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7441 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7442 unsigned IdxEn = getIdxEn(Op.getOperand(5)); 7443 SDValue Ops[] = { 7444 Op.getOperand(0), // Chain 7445 Op.getOperand(2), // src 7446 Op.getOperand(3), // cmp 7447 Op.getOperand(4), // rsrc 7448 Op.getOperand(5), // vindex 7449 SDValue(), // voffset -- will be set by setBufferOffsets 7450 SDValue(), // soffset -- will be set by setBufferOffsets 7451 SDValue(), // offset -- will be set by setBufferOffsets 7452 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7453 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7454 }; 7455 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7456 7457 EVT VT = Op.getValueType(); 7458 auto *M = cast<MemSDNode>(Op); 7459 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7460 7461 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7462 Op->getVTList(), Ops, VT, M->getMemOperand()); 7463 } 7464 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7465 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7466 SDValue Ops[] = { 7467 Op.getOperand(0), // Chain 7468 Op.getOperand(2), // src 7469 Op.getOperand(3), // cmp 7470 Op.getOperand(4), // rsrc 7471 DAG.getConstant(0, DL, MVT::i32), // vindex 7472 Offsets.first, // voffset 7473 Op.getOperand(6), // soffset 7474 Offsets.second, // offset 7475 Op.getOperand(7), // cachepolicy 7476 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7477 }; 7478 EVT VT = Op.getValueType(); 7479 auto *M = cast<MemSDNode>(Op); 7480 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]); 7481 7482 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7483 Op->getVTList(), Ops, VT, M->getMemOperand()); 7484 } 7485 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7486 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7487 SDValue Ops[] = { 7488 Op.getOperand(0), // Chain 7489 Op.getOperand(2), // src 7490 Op.getOperand(3), // cmp 7491 Op.getOperand(4), // rsrc 7492 Op.getOperand(5), // vindex 7493 Offsets.first, // voffset 7494 Op.getOperand(7), // soffset 7495 Offsets.second, // offset 7496 Op.getOperand(8), // cachepolicy 7497 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7498 }; 7499 EVT VT = Op.getValueType(); 7500 auto *M = cast<MemSDNode>(Op); 7501 updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]); 7502 7503 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7504 Op->getVTList(), Ops, VT, M->getMemOperand()); 7505 } 7506 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7507 MemSDNode *M = cast<MemSDNode>(Op); 7508 SDValue NodePtr = M->getOperand(2); 7509 SDValue RayExtent = M->getOperand(3); 7510 SDValue RayOrigin = M->getOperand(4); 7511 SDValue RayDir = M->getOperand(5); 7512 SDValue RayInvDir = M->getOperand(6); 7513 SDValue TDescr = M->getOperand(7); 7514 7515 assert(NodePtr.getValueType() == MVT::i32 || 7516 NodePtr.getValueType() == MVT::i64); 7517 assert(RayDir.getValueType() == MVT::v3f16 || 7518 RayDir.getValueType() == MVT::v3f32); 7519 7520 if (!Subtarget->hasGFX10_AEncoding()) { 7521 emitRemovedIntrinsicError(DAG, DL, Op.getValueType()); 7522 return SDValue(); 7523 } 7524 7525 const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7526 const bool Is64 = NodePtr.getValueType() == MVT::i64; 7527 const unsigned NumVDataDwords = 4; 7528 const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11); 7529 const bool UseNSA = Subtarget->hasNSAEncoding() && 7530 NumVAddrDwords <= Subtarget->getNSAMaxSize(); 7531 const unsigned BaseOpcodes[2][2] = { 7532 {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16}, 7533 {AMDGPU::IMAGE_BVH64_INTERSECT_RAY, 7534 AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}}; 7535 int Opcode; 7536 if (UseNSA) { 7537 Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16], 7538 AMDGPU::MIMGEncGfx10NSA, NumVDataDwords, 7539 NumVAddrDwords); 7540 } else { 7541 Opcode = AMDGPU::getMIMGOpcode( 7542 BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords, 7543 PowerOf2Ceil(NumVAddrDwords)); 7544 } 7545 assert(Opcode != -1); 7546 7547 SmallVector<SDValue, 16> Ops; 7548 7549 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7550 SmallVector<SDValue, 3> Lanes; 7551 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7552 if (Lanes[0].getValueSizeInBits() == 32) { 7553 for (unsigned I = 0; I < 3; ++I) 7554 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7555 } else { 7556 if (IsAligned) { 7557 Ops.push_back( 7558 DAG.getBitcast(MVT::i32, 7559 DAG.getBuildVector(MVT::v2f16, DL, 7560 { Lanes[0], Lanes[1] }))); 7561 Ops.push_back(Lanes[2]); 7562 } else { 7563 SDValue Elt0 = Ops.pop_back_val(); 7564 Ops.push_back( 7565 DAG.getBitcast(MVT::i32, 7566 DAG.getBuildVector(MVT::v2f16, DL, 7567 { Elt0, Lanes[0] }))); 7568 Ops.push_back( 7569 DAG.getBitcast(MVT::i32, 7570 DAG.getBuildVector(MVT::v2f16, DL, 7571 { Lanes[1], Lanes[2] }))); 7572 } 7573 } 7574 }; 7575 7576 if (Is64) 7577 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7578 else 7579 Ops.push_back(NodePtr); 7580 7581 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7582 packLanes(RayOrigin, true); 7583 packLanes(RayDir, true); 7584 packLanes(RayInvDir, false); 7585 7586 if (!UseNSA) { 7587 // Build a single vector containing all the operands so far prepared. 7588 if (NumVAddrDwords > 8) { 7589 SDValue Undef = DAG.getUNDEF(MVT::i32); 7590 Ops.append(16 - Ops.size(), Undef); 7591 } 7592 assert(Ops.size() == 8 || Ops.size() == 16); 7593 SDValue MergedOps = DAG.getBuildVector( 7594 Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops); 7595 Ops.clear(); 7596 Ops.push_back(MergedOps); 7597 } 7598 7599 Ops.push_back(TDescr); 7600 if (IsA16) 7601 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7602 Ops.push_back(M->getChain()); 7603 7604 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7605 MachineMemOperand *MemRef = M->getMemOperand(); 7606 DAG.setNodeMemRefs(NewNode, {MemRef}); 7607 return SDValue(NewNode, 0); 7608 } 7609 case Intrinsic::amdgcn_global_atomic_fadd: 7610 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7611 DiagnosticInfoUnsupported 7612 NoFpRet(DAG.getMachineFunction().getFunction(), 7613 "return versions of fp atomics not supported", 7614 DL.getDebugLoc(), DS_Error); 7615 DAG.getContext()->diagnose(NoFpRet); 7616 return SDValue(); 7617 } 7618 LLVM_FALLTHROUGH; 7619 case Intrinsic::amdgcn_global_atomic_fmin: 7620 case Intrinsic::amdgcn_global_atomic_fmax: 7621 case Intrinsic::amdgcn_flat_atomic_fadd: 7622 case Intrinsic::amdgcn_flat_atomic_fmin: 7623 case Intrinsic::amdgcn_flat_atomic_fmax: { 7624 MemSDNode *M = cast<MemSDNode>(Op); 7625 SDValue Ops[] = { 7626 M->getOperand(0), // Chain 7627 M->getOperand(2), // Ptr 7628 M->getOperand(3) // Value 7629 }; 7630 unsigned Opcode = 0; 7631 switch (IntrID) { 7632 case Intrinsic::amdgcn_global_atomic_fadd: 7633 case Intrinsic::amdgcn_flat_atomic_fadd: { 7634 EVT VT = Op.getOperand(3).getValueType(); 7635 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7636 DAG.getVTList(VT, MVT::Other), Ops, 7637 M->getMemOperand()); 7638 } 7639 case Intrinsic::amdgcn_global_atomic_fmin: 7640 case Intrinsic::amdgcn_flat_atomic_fmin: { 7641 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7642 break; 7643 } 7644 case Intrinsic::amdgcn_global_atomic_fmax: 7645 case Intrinsic::amdgcn_flat_atomic_fmax: { 7646 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7647 break; 7648 } 7649 default: 7650 llvm_unreachable("unhandled atomic opcode"); 7651 } 7652 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7653 M->getVTList(), Ops, M->getMemoryVT(), 7654 M->getMemOperand()); 7655 } 7656 default: 7657 7658 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7659 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7660 return lowerImage(Op, ImageDimIntr, DAG, true); 7661 7662 return SDValue(); 7663 } 7664 } 7665 7666 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7667 // dwordx4 if on SI. 7668 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7669 SDVTList VTList, 7670 ArrayRef<SDValue> Ops, EVT MemVT, 7671 MachineMemOperand *MMO, 7672 SelectionDAG &DAG) const { 7673 EVT VT = VTList.VTs[0]; 7674 EVT WidenedVT = VT; 7675 EVT WidenedMemVT = MemVT; 7676 if (!Subtarget->hasDwordx3LoadStores() && 7677 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7678 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7679 WidenedVT.getVectorElementType(), 4); 7680 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7681 WidenedMemVT.getVectorElementType(), 4); 7682 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7683 } 7684 7685 assert(VTList.NumVTs == 2); 7686 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7687 7688 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7689 WidenedMemVT, MMO); 7690 if (WidenedVT != VT) { 7691 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7692 DAG.getVectorIdxConstant(0, DL)); 7693 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7694 } 7695 return NewOp; 7696 } 7697 7698 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7699 bool ImageStore) const { 7700 EVT StoreVT = VData.getValueType(); 7701 7702 // No change for f16 and legal vector D16 types. 7703 if (!StoreVT.isVector()) 7704 return VData; 7705 7706 SDLoc DL(VData); 7707 unsigned NumElements = StoreVT.getVectorNumElements(); 7708 7709 if (Subtarget->hasUnpackedD16VMem()) { 7710 // We need to unpack the packed data to store. 7711 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7712 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7713 7714 EVT EquivStoreVT = 7715 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7716 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7717 return DAG.UnrollVectorOp(ZExt.getNode()); 7718 } 7719 7720 // The sq block of gfx8.1 does not estimate register use correctly for d16 7721 // image store instructions. The data operand is computed as if it were not a 7722 // d16 image instruction. 7723 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7724 // Bitcast to i16 7725 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7726 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7727 7728 // Decompose into scalars 7729 SmallVector<SDValue, 4> Elts; 7730 DAG.ExtractVectorElements(IntVData, Elts); 7731 7732 // Group pairs of i16 into v2i16 and bitcast to i32 7733 SmallVector<SDValue, 4> PackedElts; 7734 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7735 SDValue Pair = 7736 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7737 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7738 PackedElts.push_back(IntPair); 7739 } 7740 if ((NumElements % 2) == 1) { 7741 // Handle v3i16 7742 unsigned I = Elts.size() / 2; 7743 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7744 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7745 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7746 PackedElts.push_back(IntPair); 7747 } 7748 7749 // Pad using UNDEF 7750 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7751 7752 // Build final vector 7753 EVT VecVT = 7754 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7755 return DAG.getBuildVector(VecVT, DL, PackedElts); 7756 } 7757 7758 if (NumElements == 3) { 7759 EVT IntStoreVT = 7760 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7761 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7762 7763 EVT WidenedStoreVT = EVT::getVectorVT( 7764 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7765 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7766 WidenedStoreVT.getStoreSizeInBits()); 7767 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7768 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7769 } 7770 7771 assert(isTypeLegal(StoreVT)); 7772 return VData; 7773 } 7774 7775 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7776 SelectionDAG &DAG) const { 7777 SDLoc DL(Op); 7778 SDValue Chain = Op.getOperand(0); 7779 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7780 MachineFunction &MF = DAG.getMachineFunction(); 7781 7782 switch (IntrinsicID) { 7783 case Intrinsic::amdgcn_exp_compr: { 7784 SDValue Src0 = Op.getOperand(4); 7785 SDValue Src1 = Op.getOperand(5); 7786 // Hack around illegal type on SI by directly selecting it. 7787 if (isTypeLegal(Src0.getValueType())) 7788 return SDValue(); 7789 7790 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7791 SDValue Undef = DAG.getUNDEF(MVT::f32); 7792 const SDValue Ops[] = { 7793 Op.getOperand(2), // tgt 7794 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7795 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7796 Undef, // src2 7797 Undef, // src3 7798 Op.getOperand(7), // vm 7799 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7800 Op.getOperand(3), // en 7801 Op.getOperand(0) // Chain 7802 }; 7803 7804 unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7805 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7806 } 7807 case Intrinsic::amdgcn_s_barrier: { 7808 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7809 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7810 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7811 if (WGSize <= ST.getWavefrontSize()) 7812 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7813 Op.getOperand(0)), 0); 7814 } 7815 return SDValue(); 7816 }; 7817 case Intrinsic::amdgcn_tbuffer_store: { 7818 SDValue VData = Op.getOperand(2); 7819 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7820 if (IsD16) 7821 VData = handleD16VData(VData, DAG); 7822 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7823 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7824 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7825 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7826 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7827 SDValue Ops[] = { 7828 Chain, 7829 VData, // vdata 7830 Op.getOperand(3), // rsrc 7831 Op.getOperand(4), // vindex 7832 Op.getOperand(5), // voffset 7833 Op.getOperand(6), // soffset 7834 Op.getOperand(7), // offset 7835 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7836 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7837 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7838 }; 7839 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7840 AMDGPUISD::TBUFFER_STORE_FORMAT; 7841 MemSDNode *M = cast<MemSDNode>(Op); 7842 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7843 M->getMemoryVT(), M->getMemOperand()); 7844 } 7845 7846 case Intrinsic::amdgcn_struct_tbuffer_store: { 7847 SDValue VData = Op.getOperand(2); 7848 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7849 if (IsD16) 7850 VData = handleD16VData(VData, DAG); 7851 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7852 SDValue Ops[] = { 7853 Chain, 7854 VData, // vdata 7855 Op.getOperand(3), // rsrc 7856 Op.getOperand(4), // vindex 7857 Offsets.first, // voffset 7858 Op.getOperand(6), // soffset 7859 Offsets.second, // offset 7860 Op.getOperand(7), // format 7861 Op.getOperand(8), // cachepolicy, swizzled buffer 7862 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7863 }; 7864 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7865 AMDGPUISD::TBUFFER_STORE_FORMAT; 7866 MemSDNode *M = cast<MemSDNode>(Op); 7867 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7868 M->getMemoryVT(), M->getMemOperand()); 7869 } 7870 7871 case Intrinsic::amdgcn_raw_tbuffer_store: { 7872 SDValue VData = Op.getOperand(2); 7873 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7874 if (IsD16) 7875 VData = handleD16VData(VData, DAG); 7876 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7877 SDValue Ops[] = { 7878 Chain, 7879 VData, // vdata 7880 Op.getOperand(3), // rsrc 7881 DAG.getConstant(0, DL, MVT::i32), // vindex 7882 Offsets.first, // voffset 7883 Op.getOperand(5), // soffset 7884 Offsets.second, // offset 7885 Op.getOperand(6), // format 7886 Op.getOperand(7), // cachepolicy, swizzled buffer 7887 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7888 }; 7889 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7890 AMDGPUISD::TBUFFER_STORE_FORMAT; 7891 MemSDNode *M = cast<MemSDNode>(Op); 7892 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7893 M->getMemoryVT(), M->getMemOperand()); 7894 } 7895 7896 case Intrinsic::amdgcn_buffer_store: 7897 case Intrinsic::amdgcn_buffer_store_format: { 7898 SDValue VData = Op.getOperand(2); 7899 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7900 if (IsD16) 7901 VData = handleD16VData(VData, DAG); 7902 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7903 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7904 unsigned IdxEn = getIdxEn(Op.getOperand(4)); 7905 SDValue Ops[] = { 7906 Chain, 7907 VData, 7908 Op.getOperand(3), // rsrc 7909 Op.getOperand(4), // vindex 7910 SDValue(), // voffset -- will be set by setBufferOffsets 7911 SDValue(), // soffset -- will be set by setBufferOffsets 7912 SDValue(), // offset -- will be set by setBufferOffsets 7913 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7914 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7915 }; 7916 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7917 7918 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7919 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7920 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7921 MemSDNode *M = cast<MemSDNode>(Op); 7922 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 7923 7924 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7925 EVT VDataType = VData.getValueType().getScalarType(); 7926 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7927 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7928 7929 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7930 M->getMemoryVT(), M->getMemOperand()); 7931 } 7932 7933 case Intrinsic::amdgcn_raw_buffer_store: 7934 case Intrinsic::amdgcn_raw_buffer_store_format: { 7935 const bool IsFormat = 7936 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7937 7938 SDValue VData = Op.getOperand(2); 7939 EVT VDataVT = VData.getValueType(); 7940 EVT EltType = VDataVT.getScalarType(); 7941 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7942 if (IsD16) { 7943 VData = handleD16VData(VData, DAG); 7944 VDataVT = VData.getValueType(); 7945 } 7946 7947 if (!isTypeLegal(VDataVT)) { 7948 VData = 7949 DAG.getNode(ISD::BITCAST, DL, 7950 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7951 } 7952 7953 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7954 SDValue Ops[] = { 7955 Chain, 7956 VData, 7957 Op.getOperand(3), // rsrc 7958 DAG.getConstant(0, DL, MVT::i32), // vindex 7959 Offsets.first, // voffset 7960 Op.getOperand(5), // soffset 7961 Offsets.second, // offset 7962 Op.getOperand(6), // cachepolicy, swizzled buffer 7963 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7964 }; 7965 unsigned Opc = 7966 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7967 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7968 MemSDNode *M = cast<MemSDNode>(Op); 7969 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]); 7970 7971 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7972 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7973 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7974 7975 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7976 M->getMemoryVT(), M->getMemOperand()); 7977 } 7978 7979 case Intrinsic::amdgcn_struct_buffer_store: 7980 case Intrinsic::amdgcn_struct_buffer_store_format: { 7981 const bool IsFormat = 7982 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7983 7984 SDValue VData = Op.getOperand(2); 7985 EVT VDataVT = VData.getValueType(); 7986 EVT EltType = VDataVT.getScalarType(); 7987 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7988 7989 if (IsD16) { 7990 VData = handleD16VData(VData, DAG); 7991 VDataVT = VData.getValueType(); 7992 } 7993 7994 if (!isTypeLegal(VDataVT)) { 7995 VData = 7996 DAG.getNode(ISD::BITCAST, DL, 7997 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7998 } 7999 8000 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 8001 SDValue Ops[] = { 8002 Chain, 8003 VData, 8004 Op.getOperand(3), // rsrc 8005 Op.getOperand(4), // vindex 8006 Offsets.first, // voffset 8007 Op.getOperand(6), // soffset 8008 Offsets.second, // offset 8009 Op.getOperand(7), // cachepolicy, swizzled buffer 8010 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 8011 }; 8012 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 8013 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 8014 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 8015 MemSDNode *M = cast<MemSDNode>(Op); 8016 updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]); 8017 8018 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 8019 EVT VDataType = VData.getValueType().getScalarType(); 8020 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 8021 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 8022 8023 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 8024 M->getMemoryVT(), M->getMemOperand()); 8025 } 8026 case Intrinsic::amdgcn_end_cf: 8027 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 8028 Op->getOperand(2), Chain), 0); 8029 8030 default: { 8031 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 8032 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 8033 return lowerImage(Op, ImageDimIntr, DAG, true); 8034 8035 return Op; 8036 } 8037 } 8038 } 8039 8040 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 8041 // offset (the offset that is included in bounds checking and swizzling, to be 8042 // split between the instruction's voffset and immoffset fields) and soffset 8043 // (the offset that is excluded from bounds checking and swizzling, to go in 8044 // the instruction's soffset field). This function takes the first kind of 8045 // offset and figures out how to split it between voffset and immoffset. 8046 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 8047 SDValue Offset, SelectionDAG &DAG) const { 8048 SDLoc DL(Offset); 8049 const unsigned MaxImm = 4095; 8050 SDValue N0 = Offset; 8051 ConstantSDNode *C1 = nullptr; 8052 8053 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 8054 N0 = SDValue(); 8055 else if (DAG.isBaseWithConstantOffset(N0)) { 8056 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 8057 N0 = N0.getOperand(0); 8058 } 8059 8060 if (C1) { 8061 unsigned ImmOffset = C1->getZExtValue(); 8062 // If the immediate value is too big for the immoffset field, put the value 8063 // and -4096 into the immoffset field so that the value that is copied/added 8064 // for the voffset field is a multiple of 4096, and it stands more chance 8065 // of being CSEd with the copy/add for another similar load/store. 8066 // However, do not do that rounding down to a multiple of 4096 if that is a 8067 // negative number, as it appears to be illegal to have a negative offset 8068 // in the vgpr, even if adding the immediate offset makes it positive. 8069 unsigned Overflow = ImmOffset & ~MaxImm; 8070 ImmOffset -= Overflow; 8071 if ((int32_t)Overflow < 0) { 8072 Overflow += ImmOffset; 8073 ImmOffset = 0; 8074 } 8075 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 8076 if (Overflow) { 8077 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 8078 if (!N0) 8079 N0 = OverflowVal; 8080 else { 8081 SDValue Ops[] = { N0, OverflowVal }; 8082 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 8083 } 8084 } 8085 } 8086 if (!N0) 8087 N0 = DAG.getConstant(0, DL, MVT::i32); 8088 if (!C1) 8089 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 8090 return {N0, SDValue(C1, 0)}; 8091 } 8092 8093 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 8094 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 8095 // pointed to by Offsets. 8096 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 8097 SelectionDAG &DAG, SDValue *Offsets, 8098 Align Alignment) const { 8099 SDLoc DL(CombinedOffset); 8100 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 8101 uint32_t Imm = C->getZExtValue(); 8102 uint32_t SOffset, ImmOffset; 8103 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 8104 Alignment)) { 8105 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 8106 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8107 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8108 return; 8109 } 8110 } 8111 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 8112 SDValue N0 = CombinedOffset.getOperand(0); 8113 SDValue N1 = CombinedOffset.getOperand(1); 8114 uint32_t SOffset, ImmOffset; 8115 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 8116 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 8117 Subtarget, Alignment)) { 8118 Offsets[0] = N0; 8119 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 8120 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 8121 return; 8122 } 8123 } 8124 Offsets[0] = CombinedOffset; 8125 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 8126 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 8127 } 8128 8129 // Handle 8 bit and 16 bit buffer loads 8130 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 8131 EVT LoadVT, SDLoc DL, 8132 ArrayRef<SDValue> Ops, 8133 MemSDNode *M) const { 8134 EVT IntVT = LoadVT.changeTypeToInteger(); 8135 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 8136 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 8137 8138 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 8139 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 8140 Ops, IntVT, 8141 M->getMemOperand()); 8142 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 8143 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 8144 8145 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 8146 } 8147 8148 // Handle 8 bit and 16 bit buffer stores 8149 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 8150 EVT VDataType, SDLoc DL, 8151 SDValue Ops[], 8152 MemSDNode *M) const { 8153 if (VDataType == MVT::f16) 8154 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 8155 8156 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 8157 Ops[1] = BufferStoreExt; 8158 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 8159 AMDGPUISD::BUFFER_STORE_SHORT; 8160 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 8161 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 8162 M->getMemOperand()); 8163 } 8164 8165 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 8166 ISD::LoadExtType ExtType, SDValue Op, 8167 const SDLoc &SL, EVT VT) { 8168 if (VT.bitsLT(Op.getValueType())) 8169 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 8170 8171 switch (ExtType) { 8172 case ISD::SEXTLOAD: 8173 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 8174 case ISD::ZEXTLOAD: 8175 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 8176 case ISD::EXTLOAD: 8177 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 8178 case ISD::NON_EXTLOAD: 8179 return Op; 8180 } 8181 8182 llvm_unreachable("invalid ext type"); 8183 } 8184 8185 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 8186 SelectionDAG &DAG = DCI.DAG; 8187 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 8188 return SDValue(); 8189 8190 // FIXME: Constant loads should all be marked invariant. 8191 unsigned AS = Ld->getAddressSpace(); 8192 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 8193 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 8194 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 8195 return SDValue(); 8196 8197 // Don't do this early, since it may interfere with adjacent load merging for 8198 // illegal types. We can avoid losing alignment information for exotic types 8199 // pre-legalize. 8200 EVT MemVT = Ld->getMemoryVT(); 8201 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 8202 MemVT.getSizeInBits() >= 32) 8203 return SDValue(); 8204 8205 SDLoc SL(Ld); 8206 8207 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 8208 "unexpected vector extload"); 8209 8210 // TODO: Drop only high part of range. 8211 SDValue Ptr = Ld->getBasePtr(); 8212 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 8213 MVT::i32, SL, Ld->getChain(), Ptr, 8214 Ld->getOffset(), 8215 Ld->getPointerInfo(), MVT::i32, 8216 Ld->getAlignment(), 8217 Ld->getMemOperand()->getFlags(), 8218 Ld->getAAInfo(), 8219 nullptr); // Drop ranges 8220 8221 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 8222 if (MemVT.isFloatingPoint()) { 8223 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 8224 "unexpected fp extload"); 8225 TruncVT = MemVT.changeTypeToInteger(); 8226 } 8227 8228 SDValue Cvt = NewLoad; 8229 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 8230 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 8231 DAG.getValueType(TruncVT)); 8232 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 8233 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 8234 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 8235 } else { 8236 assert(Ld->getExtensionType() == ISD::EXTLOAD); 8237 } 8238 8239 EVT VT = Ld->getValueType(0); 8240 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 8241 8242 DCI.AddToWorklist(Cvt.getNode()); 8243 8244 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 8245 // the appropriate extension from the 32-bit load. 8246 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 8247 DCI.AddToWorklist(Cvt.getNode()); 8248 8249 // Handle conversion back to floating point if necessary. 8250 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 8251 8252 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 8253 } 8254 8255 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 8256 SDLoc DL(Op); 8257 LoadSDNode *Load = cast<LoadSDNode>(Op); 8258 ISD::LoadExtType ExtType = Load->getExtensionType(); 8259 EVT MemVT = Load->getMemoryVT(); 8260 8261 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 8262 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 8263 return SDValue(); 8264 8265 // FIXME: Copied from PPC 8266 // First, load into 32 bits, then truncate to 1 bit. 8267 8268 SDValue Chain = Load->getChain(); 8269 SDValue BasePtr = Load->getBasePtr(); 8270 MachineMemOperand *MMO = Load->getMemOperand(); 8271 8272 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 8273 8274 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 8275 BasePtr, RealMemVT, MMO); 8276 8277 if (!MemVT.isVector()) { 8278 SDValue Ops[] = { 8279 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 8280 NewLD.getValue(1) 8281 }; 8282 8283 return DAG.getMergeValues(Ops, DL); 8284 } 8285 8286 SmallVector<SDValue, 3> Elts; 8287 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 8288 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 8289 DAG.getConstant(I, DL, MVT::i32)); 8290 8291 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8292 } 8293 8294 SDValue Ops[] = { 8295 DAG.getBuildVector(MemVT, DL, Elts), 8296 NewLD.getValue(1) 8297 }; 8298 8299 return DAG.getMergeValues(Ops, DL); 8300 } 8301 8302 if (!MemVT.isVector()) 8303 return SDValue(); 8304 8305 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8306 "Custom lowering for non-i32 vectors hasn't been implemented."); 8307 8308 unsigned Alignment = Load->getAlignment(); 8309 unsigned AS = Load->getAddressSpace(); 8310 if (Subtarget->hasLDSMisalignedBug() && 8311 AS == AMDGPUAS::FLAT_ADDRESS && 8312 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8313 return SplitVectorLoad(Op, DAG); 8314 } 8315 8316 MachineFunction &MF = DAG.getMachineFunction(); 8317 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8318 // If there is a possibilty that flat instruction access scratch memory 8319 // then we need to use the same legalization rules we use for private. 8320 if (AS == AMDGPUAS::FLAT_ADDRESS && 8321 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8322 AS = MFI->hasFlatScratchInit() ? 8323 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8324 8325 unsigned NumElements = MemVT.getVectorNumElements(); 8326 8327 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8328 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8329 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8330 if (MemVT.isPow2VectorType()) 8331 return SDValue(); 8332 return WidenOrSplitVectorLoad(Op, DAG); 8333 } 8334 // Non-uniform loads will be selected to MUBUF instructions, so they 8335 // have the same legalization requirements as global and private 8336 // loads. 8337 // 8338 } 8339 8340 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8341 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8342 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8343 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8344 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8345 Alignment >= 4 && NumElements < 32) { 8346 if (MemVT.isPow2VectorType()) 8347 return SDValue(); 8348 return WidenOrSplitVectorLoad(Op, DAG); 8349 } 8350 // Non-uniform loads will be selected to MUBUF instructions, so they 8351 // have the same legalization requirements as global and private 8352 // loads. 8353 // 8354 } 8355 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8356 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8357 AS == AMDGPUAS::GLOBAL_ADDRESS || 8358 AS == AMDGPUAS::FLAT_ADDRESS) { 8359 if (NumElements > 4) 8360 return SplitVectorLoad(Op, DAG); 8361 // v3 loads not supported on SI. 8362 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8363 return WidenOrSplitVectorLoad(Op, DAG); 8364 8365 // v3 and v4 loads are supported for private and global memory. 8366 return SDValue(); 8367 } 8368 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8369 // Depending on the setting of the private_element_size field in the 8370 // resource descriptor, we can only make private accesses up to a certain 8371 // size. 8372 switch (Subtarget->getMaxPrivateElementSize()) { 8373 case 4: { 8374 SDValue Ops[2]; 8375 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8376 return DAG.getMergeValues(Ops, DL); 8377 } 8378 case 8: 8379 if (NumElements > 2) 8380 return SplitVectorLoad(Op, DAG); 8381 return SDValue(); 8382 case 16: 8383 // Same as global/flat 8384 if (NumElements > 4) 8385 return SplitVectorLoad(Op, DAG); 8386 // v3 loads not supported on SI. 8387 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8388 return WidenOrSplitVectorLoad(Op, DAG); 8389 8390 return SDValue(); 8391 default: 8392 llvm_unreachable("unsupported private_element_size"); 8393 } 8394 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8395 // Use ds_read_b128 or ds_read_b96 when possible. 8396 if (Subtarget->hasDS96AndDS128() && 8397 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8398 MemVT.getStoreSize() == 12) && 8399 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8400 Load->getAlign())) 8401 return SDValue(); 8402 8403 if (NumElements > 2) 8404 return SplitVectorLoad(Op, DAG); 8405 8406 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8407 // address is negative, then the instruction is incorrectly treated as 8408 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8409 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8410 // load later in the SILoadStoreOptimizer. 8411 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8412 NumElements == 2 && MemVT.getStoreSize() == 8 && 8413 Load->getAlignment() < 8) { 8414 return SplitVectorLoad(Op, DAG); 8415 } 8416 } 8417 8418 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8419 MemVT, *Load->getMemOperand())) { 8420 SDValue Ops[2]; 8421 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8422 return DAG.getMergeValues(Ops, DL); 8423 } 8424 8425 return SDValue(); 8426 } 8427 8428 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8429 EVT VT = Op.getValueType(); 8430 assert(VT.getSizeInBits() == 64); 8431 8432 SDLoc DL(Op); 8433 SDValue Cond = Op.getOperand(0); 8434 8435 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8436 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8437 8438 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8439 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8440 8441 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8442 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8443 8444 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8445 8446 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8447 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8448 8449 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8450 8451 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8452 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8453 } 8454 8455 // Catch division cases where we can use shortcuts with rcp and rsq 8456 // instructions. 8457 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8458 SelectionDAG &DAG) const { 8459 SDLoc SL(Op); 8460 SDValue LHS = Op.getOperand(0); 8461 SDValue RHS = Op.getOperand(1); 8462 EVT VT = Op.getValueType(); 8463 const SDNodeFlags Flags = Op->getFlags(); 8464 8465 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8466 8467 // Without !fpmath accuracy information, we can't do more because we don't 8468 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8469 if (!AllowInaccurateRcp) 8470 return SDValue(); 8471 8472 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8473 if (CLHS->isExactlyValue(1.0)) { 8474 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8475 // the CI documentation has a worst case error of 1 ulp. 8476 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8477 // use it as long as we aren't trying to use denormals. 8478 // 8479 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8480 8481 // 1.0 / sqrt(x) -> rsq(x) 8482 8483 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8484 // error seems really high at 2^29 ULP. 8485 if (RHS.getOpcode() == ISD::FSQRT) 8486 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8487 8488 // 1.0 / x -> rcp(x) 8489 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8490 } 8491 8492 // Same as for 1.0, but expand the sign out of the constant. 8493 if (CLHS->isExactlyValue(-1.0)) { 8494 // -1.0 / x -> rcp (fneg x) 8495 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8496 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8497 } 8498 } 8499 8500 // Turn into multiply by the reciprocal. 8501 // x / y -> x * (1.0 / y) 8502 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8503 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8504 } 8505 8506 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8507 SelectionDAG &DAG) const { 8508 SDLoc SL(Op); 8509 SDValue X = Op.getOperand(0); 8510 SDValue Y = Op.getOperand(1); 8511 EVT VT = Op.getValueType(); 8512 const SDNodeFlags Flags = Op->getFlags(); 8513 8514 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8515 DAG.getTarget().Options.UnsafeFPMath; 8516 if (!AllowInaccurateDiv) 8517 return SDValue(); 8518 8519 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8520 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8521 8522 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8523 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8524 8525 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8526 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8527 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8528 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8529 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8530 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8531 } 8532 8533 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8534 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8535 SDNodeFlags Flags) { 8536 if (GlueChain->getNumValues() <= 1) { 8537 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8538 } 8539 8540 assert(GlueChain->getNumValues() == 3); 8541 8542 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8543 switch (Opcode) { 8544 default: llvm_unreachable("no chain equivalent for opcode"); 8545 case ISD::FMUL: 8546 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8547 break; 8548 } 8549 8550 return DAG.getNode(Opcode, SL, VTList, 8551 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8552 Flags); 8553 } 8554 8555 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8556 EVT VT, SDValue A, SDValue B, SDValue C, 8557 SDValue GlueChain, SDNodeFlags Flags) { 8558 if (GlueChain->getNumValues() <= 1) { 8559 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8560 } 8561 8562 assert(GlueChain->getNumValues() == 3); 8563 8564 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8565 switch (Opcode) { 8566 default: llvm_unreachable("no chain equivalent for opcode"); 8567 case ISD::FMA: 8568 Opcode = AMDGPUISD::FMA_W_CHAIN; 8569 break; 8570 } 8571 8572 return DAG.getNode(Opcode, SL, VTList, 8573 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8574 Flags); 8575 } 8576 8577 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8578 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8579 return FastLowered; 8580 8581 SDLoc SL(Op); 8582 SDValue Src0 = Op.getOperand(0); 8583 SDValue Src1 = Op.getOperand(1); 8584 8585 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8586 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8587 8588 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8589 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8590 8591 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8592 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8593 8594 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8595 } 8596 8597 // Faster 2.5 ULP division that does not support denormals. 8598 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8599 SDLoc SL(Op); 8600 SDValue LHS = Op.getOperand(1); 8601 SDValue RHS = Op.getOperand(2); 8602 8603 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8604 8605 const APFloat K0Val(BitsToFloat(0x6f800000)); 8606 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8607 8608 const APFloat K1Val(BitsToFloat(0x2f800000)); 8609 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8610 8611 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8612 8613 EVT SetCCVT = 8614 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8615 8616 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8617 8618 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8619 8620 // TODO: Should this propagate fast-math-flags? 8621 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8622 8623 // rcp does not support denormals. 8624 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8625 8626 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8627 8628 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8629 } 8630 8631 // Returns immediate value for setting the F32 denorm mode when using the 8632 // S_DENORM_MODE instruction. 8633 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8634 const SDLoc &SL, const GCNSubtarget *ST) { 8635 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8636 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8637 ? FP_DENORM_FLUSH_NONE 8638 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8639 8640 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8641 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8642 } 8643 8644 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8645 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8646 return FastLowered; 8647 8648 // The selection matcher assumes anything with a chain selecting to a 8649 // mayRaiseFPException machine instruction. Since we're introducing a chain 8650 // here, we need to explicitly report nofpexcept for the regular fdiv 8651 // lowering. 8652 SDNodeFlags Flags = Op->getFlags(); 8653 Flags.setNoFPExcept(true); 8654 8655 SDLoc SL(Op); 8656 SDValue LHS = Op.getOperand(0); 8657 SDValue RHS = Op.getOperand(1); 8658 8659 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8660 8661 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8662 8663 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8664 {RHS, RHS, LHS}, Flags); 8665 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8666 {LHS, RHS, LHS}, Flags); 8667 8668 // Denominator is scaled to not be denormal, so using rcp is ok. 8669 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8670 DenominatorScaled, Flags); 8671 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8672 DenominatorScaled, Flags); 8673 8674 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8675 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8676 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8677 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8678 8679 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8680 8681 if (!HasFP32Denormals) { 8682 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8683 // lowering. The chain dependence is insufficient, and we need glue. We do 8684 // not need the glue variants in a strictfp function. 8685 8686 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8687 8688 SDNode *EnableDenorm; 8689 if (Subtarget->hasDenormModeInst()) { 8690 const SDValue EnableDenormValue = 8691 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8692 8693 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8694 DAG.getEntryNode(), EnableDenormValue).getNode(); 8695 } else { 8696 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8697 SL, MVT::i32); 8698 EnableDenorm = 8699 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8700 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8701 } 8702 8703 SDValue Ops[3] = { 8704 NegDivScale0, 8705 SDValue(EnableDenorm, 0), 8706 SDValue(EnableDenorm, 1) 8707 }; 8708 8709 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8710 } 8711 8712 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8713 ApproxRcp, One, NegDivScale0, Flags); 8714 8715 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8716 ApproxRcp, Fma0, Flags); 8717 8718 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8719 Fma1, Fma1, Flags); 8720 8721 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8722 NumeratorScaled, Mul, Flags); 8723 8724 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8725 Fma2, Fma1, Mul, Fma2, Flags); 8726 8727 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8728 NumeratorScaled, Fma3, Flags); 8729 8730 if (!HasFP32Denormals) { 8731 SDNode *DisableDenorm; 8732 if (Subtarget->hasDenormModeInst()) { 8733 const SDValue DisableDenormValue = 8734 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8735 8736 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8737 Fma4.getValue(1), DisableDenormValue, 8738 Fma4.getValue(2)).getNode(); 8739 } else { 8740 const SDValue DisableDenormValue = 8741 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8742 8743 DisableDenorm = DAG.getMachineNode( 8744 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8745 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8746 } 8747 8748 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8749 SDValue(DisableDenorm, 0), DAG.getRoot()); 8750 DAG.setRoot(OutputChain); 8751 } 8752 8753 SDValue Scale = NumeratorScaled.getValue(1); 8754 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8755 {Fma4, Fma1, Fma3, Scale}, Flags); 8756 8757 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8758 } 8759 8760 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8761 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8762 return FastLowered; 8763 8764 SDLoc SL(Op); 8765 SDValue X = Op.getOperand(0); 8766 SDValue Y = Op.getOperand(1); 8767 8768 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8769 8770 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8771 8772 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8773 8774 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8775 8776 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8777 8778 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8779 8780 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8781 8782 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8783 8784 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8785 8786 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8787 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8788 8789 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8790 NegDivScale0, Mul, DivScale1); 8791 8792 SDValue Scale; 8793 8794 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8795 // Workaround a hardware bug on SI where the condition output from div_scale 8796 // is not usable. 8797 8798 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8799 8800 // Figure out if the scale to use for div_fmas. 8801 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8802 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8803 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8804 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8805 8806 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8807 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8808 8809 SDValue Scale0Hi 8810 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8811 SDValue Scale1Hi 8812 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8813 8814 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8815 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8816 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8817 } else { 8818 Scale = DivScale1.getValue(1); 8819 } 8820 8821 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8822 Fma4, Fma3, Mul, Scale); 8823 8824 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8825 } 8826 8827 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8828 EVT VT = Op.getValueType(); 8829 8830 if (VT == MVT::f32) 8831 return LowerFDIV32(Op, DAG); 8832 8833 if (VT == MVT::f64) 8834 return LowerFDIV64(Op, DAG); 8835 8836 if (VT == MVT::f16) 8837 return LowerFDIV16(Op, DAG); 8838 8839 llvm_unreachable("Unexpected type for fdiv"); 8840 } 8841 8842 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8843 SDLoc DL(Op); 8844 StoreSDNode *Store = cast<StoreSDNode>(Op); 8845 EVT VT = Store->getMemoryVT(); 8846 8847 if (VT == MVT::i1) { 8848 return DAG.getTruncStore(Store->getChain(), DL, 8849 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8850 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8851 } 8852 8853 assert(VT.isVector() && 8854 Store->getValue().getValueType().getScalarType() == MVT::i32); 8855 8856 unsigned AS = Store->getAddressSpace(); 8857 if (Subtarget->hasLDSMisalignedBug() && 8858 AS == AMDGPUAS::FLAT_ADDRESS && 8859 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8860 return SplitVectorStore(Op, DAG); 8861 } 8862 8863 MachineFunction &MF = DAG.getMachineFunction(); 8864 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8865 // If there is a possibilty that flat instruction access scratch memory 8866 // then we need to use the same legalization rules we use for private. 8867 if (AS == AMDGPUAS::FLAT_ADDRESS && 8868 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8869 AS = MFI->hasFlatScratchInit() ? 8870 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8871 8872 unsigned NumElements = VT.getVectorNumElements(); 8873 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8874 AS == AMDGPUAS::FLAT_ADDRESS) { 8875 if (NumElements > 4) 8876 return SplitVectorStore(Op, DAG); 8877 // v3 stores not supported on SI. 8878 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8879 return SplitVectorStore(Op, DAG); 8880 8881 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8882 VT, *Store->getMemOperand())) 8883 return expandUnalignedStore(Store, DAG); 8884 8885 return SDValue(); 8886 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8887 switch (Subtarget->getMaxPrivateElementSize()) { 8888 case 4: 8889 return scalarizeVectorStore(Store, DAG); 8890 case 8: 8891 if (NumElements > 2) 8892 return SplitVectorStore(Op, DAG); 8893 return SDValue(); 8894 case 16: 8895 if (NumElements > 4 || 8896 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8897 return SplitVectorStore(Op, DAG); 8898 return SDValue(); 8899 default: 8900 llvm_unreachable("unsupported private_element_size"); 8901 } 8902 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8903 // Use ds_write_b128 or ds_write_b96 when possible. 8904 if (Subtarget->hasDS96AndDS128() && 8905 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8906 (VT.getStoreSize() == 12)) && 8907 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8908 Store->getAlign())) 8909 return SDValue(); 8910 8911 if (NumElements > 2) 8912 return SplitVectorStore(Op, DAG); 8913 8914 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8915 // address is negative, then the instruction is incorrectly treated as 8916 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8917 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8918 // store later in the SILoadStoreOptimizer. 8919 if (!Subtarget->hasUsableDSOffset() && 8920 NumElements == 2 && VT.getStoreSize() == 8 && 8921 Store->getAlignment() < 8) { 8922 return SplitVectorStore(Op, DAG); 8923 } 8924 8925 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8926 VT, *Store->getMemOperand())) { 8927 if (VT.isVector()) 8928 return SplitVectorStore(Op, DAG); 8929 return expandUnalignedStore(Store, DAG); 8930 } 8931 8932 return SDValue(); 8933 } else { 8934 llvm_unreachable("unhandled address space"); 8935 } 8936 } 8937 8938 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8939 SDLoc DL(Op); 8940 EVT VT = Op.getValueType(); 8941 SDValue Arg = Op.getOperand(0); 8942 SDValue TrigVal; 8943 8944 // Propagate fast-math flags so that the multiply we introduce can be folded 8945 // if Arg is already the result of a multiply by constant. 8946 auto Flags = Op->getFlags(); 8947 8948 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8949 8950 if (Subtarget->hasTrigReducedRange()) { 8951 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8952 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8953 } else { 8954 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8955 } 8956 8957 switch (Op.getOpcode()) { 8958 case ISD::FCOS: 8959 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8960 case ISD::FSIN: 8961 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8962 default: 8963 llvm_unreachable("Wrong trig opcode"); 8964 } 8965 } 8966 8967 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8968 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8969 assert(AtomicNode->isCompareAndSwap()); 8970 unsigned AS = AtomicNode->getAddressSpace(); 8971 8972 // No custom lowering required for local address space 8973 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8974 return Op; 8975 8976 // Non-local address space requires custom lowering for atomic compare 8977 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8978 SDLoc DL(Op); 8979 SDValue ChainIn = Op.getOperand(0); 8980 SDValue Addr = Op.getOperand(1); 8981 SDValue Old = Op.getOperand(2); 8982 SDValue New = Op.getOperand(3); 8983 EVT VT = Op.getValueType(); 8984 MVT SimpleVT = VT.getSimpleVT(); 8985 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8986 8987 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8988 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8989 8990 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8991 Ops, VT, AtomicNode->getMemOperand()); 8992 } 8993 8994 //===----------------------------------------------------------------------===// 8995 // Custom DAG optimizations 8996 //===----------------------------------------------------------------------===// 8997 8998 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8999 DAGCombinerInfo &DCI) const { 9000 EVT VT = N->getValueType(0); 9001 EVT ScalarVT = VT.getScalarType(); 9002 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 9003 return SDValue(); 9004 9005 SelectionDAG &DAG = DCI.DAG; 9006 SDLoc DL(N); 9007 9008 SDValue Src = N->getOperand(0); 9009 EVT SrcVT = Src.getValueType(); 9010 9011 // TODO: We could try to match extracting the higher bytes, which would be 9012 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 9013 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 9014 // about in practice. 9015 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 9016 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 9017 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 9018 DCI.AddToWorklist(Cvt.getNode()); 9019 9020 // For the f16 case, fold to a cast to f32 and then cast back to f16. 9021 if (ScalarVT != MVT::f32) { 9022 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 9023 DAG.getTargetConstant(0, DL, MVT::i32)); 9024 } 9025 return Cvt; 9026 } 9027 } 9028 9029 return SDValue(); 9030 } 9031 9032 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 9033 9034 // This is a variant of 9035 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 9036 // 9037 // The normal DAG combiner will do this, but only if the add has one use since 9038 // that would increase the number of instructions. 9039 // 9040 // This prevents us from seeing a constant offset that can be folded into a 9041 // memory instruction's addressing mode. If we know the resulting add offset of 9042 // a pointer can be folded into an addressing offset, we can replace the pointer 9043 // operand with the add of new constant offset. This eliminates one of the uses, 9044 // and may allow the remaining use to also be simplified. 9045 // 9046 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 9047 unsigned AddrSpace, 9048 EVT MemVT, 9049 DAGCombinerInfo &DCI) const { 9050 SDValue N0 = N->getOperand(0); 9051 SDValue N1 = N->getOperand(1); 9052 9053 // We only do this to handle cases where it's profitable when there are 9054 // multiple uses of the add, so defer to the standard combine. 9055 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 9056 N0->hasOneUse()) 9057 return SDValue(); 9058 9059 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 9060 if (!CN1) 9061 return SDValue(); 9062 9063 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9064 if (!CAdd) 9065 return SDValue(); 9066 9067 // If the resulting offset is too large, we can't fold it into the addressing 9068 // mode offset. 9069 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 9070 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 9071 9072 AddrMode AM; 9073 AM.HasBaseReg = true; 9074 AM.BaseOffs = Offset.getSExtValue(); 9075 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 9076 return SDValue(); 9077 9078 SelectionDAG &DAG = DCI.DAG; 9079 SDLoc SL(N); 9080 EVT VT = N->getValueType(0); 9081 9082 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 9083 SDValue COffset = DAG.getConstant(Offset, SL, VT); 9084 9085 SDNodeFlags Flags; 9086 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 9087 (N0.getOpcode() == ISD::OR || 9088 N0->getFlags().hasNoUnsignedWrap())); 9089 9090 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 9091 } 9092 9093 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 9094 /// by the chain and intrinsic ID. Theoretically we would also need to check the 9095 /// specific intrinsic, but they all place the pointer operand first. 9096 static unsigned getBasePtrIndex(const MemSDNode *N) { 9097 switch (N->getOpcode()) { 9098 case ISD::STORE: 9099 case ISD::INTRINSIC_W_CHAIN: 9100 case ISD::INTRINSIC_VOID: 9101 return 2; 9102 default: 9103 return 1; 9104 } 9105 } 9106 9107 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 9108 DAGCombinerInfo &DCI) const { 9109 SelectionDAG &DAG = DCI.DAG; 9110 SDLoc SL(N); 9111 9112 unsigned PtrIdx = getBasePtrIndex(N); 9113 SDValue Ptr = N->getOperand(PtrIdx); 9114 9115 // TODO: We could also do this for multiplies. 9116 if (Ptr.getOpcode() == ISD::SHL) { 9117 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 9118 N->getMemoryVT(), DCI); 9119 if (NewPtr) { 9120 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 9121 9122 NewOps[PtrIdx] = NewPtr; 9123 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 9124 } 9125 } 9126 9127 return SDValue(); 9128 } 9129 9130 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 9131 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 9132 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 9133 (Opc == ISD::XOR && Val == 0); 9134 } 9135 9136 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 9137 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 9138 // integer combine opportunities since most 64-bit operations are decomposed 9139 // this way. TODO: We won't want this for SALU especially if it is an inline 9140 // immediate. 9141 SDValue SITargetLowering::splitBinaryBitConstantOp( 9142 DAGCombinerInfo &DCI, 9143 const SDLoc &SL, 9144 unsigned Opc, SDValue LHS, 9145 const ConstantSDNode *CRHS) const { 9146 uint64_t Val = CRHS->getZExtValue(); 9147 uint32_t ValLo = Lo_32(Val); 9148 uint32_t ValHi = Hi_32(Val); 9149 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9150 9151 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 9152 bitOpWithConstantIsReducible(Opc, ValHi)) || 9153 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 9154 // If we need to materialize a 64-bit immediate, it will be split up later 9155 // anyway. Avoid creating the harder to understand 64-bit immediate 9156 // materialization. 9157 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 9158 } 9159 9160 return SDValue(); 9161 } 9162 9163 // Returns true if argument is a boolean value which is not serialized into 9164 // memory or argument and does not require v_cndmask_b32 to be deserialized. 9165 static bool isBoolSGPR(SDValue V) { 9166 if (V.getValueType() != MVT::i1) 9167 return false; 9168 switch (V.getOpcode()) { 9169 default: 9170 break; 9171 case ISD::SETCC: 9172 case AMDGPUISD::FP_CLASS: 9173 return true; 9174 case ISD::AND: 9175 case ISD::OR: 9176 case ISD::XOR: 9177 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 9178 } 9179 return false; 9180 } 9181 9182 // If a constant has all zeroes or all ones within each byte return it. 9183 // Otherwise return 0. 9184 static uint32_t getConstantPermuteMask(uint32_t C) { 9185 // 0xff for any zero byte in the mask 9186 uint32_t ZeroByteMask = 0; 9187 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 9188 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 9189 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 9190 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 9191 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 9192 if ((NonZeroByteMask & C) != NonZeroByteMask) 9193 return 0; // Partial bytes selected. 9194 return C; 9195 } 9196 9197 // Check if a node selects whole bytes from its operand 0 starting at a byte 9198 // boundary while masking the rest. Returns select mask as in the v_perm_b32 9199 // or -1 if not succeeded. 9200 // Note byte select encoding: 9201 // value 0-3 selects corresponding source byte; 9202 // value 0xc selects zero; 9203 // value 0xff selects 0xff. 9204 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 9205 assert(V.getValueSizeInBits() == 32); 9206 9207 if (V.getNumOperands() != 2) 9208 return ~0; 9209 9210 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 9211 if (!N1) 9212 return ~0; 9213 9214 uint32_t C = N1->getZExtValue(); 9215 9216 switch (V.getOpcode()) { 9217 default: 9218 break; 9219 case ISD::AND: 9220 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9221 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 9222 } 9223 break; 9224 9225 case ISD::OR: 9226 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 9227 return (0x03020100 & ~ConstMask) | ConstMask; 9228 } 9229 break; 9230 9231 case ISD::SHL: 9232 if (C % 8) 9233 return ~0; 9234 9235 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 9236 9237 case ISD::SRL: 9238 if (C % 8) 9239 return ~0; 9240 9241 return uint32_t(0x0c0c0c0c03020100ull >> C); 9242 } 9243 9244 return ~0; 9245 } 9246 9247 SDValue SITargetLowering::performAndCombine(SDNode *N, 9248 DAGCombinerInfo &DCI) const { 9249 if (DCI.isBeforeLegalize()) 9250 return SDValue(); 9251 9252 SelectionDAG &DAG = DCI.DAG; 9253 EVT VT = N->getValueType(0); 9254 SDValue LHS = N->getOperand(0); 9255 SDValue RHS = N->getOperand(1); 9256 9257 9258 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9259 if (VT == MVT::i64 && CRHS) { 9260 if (SDValue Split 9261 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 9262 return Split; 9263 } 9264 9265 if (CRHS && VT == MVT::i32) { 9266 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 9267 // nb = number of trailing zeroes in mask 9268 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 9269 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 9270 uint64_t Mask = CRHS->getZExtValue(); 9271 unsigned Bits = countPopulation(Mask); 9272 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 9273 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 9274 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 9275 unsigned Shift = CShift->getZExtValue(); 9276 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 9277 unsigned Offset = NB + Shift; 9278 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 9279 SDLoc SL(N); 9280 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 9281 LHS->getOperand(0), 9282 DAG.getConstant(Offset, SL, MVT::i32), 9283 DAG.getConstant(Bits, SL, MVT::i32)); 9284 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 9285 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 9286 DAG.getValueType(NarrowVT)); 9287 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 9288 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 9289 return Shl; 9290 } 9291 } 9292 } 9293 9294 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9295 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9296 isa<ConstantSDNode>(LHS.getOperand(2))) { 9297 uint32_t Sel = getConstantPermuteMask(Mask); 9298 if (!Sel) 9299 return SDValue(); 9300 9301 // Select 0xc for all zero bytes 9302 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9303 SDLoc DL(N); 9304 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9305 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9306 } 9307 } 9308 9309 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9310 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9311 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9312 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9313 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9314 9315 SDValue X = LHS.getOperand(0); 9316 SDValue Y = RHS.getOperand(0); 9317 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9318 return SDValue(); 9319 9320 if (LCC == ISD::SETO) { 9321 if (X != LHS.getOperand(1)) 9322 return SDValue(); 9323 9324 if (RCC == ISD::SETUNE) { 9325 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9326 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9327 return SDValue(); 9328 9329 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9330 SIInstrFlags::N_SUBNORMAL | 9331 SIInstrFlags::N_ZERO | 9332 SIInstrFlags::P_ZERO | 9333 SIInstrFlags::P_SUBNORMAL | 9334 SIInstrFlags::P_NORMAL; 9335 9336 static_assert(((~(SIInstrFlags::S_NAN | 9337 SIInstrFlags::Q_NAN | 9338 SIInstrFlags::N_INFINITY | 9339 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9340 "mask not equal"); 9341 9342 SDLoc DL(N); 9343 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9344 X, DAG.getConstant(Mask, DL, MVT::i32)); 9345 } 9346 } 9347 } 9348 9349 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9350 std::swap(LHS, RHS); 9351 9352 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9353 RHS.hasOneUse()) { 9354 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9355 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9356 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9357 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9358 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9359 (RHS.getOperand(0) == LHS.getOperand(0) && 9360 LHS.getOperand(0) == LHS.getOperand(1))) { 9361 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9362 unsigned NewMask = LCC == ISD::SETO ? 9363 Mask->getZExtValue() & ~OrdMask : 9364 Mask->getZExtValue() & OrdMask; 9365 9366 SDLoc DL(N); 9367 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9368 DAG.getConstant(NewMask, DL, MVT::i32)); 9369 } 9370 } 9371 9372 if (VT == MVT::i32 && 9373 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9374 // and x, (sext cc from i1) => select cc, x, 0 9375 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9376 std::swap(LHS, RHS); 9377 if (isBoolSGPR(RHS.getOperand(0))) 9378 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9379 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9380 } 9381 9382 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9383 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9384 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9385 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9386 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9387 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9388 if (LHSMask != ~0u && RHSMask != ~0u) { 9389 // Canonicalize the expression in an attempt to have fewer unique masks 9390 // and therefore fewer registers used to hold the masks. 9391 if (LHSMask > RHSMask) { 9392 std::swap(LHSMask, RHSMask); 9393 std::swap(LHS, RHS); 9394 } 9395 9396 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9397 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9398 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9399 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9400 9401 // Check of we need to combine values from two sources within a byte. 9402 if (!(LHSUsedLanes & RHSUsedLanes) && 9403 // If we select high and lower word keep it for SDWA. 9404 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9405 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9406 // Each byte in each mask is either selector mask 0-3, or has higher 9407 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9408 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9409 // mask which is not 0xff wins. By anding both masks we have a correct 9410 // result except that 0x0c shall be corrected to give 0x0c only. 9411 uint32_t Mask = LHSMask & RHSMask; 9412 for (unsigned I = 0; I < 32; I += 8) { 9413 uint32_t ByteSel = 0xff << I; 9414 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9415 Mask &= (0x0c << I) & 0xffffffff; 9416 } 9417 9418 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9419 // or 0x0c. 9420 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9421 SDLoc DL(N); 9422 9423 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9424 LHS.getOperand(0), RHS.getOperand(0), 9425 DAG.getConstant(Sel, DL, MVT::i32)); 9426 } 9427 } 9428 } 9429 9430 return SDValue(); 9431 } 9432 9433 SDValue SITargetLowering::performOrCombine(SDNode *N, 9434 DAGCombinerInfo &DCI) const { 9435 SelectionDAG &DAG = DCI.DAG; 9436 SDValue LHS = N->getOperand(0); 9437 SDValue RHS = N->getOperand(1); 9438 9439 EVT VT = N->getValueType(0); 9440 if (VT == MVT::i1) { 9441 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9442 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9443 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9444 SDValue Src = LHS.getOperand(0); 9445 if (Src != RHS.getOperand(0)) 9446 return SDValue(); 9447 9448 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9449 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9450 if (!CLHS || !CRHS) 9451 return SDValue(); 9452 9453 // Only 10 bits are used. 9454 static const uint32_t MaxMask = 0x3ff; 9455 9456 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9457 SDLoc DL(N); 9458 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9459 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9460 } 9461 9462 return SDValue(); 9463 } 9464 9465 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9466 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9467 LHS.getOpcode() == AMDGPUISD::PERM && 9468 isa<ConstantSDNode>(LHS.getOperand(2))) { 9469 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9470 if (!Sel) 9471 return SDValue(); 9472 9473 Sel |= LHS.getConstantOperandVal(2); 9474 SDLoc DL(N); 9475 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9476 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9477 } 9478 9479 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9480 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9481 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9482 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9483 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9484 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9485 if (LHSMask != ~0u && RHSMask != ~0u) { 9486 // Canonicalize the expression in an attempt to have fewer unique masks 9487 // and therefore fewer registers used to hold the masks. 9488 if (LHSMask > RHSMask) { 9489 std::swap(LHSMask, RHSMask); 9490 std::swap(LHS, RHS); 9491 } 9492 9493 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9494 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9495 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9496 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9497 9498 // Check of we need to combine values from two sources within a byte. 9499 if (!(LHSUsedLanes & RHSUsedLanes) && 9500 // If we select high and lower word keep it for SDWA. 9501 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9502 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9503 // Kill zero bytes selected by other mask. Zero value is 0xc. 9504 LHSMask &= ~RHSUsedLanes; 9505 RHSMask &= ~LHSUsedLanes; 9506 // Add 4 to each active LHS lane 9507 LHSMask |= LHSUsedLanes & 0x04040404; 9508 // Combine masks 9509 uint32_t Sel = LHSMask | RHSMask; 9510 SDLoc DL(N); 9511 9512 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9513 LHS.getOperand(0), RHS.getOperand(0), 9514 DAG.getConstant(Sel, DL, MVT::i32)); 9515 } 9516 } 9517 } 9518 9519 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9520 return SDValue(); 9521 9522 // TODO: This could be a generic combine with a predicate for extracting the 9523 // high half of an integer being free. 9524 9525 // (or i64:x, (zero_extend i32:y)) -> 9526 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9527 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9528 RHS.getOpcode() != ISD::ZERO_EXTEND) 9529 std::swap(LHS, RHS); 9530 9531 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9532 SDValue ExtSrc = RHS.getOperand(0); 9533 EVT SrcVT = ExtSrc.getValueType(); 9534 if (SrcVT == MVT::i32) { 9535 SDLoc SL(N); 9536 SDValue LowLHS, HiBits; 9537 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9538 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9539 9540 DCI.AddToWorklist(LowOr.getNode()); 9541 DCI.AddToWorklist(HiBits.getNode()); 9542 9543 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9544 LowOr, HiBits); 9545 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9546 } 9547 } 9548 9549 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9550 if (CRHS) { 9551 if (SDValue Split 9552 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, 9553 N->getOperand(0), CRHS)) 9554 return Split; 9555 } 9556 9557 return SDValue(); 9558 } 9559 9560 SDValue SITargetLowering::performXorCombine(SDNode *N, 9561 DAGCombinerInfo &DCI) const { 9562 EVT VT = N->getValueType(0); 9563 if (VT != MVT::i64) 9564 return SDValue(); 9565 9566 SDValue LHS = N->getOperand(0); 9567 SDValue RHS = N->getOperand(1); 9568 9569 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9570 if (CRHS) { 9571 if (SDValue Split 9572 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9573 return Split; 9574 } 9575 9576 return SDValue(); 9577 } 9578 9579 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9580 DAGCombinerInfo &DCI) const { 9581 if (!Subtarget->has16BitInsts() || 9582 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9583 return SDValue(); 9584 9585 EVT VT = N->getValueType(0); 9586 if (VT != MVT::i32) 9587 return SDValue(); 9588 9589 SDValue Src = N->getOperand(0); 9590 if (Src.getValueType() != MVT::i16) 9591 return SDValue(); 9592 9593 return SDValue(); 9594 } 9595 9596 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9597 DAGCombinerInfo &DCI) 9598 const { 9599 SDValue Src = N->getOperand(0); 9600 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9601 9602 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9603 VTSign->getVT() == MVT::i8) || 9604 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9605 VTSign->getVT() == MVT::i16)) && 9606 Src.hasOneUse()) { 9607 auto *M = cast<MemSDNode>(Src); 9608 SDValue Ops[] = { 9609 Src.getOperand(0), // Chain 9610 Src.getOperand(1), // rsrc 9611 Src.getOperand(2), // vindex 9612 Src.getOperand(3), // voffset 9613 Src.getOperand(4), // soffset 9614 Src.getOperand(5), // offset 9615 Src.getOperand(6), 9616 Src.getOperand(7) 9617 }; 9618 // replace with BUFFER_LOAD_BYTE/SHORT 9619 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9620 Src.getOperand(0).getValueType()); 9621 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9622 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9623 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9624 ResList, 9625 Ops, M->getMemoryVT(), 9626 M->getMemOperand()); 9627 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9628 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9629 } 9630 return SDValue(); 9631 } 9632 9633 SDValue SITargetLowering::performClassCombine(SDNode *N, 9634 DAGCombinerInfo &DCI) const { 9635 SelectionDAG &DAG = DCI.DAG; 9636 SDValue Mask = N->getOperand(1); 9637 9638 // fp_class x, 0 -> false 9639 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9640 if (CMask->isZero()) 9641 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9642 } 9643 9644 if (N->getOperand(0).isUndef()) 9645 return DAG.getUNDEF(MVT::i1); 9646 9647 return SDValue(); 9648 } 9649 9650 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9651 DAGCombinerInfo &DCI) const { 9652 EVT VT = N->getValueType(0); 9653 SDValue N0 = N->getOperand(0); 9654 9655 if (N0.isUndef()) 9656 return N0; 9657 9658 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9659 N0.getOpcode() == ISD::SINT_TO_FP)) { 9660 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9661 N->getFlags()); 9662 } 9663 9664 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9665 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9666 N0.getOperand(0), N->getFlags()); 9667 } 9668 9669 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9670 } 9671 9672 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9673 unsigned MaxDepth) const { 9674 unsigned Opcode = Op.getOpcode(); 9675 if (Opcode == ISD::FCANONICALIZE) 9676 return true; 9677 9678 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9679 auto F = CFP->getValueAPF(); 9680 if (F.isNaN() && F.isSignaling()) 9681 return false; 9682 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9683 } 9684 9685 // If source is a result of another standard FP operation it is already in 9686 // canonical form. 9687 if (MaxDepth == 0) 9688 return false; 9689 9690 switch (Opcode) { 9691 // These will flush denorms if required. 9692 case ISD::FADD: 9693 case ISD::FSUB: 9694 case ISD::FMUL: 9695 case ISD::FCEIL: 9696 case ISD::FFLOOR: 9697 case ISD::FMA: 9698 case ISD::FMAD: 9699 case ISD::FSQRT: 9700 case ISD::FDIV: 9701 case ISD::FREM: 9702 case ISD::FP_ROUND: 9703 case ISD::FP_EXTEND: 9704 case AMDGPUISD::FMUL_LEGACY: 9705 case AMDGPUISD::FMAD_FTZ: 9706 case AMDGPUISD::RCP: 9707 case AMDGPUISD::RSQ: 9708 case AMDGPUISD::RSQ_CLAMP: 9709 case AMDGPUISD::RCP_LEGACY: 9710 case AMDGPUISD::RCP_IFLAG: 9711 case AMDGPUISD::DIV_SCALE: 9712 case AMDGPUISD::DIV_FMAS: 9713 case AMDGPUISD::DIV_FIXUP: 9714 case AMDGPUISD::FRACT: 9715 case AMDGPUISD::LDEXP: 9716 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9717 case AMDGPUISD::CVT_F32_UBYTE0: 9718 case AMDGPUISD::CVT_F32_UBYTE1: 9719 case AMDGPUISD::CVT_F32_UBYTE2: 9720 case AMDGPUISD::CVT_F32_UBYTE3: 9721 return true; 9722 9723 // It can/will be lowered or combined as a bit operation. 9724 // Need to check their input recursively to handle. 9725 case ISD::FNEG: 9726 case ISD::FABS: 9727 case ISD::FCOPYSIGN: 9728 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9729 9730 case ISD::FSIN: 9731 case ISD::FCOS: 9732 case ISD::FSINCOS: 9733 return Op.getValueType().getScalarType() != MVT::f16; 9734 9735 case ISD::FMINNUM: 9736 case ISD::FMAXNUM: 9737 case ISD::FMINNUM_IEEE: 9738 case ISD::FMAXNUM_IEEE: 9739 case AMDGPUISD::CLAMP: 9740 case AMDGPUISD::FMED3: 9741 case AMDGPUISD::FMAX3: 9742 case AMDGPUISD::FMIN3: { 9743 // FIXME: Shouldn't treat the generic operations different based these. 9744 // However, we aren't really required to flush the result from 9745 // minnum/maxnum.. 9746 9747 // snans will be quieted, so we only need to worry about denormals. 9748 if (Subtarget->supportsMinMaxDenormModes() || 9749 denormalsEnabledForType(DAG, Op.getValueType())) 9750 return true; 9751 9752 // Flushing may be required. 9753 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9754 // targets need to check their input recursively. 9755 9756 // FIXME: Does this apply with clamp? It's implemented with max. 9757 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9758 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9759 return false; 9760 } 9761 9762 return true; 9763 } 9764 case ISD::SELECT: { 9765 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9766 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9767 } 9768 case ISD::BUILD_VECTOR: { 9769 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9770 SDValue SrcOp = Op.getOperand(i); 9771 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9772 return false; 9773 } 9774 9775 return true; 9776 } 9777 case ISD::EXTRACT_VECTOR_ELT: 9778 case ISD::EXTRACT_SUBVECTOR: { 9779 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9780 } 9781 case ISD::INSERT_VECTOR_ELT: { 9782 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9783 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9784 } 9785 case ISD::UNDEF: 9786 // Could be anything. 9787 return false; 9788 9789 case ISD::BITCAST: 9790 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9791 case ISD::TRUNCATE: { 9792 // Hack round the mess we make when legalizing extract_vector_elt 9793 if (Op.getValueType() == MVT::i16) { 9794 SDValue TruncSrc = Op.getOperand(0); 9795 if (TruncSrc.getValueType() == MVT::i32 && 9796 TruncSrc.getOpcode() == ISD::BITCAST && 9797 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9798 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9799 } 9800 } 9801 return false; 9802 } 9803 case ISD::INTRINSIC_WO_CHAIN: { 9804 unsigned IntrinsicID 9805 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9806 // TODO: Handle more intrinsics 9807 switch (IntrinsicID) { 9808 case Intrinsic::amdgcn_cvt_pkrtz: 9809 case Intrinsic::amdgcn_cubeid: 9810 case Intrinsic::amdgcn_frexp_mant: 9811 case Intrinsic::amdgcn_fdot2: 9812 case Intrinsic::amdgcn_rcp: 9813 case Intrinsic::amdgcn_rsq: 9814 case Intrinsic::amdgcn_rsq_clamp: 9815 case Intrinsic::amdgcn_rcp_legacy: 9816 case Intrinsic::amdgcn_rsq_legacy: 9817 case Intrinsic::amdgcn_trig_preop: 9818 return true; 9819 default: 9820 break; 9821 } 9822 9823 LLVM_FALLTHROUGH; 9824 } 9825 default: 9826 return denormalsEnabledForType(DAG, Op.getValueType()) && 9827 DAG.isKnownNeverSNaN(Op); 9828 } 9829 9830 llvm_unreachable("invalid operation"); 9831 } 9832 9833 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF, 9834 unsigned MaxDepth) const { 9835 MachineRegisterInfo &MRI = MF.getRegInfo(); 9836 MachineInstr *MI = MRI.getVRegDef(Reg); 9837 unsigned Opcode = MI->getOpcode(); 9838 9839 if (Opcode == AMDGPU::G_FCANONICALIZE) 9840 return true; 9841 9842 Optional<FPValueAndVReg> FCR; 9843 // Constant splat (can be padded with undef) or scalar constant. 9844 if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) { 9845 if (FCR->Value.isSignaling()) 9846 return false; 9847 return !FCR->Value.isDenormal() || 9848 denormalsEnabledForType(MRI.getType(FCR->VReg), MF); 9849 } 9850 9851 if (MaxDepth == 0) 9852 return false; 9853 9854 switch (Opcode) { 9855 case AMDGPU::G_FMINNUM_IEEE: 9856 case AMDGPU::G_FMAXNUM_IEEE: { 9857 if (Subtarget->supportsMinMaxDenormModes() || 9858 denormalsEnabledForType(MRI.getType(Reg), MF)) 9859 return true; 9860 for (const MachineOperand &MO : llvm::drop_begin(MI->operands())) 9861 if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1)) 9862 return false; 9863 return true; 9864 } 9865 default: 9866 return denormalsEnabledForType(MRI.getType(Reg), MF) && 9867 isKnownNeverSNaN(Reg, MRI); 9868 } 9869 9870 llvm_unreachable("invalid operation"); 9871 } 9872 9873 // Constant fold canonicalize. 9874 SDValue SITargetLowering::getCanonicalConstantFP( 9875 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9876 // Flush denormals to 0 if not enabled. 9877 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9878 return DAG.getConstantFP(0.0, SL, VT); 9879 9880 if (C.isNaN()) { 9881 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9882 if (C.isSignaling()) { 9883 // Quiet a signaling NaN. 9884 // FIXME: Is this supposed to preserve payload bits? 9885 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9886 } 9887 9888 // Make sure it is the canonical NaN bitpattern. 9889 // 9890 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9891 // immediate? 9892 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9893 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9894 } 9895 9896 // Already canonical. 9897 return DAG.getConstantFP(C, SL, VT); 9898 } 9899 9900 static bool vectorEltWillFoldAway(SDValue Op) { 9901 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9902 } 9903 9904 SDValue SITargetLowering::performFCanonicalizeCombine( 9905 SDNode *N, 9906 DAGCombinerInfo &DCI) const { 9907 SelectionDAG &DAG = DCI.DAG; 9908 SDValue N0 = N->getOperand(0); 9909 EVT VT = N->getValueType(0); 9910 9911 // fcanonicalize undef -> qnan 9912 if (N0.isUndef()) { 9913 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9914 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9915 } 9916 9917 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9918 EVT VT = N->getValueType(0); 9919 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9920 } 9921 9922 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9923 // (fcanonicalize k) 9924 // 9925 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9926 9927 // TODO: This could be better with wider vectors that will be split to v2f16, 9928 // and to consider uses since there aren't that many packed operations. 9929 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9930 isTypeLegal(MVT::v2f16)) { 9931 SDLoc SL(N); 9932 SDValue NewElts[2]; 9933 SDValue Lo = N0.getOperand(0); 9934 SDValue Hi = N0.getOperand(1); 9935 EVT EltVT = Lo.getValueType(); 9936 9937 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9938 for (unsigned I = 0; I != 2; ++I) { 9939 SDValue Op = N0.getOperand(I); 9940 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9941 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9942 CFP->getValueAPF()); 9943 } else if (Op.isUndef()) { 9944 // Handled below based on what the other operand is. 9945 NewElts[I] = Op; 9946 } else { 9947 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9948 } 9949 } 9950 9951 // If one half is undef, and one is constant, perfer a splat vector rather 9952 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9953 // cheaper to use and may be free with a packed operation. 9954 if (NewElts[0].isUndef()) { 9955 if (isa<ConstantFPSDNode>(NewElts[1])) 9956 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9957 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9958 } 9959 9960 if (NewElts[1].isUndef()) { 9961 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9962 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9963 } 9964 9965 return DAG.getBuildVector(VT, SL, NewElts); 9966 } 9967 } 9968 9969 unsigned SrcOpc = N0.getOpcode(); 9970 9971 // If it's free to do so, push canonicalizes further up the source, which may 9972 // find a canonical source. 9973 // 9974 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9975 // sNaNs. 9976 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9977 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9978 if (CRHS && N0.hasOneUse()) { 9979 SDLoc SL(N); 9980 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9981 N0.getOperand(0)); 9982 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9983 DCI.AddToWorklist(Canon0.getNode()); 9984 9985 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9986 } 9987 } 9988 9989 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9990 } 9991 9992 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9993 switch (Opc) { 9994 case ISD::FMAXNUM: 9995 case ISD::FMAXNUM_IEEE: 9996 return AMDGPUISD::FMAX3; 9997 case ISD::SMAX: 9998 return AMDGPUISD::SMAX3; 9999 case ISD::UMAX: 10000 return AMDGPUISD::UMAX3; 10001 case ISD::FMINNUM: 10002 case ISD::FMINNUM_IEEE: 10003 return AMDGPUISD::FMIN3; 10004 case ISD::SMIN: 10005 return AMDGPUISD::SMIN3; 10006 case ISD::UMIN: 10007 return AMDGPUISD::UMIN3; 10008 default: 10009 llvm_unreachable("Not a min/max opcode"); 10010 } 10011 } 10012 10013 SDValue SITargetLowering::performIntMed3ImmCombine( 10014 SelectionDAG &DAG, const SDLoc &SL, 10015 SDValue Op0, SDValue Op1, bool Signed) const { 10016 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 10017 if (!K1) 10018 return SDValue(); 10019 10020 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 10021 if (!K0) 10022 return SDValue(); 10023 10024 if (Signed) { 10025 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 10026 return SDValue(); 10027 } else { 10028 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 10029 return SDValue(); 10030 } 10031 10032 EVT VT = K0->getValueType(0); 10033 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 10034 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 10035 return DAG.getNode(Med3Opc, SL, VT, 10036 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 10037 } 10038 10039 // If there isn't a 16-bit med3 operation, convert to 32-bit. 10040 if (VT == MVT::i16) { 10041 MVT NVT = MVT::i32; 10042 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10043 10044 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 10045 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 10046 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 10047 10048 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 10049 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 10050 } 10051 10052 return SDValue(); 10053 } 10054 10055 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 10056 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 10057 return C; 10058 10059 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 10060 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 10061 return C; 10062 } 10063 10064 return nullptr; 10065 } 10066 10067 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 10068 const SDLoc &SL, 10069 SDValue Op0, 10070 SDValue Op1) const { 10071 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 10072 if (!K1) 10073 return SDValue(); 10074 10075 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 10076 if (!K0) 10077 return SDValue(); 10078 10079 // Ordered >= (although NaN inputs should have folded away by now). 10080 if (K0->getValueAPF() > K1->getValueAPF()) 10081 return SDValue(); 10082 10083 const MachineFunction &MF = DAG.getMachineFunction(); 10084 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10085 10086 // TODO: Check IEEE bit enabled? 10087 EVT VT = Op0.getValueType(); 10088 if (Info->getMode().DX10Clamp) { 10089 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 10090 // hardware fmed3 behavior converting to a min. 10091 // FIXME: Should this be allowing -0.0? 10092 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 10093 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 10094 } 10095 10096 // med3 for f16 is only available on gfx9+, and not available for v2f16. 10097 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 10098 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 10099 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 10100 // then give the other result, which is different from med3 with a NaN 10101 // input. 10102 SDValue Var = Op0.getOperand(0); 10103 if (!DAG.isKnownNeverSNaN(Var)) 10104 return SDValue(); 10105 10106 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10107 10108 if ((!K0->hasOneUse() || 10109 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 10110 (!K1->hasOneUse() || 10111 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 10112 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 10113 Var, SDValue(K0, 0), SDValue(K1, 0)); 10114 } 10115 } 10116 10117 return SDValue(); 10118 } 10119 10120 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 10121 DAGCombinerInfo &DCI) const { 10122 SelectionDAG &DAG = DCI.DAG; 10123 10124 EVT VT = N->getValueType(0); 10125 unsigned Opc = N->getOpcode(); 10126 SDValue Op0 = N->getOperand(0); 10127 SDValue Op1 = N->getOperand(1); 10128 10129 // Only do this if the inner op has one use since this will just increases 10130 // register pressure for no benefit. 10131 10132 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 10133 !VT.isVector() && 10134 (VT == MVT::i32 || VT == MVT::f32 || 10135 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 10136 // max(max(a, b), c) -> max3(a, b, c) 10137 // min(min(a, b), c) -> min3(a, b, c) 10138 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 10139 SDLoc DL(N); 10140 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10141 DL, 10142 N->getValueType(0), 10143 Op0.getOperand(0), 10144 Op0.getOperand(1), 10145 Op1); 10146 } 10147 10148 // Try commuted. 10149 // max(a, max(b, c)) -> max3(a, b, c) 10150 // min(a, min(b, c)) -> min3(a, b, c) 10151 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 10152 SDLoc DL(N); 10153 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 10154 DL, 10155 N->getValueType(0), 10156 Op0, 10157 Op1.getOperand(0), 10158 Op1.getOperand(1)); 10159 } 10160 } 10161 10162 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 10163 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 10164 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 10165 return Med3; 10166 } 10167 10168 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 10169 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 10170 return Med3; 10171 } 10172 10173 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 10174 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 10175 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 10176 (Opc == AMDGPUISD::FMIN_LEGACY && 10177 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 10178 (VT == MVT::f32 || VT == MVT::f64 || 10179 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 10180 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 10181 Op0.hasOneUse()) { 10182 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 10183 return Res; 10184 } 10185 10186 return SDValue(); 10187 } 10188 10189 static bool isClampZeroToOne(SDValue A, SDValue B) { 10190 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 10191 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 10192 // FIXME: Should this be allowing -0.0? 10193 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 10194 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 10195 } 10196 } 10197 10198 return false; 10199 } 10200 10201 // FIXME: Should only worry about snans for version with chain. 10202 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 10203 DAGCombinerInfo &DCI) const { 10204 EVT VT = N->getValueType(0); 10205 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 10206 // NaNs. With a NaN input, the order of the operands may change the result. 10207 10208 SelectionDAG &DAG = DCI.DAG; 10209 SDLoc SL(N); 10210 10211 SDValue Src0 = N->getOperand(0); 10212 SDValue Src1 = N->getOperand(1); 10213 SDValue Src2 = N->getOperand(2); 10214 10215 if (isClampZeroToOne(Src0, Src1)) { 10216 // const_a, const_b, x -> clamp is safe in all cases including signaling 10217 // nans. 10218 // FIXME: Should this be allowing -0.0? 10219 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 10220 } 10221 10222 const MachineFunction &MF = DAG.getMachineFunction(); 10223 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10224 10225 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 10226 // handling no dx10-clamp? 10227 if (Info->getMode().DX10Clamp) { 10228 // If NaNs is clamped to 0, we are free to reorder the inputs. 10229 10230 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10231 std::swap(Src0, Src1); 10232 10233 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 10234 std::swap(Src1, Src2); 10235 10236 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 10237 std::swap(Src0, Src1); 10238 10239 if (isClampZeroToOne(Src1, Src2)) 10240 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 10241 } 10242 10243 return SDValue(); 10244 } 10245 10246 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 10247 DAGCombinerInfo &DCI) const { 10248 SDValue Src0 = N->getOperand(0); 10249 SDValue Src1 = N->getOperand(1); 10250 if (Src0.isUndef() && Src1.isUndef()) 10251 return DCI.DAG.getUNDEF(N->getValueType(0)); 10252 return SDValue(); 10253 } 10254 10255 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 10256 // expanded into a set of cmp/select instructions. 10257 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 10258 unsigned NumElem, 10259 bool IsDivergentIdx) { 10260 if (UseDivergentRegisterIndexing) 10261 return false; 10262 10263 unsigned VecSize = EltSize * NumElem; 10264 10265 // Sub-dword vectors of size 2 dword or less have better implementation. 10266 if (VecSize <= 64 && EltSize < 32) 10267 return false; 10268 10269 // Always expand the rest of sub-dword instructions, otherwise it will be 10270 // lowered via memory. 10271 if (EltSize < 32) 10272 return true; 10273 10274 // Always do this if var-idx is divergent, otherwise it will become a loop. 10275 if (IsDivergentIdx) 10276 return true; 10277 10278 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10279 unsigned NumInsts = NumElem /* Number of compares */ + 10280 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10281 return NumInsts <= 16; 10282 } 10283 10284 static bool shouldExpandVectorDynExt(SDNode *N) { 10285 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10286 if (isa<ConstantSDNode>(Idx)) 10287 return false; 10288 10289 SDValue Vec = N->getOperand(0); 10290 EVT VecVT = Vec.getValueType(); 10291 EVT EltVT = VecVT.getVectorElementType(); 10292 unsigned EltSize = EltVT.getSizeInBits(); 10293 unsigned NumElem = VecVT.getVectorNumElements(); 10294 10295 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10296 Idx->isDivergent()); 10297 } 10298 10299 SDValue SITargetLowering::performExtractVectorEltCombine( 10300 SDNode *N, DAGCombinerInfo &DCI) const { 10301 SDValue Vec = N->getOperand(0); 10302 SelectionDAG &DAG = DCI.DAG; 10303 10304 EVT VecVT = Vec.getValueType(); 10305 EVT EltVT = VecVT.getVectorElementType(); 10306 10307 if ((Vec.getOpcode() == ISD::FNEG || 10308 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10309 SDLoc SL(N); 10310 EVT EltVT = N->getValueType(0); 10311 SDValue Idx = N->getOperand(1); 10312 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10313 Vec.getOperand(0), Idx); 10314 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10315 } 10316 10317 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10318 // => 10319 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10320 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10321 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10322 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10323 SDLoc SL(N); 10324 EVT EltVT = N->getValueType(0); 10325 SDValue Idx = N->getOperand(1); 10326 unsigned Opc = Vec.getOpcode(); 10327 10328 switch(Opc) { 10329 default: 10330 break; 10331 // TODO: Support other binary operations. 10332 case ISD::FADD: 10333 case ISD::FSUB: 10334 case ISD::FMUL: 10335 case ISD::ADD: 10336 case ISD::UMIN: 10337 case ISD::UMAX: 10338 case ISD::SMIN: 10339 case ISD::SMAX: 10340 case ISD::FMAXNUM: 10341 case ISD::FMINNUM: 10342 case ISD::FMAXNUM_IEEE: 10343 case ISD::FMINNUM_IEEE: { 10344 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10345 Vec.getOperand(0), Idx); 10346 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10347 Vec.getOperand(1), Idx); 10348 10349 DCI.AddToWorklist(Elt0.getNode()); 10350 DCI.AddToWorklist(Elt1.getNode()); 10351 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10352 } 10353 } 10354 } 10355 10356 unsigned VecSize = VecVT.getSizeInBits(); 10357 unsigned EltSize = EltVT.getSizeInBits(); 10358 10359 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10360 if (::shouldExpandVectorDynExt(N)) { 10361 SDLoc SL(N); 10362 SDValue Idx = N->getOperand(1); 10363 SDValue V; 10364 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10365 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10366 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10367 if (I == 0) 10368 V = Elt; 10369 else 10370 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10371 } 10372 return V; 10373 } 10374 10375 if (!DCI.isBeforeLegalize()) 10376 return SDValue(); 10377 10378 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10379 // elements. This exposes more load reduction opportunities by replacing 10380 // multiple small extract_vector_elements with a single 32-bit extract. 10381 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10382 if (isa<MemSDNode>(Vec) && 10383 EltSize <= 16 && 10384 EltVT.isByteSized() && 10385 VecSize > 32 && 10386 VecSize % 32 == 0 && 10387 Idx) { 10388 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10389 10390 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10391 unsigned EltIdx = BitIndex / 32; 10392 unsigned LeftoverBitIdx = BitIndex % 32; 10393 SDLoc SL(N); 10394 10395 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10396 DCI.AddToWorklist(Cast.getNode()); 10397 10398 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10399 DAG.getConstant(EltIdx, SL, MVT::i32)); 10400 DCI.AddToWorklist(Elt.getNode()); 10401 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10402 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10403 DCI.AddToWorklist(Srl.getNode()); 10404 10405 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10406 DCI.AddToWorklist(Trunc.getNode()); 10407 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10408 } 10409 10410 return SDValue(); 10411 } 10412 10413 SDValue 10414 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10415 DAGCombinerInfo &DCI) const { 10416 SDValue Vec = N->getOperand(0); 10417 SDValue Idx = N->getOperand(2); 10418 EVT VecVT = Vec.getValueType(); 10419 EVT EltVT = VecVT.getVectorElementType(); 10420 10421 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10422 // => BUILD_VECTOR n x select (e, const-idx) 10423 if (!::shouldExpandVectorDynExt(N)) 10424 return SDValue(); 10425 10426 SelectionDAG &DAG = DCI.DAG; 10427 SDLoc SL(N); 10428 SDValue Ins = N->getOperand(1); 10429 EVT IdxVT = Idx.getValueType(); 10430 10431 SmallVector<SDValue, 16> Ops; 10432 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10433 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10434 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10435 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10436 Ops.push_back(V); 10437 } 10438 10439 return DAG.getBuildVector(VecVT, SL, Ops); 10440 } 10441 10442 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10443 const SDNode *N0, 10444 const SDNode *N1) const { 10445 EVT VT = N0->getValueType(0); 10446 10447 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10448 // support denormals ever. 10449 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10450 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10451 getSubtarget()->hasMadF16())) && 10452 isOperationLegal(ISD::FMAD, VT)) 10453 return ISD::FMAD; 10454 10455 const TargetOptions &Options = DAG.getTarget().Options; 10456 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10457 (N0->getFlags().hasAllowContract() && 10458 N1->getFlags().hasAllowContract())) && 10459 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10460 return ISD::FMA; 10461 } 10462 10463 return 0; 10464 } 10465 10466 // For a reassociatable opcode perform: 10467 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10468 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10469 SelectionDAG &DAG) const { 10470 EVT VT = N->getValueType(0); 10471 if (VT != MVT::i32 && VT != MVT::i64) 10472 return SDValue(); 10473 10474 unsigned Opc = N->getOpcode(); 10475 SDValue Op0 = N->getOperand(0); 10476 SDValue Op1 = N->getOperand(1); 10477 10478 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10479 return SDValue(); 10480 10481 if (Op0->isDivergent()) 10482 std::swap(Op0, Op1); 10483 10484 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10485 return SDValue(); 10486 10487 SDValue Op2 = Op1.getOperand(1); 10488 Op1 = Op1.getOperand(0); 10489 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10490 return SDValue(); 10491 10492 if (Op1->isDivergent()) 10493 std::swap(Op1, Op2); 10494 10495 // If either operand is constant this will conflict with 10496 // DAGCombiner::ReassociateOps(). 10497 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10498 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10499 return SDValue(); 10500 10501 SDLoc SL(N); 10502 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10503 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10504 } 10505 10506 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10507 EVT VT, 10508 SDValue N0, SDValue N1, SDValue N2, 10509 bool Signed) { 10510 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10511 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10512 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10513 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10514 } 10515 10516 SDValue SITargetLowering::performAddCombine(SDNode *N, 10517 DAGCombinerInfo &DCI) const { 10518 SelectionDAG &DAG = DCI.DAG; 10519 EVT VT = N->getValueType(0); 10520 SDLoc SL(N); 10521 SDValue LHS = N->getOperand(0); 10522 SDValue RHS = N->getOperand(1); 10523 10524 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10525 && Subtarget->hasMad64_32() && 10526 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10527 VT.getScalarSizeInBits() <= 64) { 10528 if (LHS.getOpcode() != ISD::MUL) 10529 std::swap(LHS, RHS); 10530 10531 SDValue MulLHS = LHS.getOperand(0); 10532 SDValue MulRHS = LHS.getOperand(1); 10533 SDValue AddRHS = RHS; 10534 10535 // TODO: Maybe restrict if SGPR inputs. 10536 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10537 numBitsUnsigned(MulRHS, DAG) <= 32) { 10538 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10539 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10540 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10541 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10542 } 10543 10544 if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) { 10545 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10546 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10547 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10548 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10549 } 10550 10551 return SDValue(); 10552 } 10553 10554 if (SDValue V = reassociateScalarOps(N, DAG)) { 10555 return V; 10556 } 10557 10558 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10559 return SDValue(); 10560 10561 // add x, zext (setcc) => addcarry x, 0, setcc 10562 // add x, sext (setcc) => subcarry x, 0, setcc 10563 unsigned Opc = LHS.getOpcode(); 10564 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10565 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10566 std::swap(RHS, LHS); 10567 10568 Opc = RHS.getOpcode(); 10569 switch (Opc) { 10570 default: break; 10571 case ISD::ZERO_EXTEND: 10572 case ISD::SIGN_EXTEND: 10573 case ISD::ANY_EXTEND: { 10574 auto Cond = RHS.getOperand(0); 10575 // If this won't be a real VOPC output, we would still need to insert an 10576 // extra instruction anyway. 10577 if (!isBoolSGPR(Cond)) 10578 break; 10579 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10580 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10581 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10582 return DAG.getNode(Opc, SL, VTList, Args); 10583 } 10584 case ISD::ADDCARRY: { 10585 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10586 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10587 if (!C || C->getZExtValue() != 0) break; 10588 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10589 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10590 } 10591 } 10592 return SDValue(); 10593 } 10594 10595 SDValue SITargetLowering::performSubCombine(SDNode *N, 10596 DAGCombinerInfo &DCI) const { 10597 SelectionDAG &DAG = DCI.DAG; 10598 EVT VT = N->getValueType(0); 10599 10600 if (VT != MVT::i32) 10601 return SDValue(); 10602 10603 SDLoc SL(N); 10604 SDValue LHS = N->getOperand(0); 10605 SDValue RHS = N->getOperand(1); 10606 10607 // sub x, zext (setcc) => subcarry x, 0, setcc 10608 // sub x, sext (setcc) => addcarry x, 0, setcc 10609 unsigned Opc = RHS.getOpcode(); 10610 switch (Opc) { 10611 default: break; 10612 case ISD::ZERO_EXTEND: 10613 case ISD::SIGN_EXTEND: 10614 case ISD::ANY_EXTEND: { 10615 auto Cond = RHS.getOperand(0); 10616 // If this won't be a real VOPC output, we would still need to insert an 10617 // extra instruction anyway. 10618 if (!isBoolSGPR(Cond)) 10619 break; 10620 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10621 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10622 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10623 return DAG.getNode(Opc, SL, VTList, Args); 10624 } 10625 } 10626 10627 if (LHS.getOpcode() == ISD::SUBCARRY) { 10628 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10629 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10630 if (!C || !C->isZero()) 10631 return SDValue(); 10632 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10633 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10634 } 10635 return SDValue(); 10636 } 10637 10638 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10639 DAGCombinerInfo &DCI) const { 10640 10641 if (N->getValueType(0) != MVT::i32) 10642 return SDValue(); 10643 10644 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10645 if (!C || C->getZExtValue() != 0) 10646 return SDValue(); 10647 10648 SelectionDAG &DAG = DCI.DAG; 10649 SDValue LHS = N->getOperand(0); 10650 10651 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10652 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10653 unsigned LHSOpc = LHS.getOpcode(); 10654 unsigned Opc = N->getOpcode(); 10655 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10656 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10657 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10658 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10659 } 10660 return SDValue(); 10661 } 10662 10663 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10664 DAGCombinerInfo &DCI) const { 10665 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10666 return SDValue(); 10667 10668 SelectionDAG &DAG = DCI.DAG; 10669 EVT VT = N->getValueType(0); 10670 10671 SDLoc SL(N); 10672 SDValue LHS = N->getOperand(0); 10673 SDValue RHS = N->getOperand(1); 10674 10675 // These should really be instruction patterns, but writing patterns with 10676 // source modiifiers is a pain. 10677 10678 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10679 if (LHS.getOpcode() == ISD::FADD) { 10680 SDValue A = LHS.getOperand(0); 10681 if (A == LHS.getOperand(1)) { 10682 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10683 if (FusedOp != 0) { 10684 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10685 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10686 } 10687 } 10688 } 10689 10690 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10691 if (RHS.getOpcode() == ISD::FADD) { 10692 SDValue A = RHS.getOperand(0); 10693 if (A == RHS.getOperand(1)) { 10694 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10695 if (FusedOp != 0) { 10696 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10697 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10698 } 10699 } 10700 } 10701 10702 return SDValue(); 10703 } 10704 10705 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10706 DAGCombinerInfo &DCI) const { 10707 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10708 return SDValue(); 10709 10710 SelectionDAG &DAG = DCI.DAG; 10711 SDLoc SL(N); 10712 EVT VT = N->getValueType(0); 10713 assert(!VT.isVector()); 10714 10715 // Try to get the fneg to fold into the source modifier. This undoes generic 10716 // DAG combines and folds them into the mad. 10717 // 10718 // Only do this if we are not trying to support denormals. v_mad_f32 does 10719 // not support denormals ever. 10720 SDValue LHS = N->getOperand(0); 10721 SDValue RHS = N->getOperand(1); 10722 if (LHS.getOpcode() == ISD::FADD) { 10723 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10724 SDValue A = LHS.getOperand(0); 10725 if (A == LHS.getOperand(1)) { 10726 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10727 if (FusedOp != 0){ 10728 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10729 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10730 10731 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10732 } 10733 } 10734 } 10735 10736 if (RHS.getOpcode() == ISD::FADD) { 10737 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10738 10739 SDValue A = RHS.getOperand(0); 10740 if (A == RHS.getOperand(1)) { 10741 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10742 if (FusedOp != 0){ 10743 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10744 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10745 } 10746 } 10747 } 10748 10749 return SDValue(); 10750 } 10751 10752 SDValue SITargetLowering::performFMACombine(SDNode *N, 10753 DAGCombinerInfo &DCI) const { 10754 SelectionDAG &DAG = DCI.DAG; 10755 EVT VT = N->getValueType(0); 10756 SDLoc SL(N); 10757 10758 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10759 return SDValue(); 10760 10761 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10762 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10763 SDValue Op1 = N->getOperand(0); 10764 SDValue Op2 = N->getOperand(1); 10765 SDValue FMA = N->getOperand(2); 10766 10767 if (FMA.getOpcode() != ISD::FMA || 10768 Op1.getOpcode() != ISD::FP_EXTEND || 10769 Op2.getOpcode() != ISD::FP_EXTEND) 10770 return SDValue(); 10771 10772 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10773 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10774 // is sufficient to allow generaing fdot2. 10775 const TargetOptions &Options = DAG.getTarget().Options; 10776 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10777 (N->getFlags().hasAllowContract() && 10778 FMA->getFlags().hasAllowContract())) { 10779 Op1 = Op1.getOperand(0); 10780 Op2 = Op2.getOperand(0); 10781 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10782 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10783 return SDValue(); 10784 10785 SDValue Vec1 = Op1.getOperand(0); 10786 SDValue Idx1 = Op1.getOperand(1); 10787 SDValue Vec2 = Op2.getOperand(0); 10788 10789 SDValue FMAOp1 = FMA.getOperand(0); 10790 SDValue FMAOp2 = FMA.getOperand(1); 10791 SDValue FMAAcc = FMA.getOperand(2); 10792 10793 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10794 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10795 return SDValue(); 10796 10797 FMAOp1 = FMAOp1.getOperand(0); 10798 FMAOp2 = FMAOp2.getOperand(0); 10799 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10800 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10801 return SDValue(); 10802 10803 SDValue Vec3 = FMAOp1.getOperand(0); 10804 SDValue Vec4 = FMAOp2.getOperand(0); 10805 SDValue Idx2 = FMAOp1.getOperand(1); 10806 10807 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10808 // Idx1 and Idx2 cannot be the same. 10809 Idx1 == Idx2) 10810 return SDValue(); 10811 10812 if (Vec1 == Vec2 || Vec3 == Vec4) 10813 return SDValue(); 10814 10815 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10816 return SDValue(); 10817 10818 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10819 (Vec1 == Vec4 && Vec2 == Vec3)) { 10820 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10821 DAG.getTargetConstant(0, SL, MVT::i1)); 10822 } 10823 } 10824 return SDValue(); 10825 } 10826 10827 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10828 DAGCombinerInfo &DCI) const { 10829 SelectionDAG &DAG = DCI.DAG; 10830 SDLoc SL(N); 10831 10832 SDValue LHS = N->getOperand(0); 10833 SDValue RHS = N->getOperand(1); 10834 EVT VT = LHS.getValueType(); 10835 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10836 10837 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10838 if (!CRHS) { 10839 CRHS = dyn_cast<ConstantSDNode>(LHS); 10840 if (CRHS) { 10841 std::swap(LHS, RHS); 10842 CC = getSetCCSwappedOperands(CC); 10843 } 10844 } 10845 10846 if (CRHS) { 10847 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10848 isBoolSGPR(LHS.getOperand(0))) { 10849 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10850 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10851 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10852 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10853 if ((CRHS->isAllOnes() && 10854 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10855 (CRHS->isZero() && 10856 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10857 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10858 DAG.getConstant(-1, SL, MVT::i1)); 10859 if ((CRHS->isAllOnes() && 10860 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10861 (CRHS->isZero() && 10862 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10863 return LHS.getOperand(0); 10864 } 10865 10866 const APInt &CRHSVal = CRHS->getAPIntValue(); 10867 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10868 LHS.getOpcode() == ISD::SELECT && 10869 isa<ConstantSDNode>(LHS.getOperand(1)) && 10870 isa<ConstantSDNode>(LHS.getOperand(2)) && 10871 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10872 isBoolSGPR(LHS.getOperand(0))) { 10873 // Given CT != FT: 10874 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10875 // setcc (select cc, CT, CF), CF, ne => cc 10876 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10877 // setcc (select cc, CT, CF), CT, eq => cc 10878 const APInt &CT = LHS.getConstantOperandAPInt(1); 10879 const APInt &CF = LHS.getConstantOperandAPInt(2); 10880 10881 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10882 (CT == CRHSVal && CC == ISD::SETNE)) 10883 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10884 DAG.getConstant(-1, SL, MVT::i1)); 10885 if ((CF == CRHSVal && CC == ISD::SETNE) || 10886 (CT == CRHSVal && CC == ISD::SETEQ)) 10887 return LHS.getOperand(0); 10888 } 10889 } 10890 10891 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10892 VT != MVT::f16)) 10893 return SDValue(); 10894 10895 // Match isinf/isfinite pattern 10896 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10897 // (fcmp one (fabs x), inf) -> (fp_class x, 10898 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10899 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10900 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10901 if (!CRHS) 10902 return SDValue(); 10903 10904 const APFloat &APF = CRHS->getValueAPF(); 10905 if (APF.isInfinity() && !APF.isNegative()) { 10906 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10907 SIInstrFlags::N_INFINITY; 10908 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10909 SIInstrFlags::P_ZERO | 10910 SIInstrFlags::N_NORMAL | 10911 SIInstrFlags::P_NORMAL | 10912 SIInstrFlags::N_SUBNORMAL | 10913 SIInstrFlags::P_SUBNORMAL; 10914 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10915 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10916 DAG.getConstant(Mask, SL, MVT::i32)); 10917 } 10918 } 10919 10920 return SDValue(); 10921 } 10922 10923 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10924 DAGCombinerInfo &DCI) const { 10925 SelectionDAG &DAG = DCI.DAG; 10926 SDLoc SL(N); 10927 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10928 10929 SDValue Src = N->getOperand(0); 10930 SDValue Shift = N->getOperand(0); 10931 10932 // TODO: Extend type shouldn't matter (assuming legal types). 10933 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10934 Shift = Shift.getOperand(0); 10935 10936 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10937 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10938 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10939 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10940 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10941 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10942 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10943 SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0), 10944 SDLoc(Shift.getOperand(0)), MVT::i32); 10945 10946 unsigned ShiftOffset = 8 * Offset; 10947 if (Shift.getOpcode() == ISD::SHL) 10948 ShiftOffset -= C->getZExtValue(); 10949 else 10950 ShiftOffset += C->getZExtValue(); 10951 10952 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10953 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10954 MVT::f32, Shifted); 10955 } 10956 } 10957 } 10958 10959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10960 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10961 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10962 // We simplified Src. If this node is not dead, visit it again so it is 10963 // folded properly. 10964 if (N->getOpcode() != ISD::DELETED_NODE) 10965 DCI.AddToWorklist(N); 10966 return SDValue(N, 0); 10967 } 10968 10969 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10970 if (SDValue DemandedSrc = 10971 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10972 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10973 10974 return SDValue(); 10975 } 10976 10977 SDValue SITargetLowering::performClampCombine(SDNode *N, 10978 DAGCombinerInfo &DCI) const { 10979 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10980 if (!CSrc) 10981 return SDValue(); 10982 10983 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10984 const APFloat &F = CSrc->getValueAPF(); 10985 APFloat Zero = APFloat::getZero(F.getSemantics()); 10986 if (F < Zero || 10987 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10988 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10989 } 10990 10991 APFloat One(F.getSemantics(), "1.0"); 10992 if (F > One) 10993 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10994 10995 return SDValue(CSrc, 0); 10996 } 10997 10998 10999 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 11000 DAGCombinerInfo &DCI) const { 11001 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 11002 return SDValue(); 11003 switch (N->getOpcode()) { 11004 case ISD::ADD: 11005 return performAddCombine(N, DCI); 11006 case ISD::SUB: 11007 return performSubCombine(N, DCI); 11008 case ISD::ADDCARRY: 11009 case ISD::SUBCARRY: 11010 return performAddCarrySubCarryCombine(N, DCI); 11011 case ISD::FADD: 11012 return performFAddCombine(N, DCI); 11013 case ISD::FSUB: 11014 return performFSubCombine(N, DCI); 11015 case ISD::SETCC: 11016 return performSetCCCombine(N, DCI); 11017 case ISD::FMAXNUM: 11018 case ISD::FMINNUM: 11019 case ISD::FMAXNUM_IEEE: 11020 case ISD::FMINNUM_IEEE: 11021 case ISD::SMAX: 11022 case ISD::SMIN: 11023 case ISD::UMAX: 11024 case ISD::UMIN: 11025 case AMDGPUISD::FMIN_LEGACY: 11026 case AMDGPUISD::FMAX_LEGACY: 11027 return performMinMaxCombine(N, DCI); 11028 case ISD::FMA: 11029 return performFMACombine(N, DCI); 11030 case ISD::AND: 11031 return performAndCombine(N, DCI); 11032 case ISD::OR: 11033 return performOrCombine(N, DCI); 11034 case ISD::XOR: 11035 return performXorCombine(N, DCI); 11036 case ISD::ZERO_EXTEND: 11037 return performZeroExtendCombine(N, DCI); 11038 case ISD::SIGN_EXTEND_INREG: 11039 return performSignExtendInRegCombine(N , DCI); 11040 case AMDGPUISD::FP_CLASS: 11041 return performClassCombine(N, DCI); 11042 case ISD::FCANONICALIZE: 11043 return performFCanonicalizeCombine(N, DCI); 11044 case AMDGPUISD::RCP: 11045 return performRcpCombine(N, DCI); 11046 case AMDGPUISD::FRACT: 11047 case AMDGPUISD::RSQ: 11048 case AMDGPUISD::RCP_LEGACY: 11049 case AMDGPUISD::RCP_IFLAG: 11050 case AMDGPUISD::RSQ_CLAMP: 11051 case AMDGPUISD::LDEXP: { 11052 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 11053 SDValue Src = N->getOperand(0); 11054 if (Src.isUndef()) 11055 return Src; 11056 break; 11057 } 11058 case ISD::SINT_TO_FP: 11059 case ISD::UINT_TO_FP: 11060 return performUCharToFloatCombine(N, DCI); 11061 case AMDGPUISD::CVT_F32_UBYTE0: 11062 case AMDGPUISD::CVT_F32_UBYTE1: 11063 case AMDGPUISD::CVT_F32_UBYTE2: 11064 case AMDGPUISD::CVT_F32_UBYTE3: 11065 return performCvtF32UByteNCombine(N, DCI); 11066 case AMDGPUISD::FMED3: 11067 return performFMed3Combine(N, DCI); 11068 case AMDGPUISD::CVT_PKRTZ_F16_F32: 11069 return performCvtPkRTZCombine(N, DCI); 11070 case AMDGPUISD::CLAMP: 11071 return performClampCombine(N, DCI); 11072 case ISD::SCALAR_TO_VECTOR: { 11073 SelectionDAG &DAG = DCI.DAG; 11074 EVT VT = N->getValueType(0); 11075 11076 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 11077 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 11078 SDLoc SL(N); 11079 SDValue Src = N->getOperand(0); 11080 EVT EltVT = Src.getValueType(); 11081 if (EltVT == MVT::f16) 11082 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 11083 11084 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 11085 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 11086 } 11087 11088 break; 11089 } 11090 case ISD::EXTRACT_VECTOR_ELT: 11091 return performExtractVectorEltCombine(N, DCI); 11092 case ISD::INSERT_VECTOR_ELT: 11093 return performInsertVectorEltCombine(N, DCI); 11094 case ISD::LOAD: { 11095 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 11096 return Widended; 11097 LLVM_FALLTHROUGH; 11098 } 11099 default: { 11100 if (!DCI.isBeforeLegalize()) { 11101 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 11102 return performMemSDNodeCombine(MemNode, DCI); 11103 } 11104 11105 break; 11106 } 11107 } 11108 11109 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 11110 } 11111 11112 /// Helper function for adjustWritemask 11113 static unsigned SubIdx2Lane(unsigned Idx) { 11114 switch (Idx) { 11115 default: return ~0u; 11116 case AMDGPU::sub0: return 0; 11117 case AMDGPU::sub1: return 1; 11118 case AMDGPU::sub2: return 2; 11119 case AMDGPU::sub3: return 3; 11120 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 11121 } 11122 } 11123 11124 /// Adjust the writemask of MIMG instructions 11125 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 11126 SelectionDAG &DAG) const { 11127 unsigned Opcode = Node->getMachineOpcode(); 11128 11129 // Subtract 1 because the vdata output is not a MachineSDNode operand. 11130 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 11131 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 11132 return Node; // not implemented for D16 11133 11134 SDNode *Users[5] = { nullptr }; 11135 unsigned Lane = 0; 11136 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 11137 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 11138 unsigned NewDmask = 0; 11139 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 11140 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 11141 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 11142 Node->getConstantOperandVal(LWEIdx)) 11143 ? true 11144 : false; 11145 unsigned TFCLane = 0; 11146 bool HasChain = Node->getNumValues() > 1; 11147 11148 if (OldDmask == 0) { 11149 // These are folded out, but on the chance it happens don't assert. 11150 return Node; 11151 } 11152 11153 unsigned OldBitsSet = countPopulation(OldDmask); 11154 // Work out which is the TFE/LWE lane if that is enabled. 11155 if (UsesTFC) { 11156 TFCLane = OldBitsSet; 11157 } 11158 11159 // Try to figure out the used register components 11160 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 11161 I != E; ++I) { 11162 11163 // Don't look at users of the chain. 11164 if (I.getUse().getResNo() != 0) 11165 continue; 11166 11167 // Abort if we can't understand the usage 11168 if (!I->isMachineOpcode() || 11169 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 11170 return Node; 11171 11172 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 11173 // Note that subregs are packed, i.e. Lane==0 is the first bit set 11174 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 11175 // set, etc. 11176 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 11177 if (Lane == ~0u) 11178 return Node; 11179 11180 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 11181 if (UsesTFC && Lane == TFCLane) { 11182 Users[Lane] = *I; 11183 } else { 11184 // Set which texture component corresponds to the lane. 11185 unsigned Comp; 11186 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 11187 Comp = countTrailingZeros(Dmask); 11188 Dmask &= ~(1 << Comp); 11189 } 11190 11191 // Abort if we have more than one user per component. 11192 if (Users[Lane]) 11193 return Node; 11194 11195 Users[Lane] = *I; 11196 NewDmask |= 1 << Comp; 11197 } 11198 } 11199 11200 // Don't allow 0 dmask, as hardware assumes one channel enabled. 11201 bool NoChannels = !NewDmask; 11202 if (NoChannels) { 11203 if (!UsesTFC) { 11204 // No uses of the result and not using TFC. Then do nothing. 11205 return Node; 11206 } 11207 // If the original dmask has one channel - then nothing to do 11208 if (OldBitsSet == 1) 11209 return Node; 11210 // Use an arbitrary dmask - required for the instruction to work 11211 NewDmask = 1; 11212 } 11213 // Abort if there's no change 11214 if (NewDmask == OldDmask) 11215 return Node; 11216 11217 unsigned BitsSet = countPopulation(NewDmask); 11218 11219 // Check for TFE or LWE - increase the number of channels by one to account 11220 // for the extra return value 11221 // This will need adjustment for D16 if this is also included in 11222 // adjustWriteMask (this function) but at present D16 are excluded. 11223 unsigned NewChannels = BitsSet + UsesTFC; 11224 11225 int NewOpcode = 11226 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 11227 assert(NewOpcode != -1 && 11228 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 11229 "failed to find equivalent MIMG op"); 11230 11231 // Adjust the writemask in the node 11232 SmallVector<SDValue, 12> Ops; 11233 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 11234 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 11235 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 11236 11237 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 11238 11239 MVT ResultVT = NewChannels == 1 ? 11240 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 11241 NewChannels == 5 ? 8 : NewChannels); 11242 SDVTList NewVTList = HasChain ? 11243 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 11244 11245 11246 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 11247 NewVTList, Ops); 11248 11249 if (HasChain) { 11250 // Update chain. 11251 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 11252 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 11253 } 11254 11255 if (NewChannels == 1) { 11256 assert(Node->hasNUsesOfValue(1, 0)); 11257 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 11258 SDLoc(Node), Users[Lane]->getValueType(0), 11259 SDValue(NewNode, 0)); 11260 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 11261 return nullptr; 11262 } 11263 11264 // Update the users of the node with the new indices 11265 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 11266 SDNode *User = Users[i]; 11267 if (!User) { 11268 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11269 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11270 if (i || !NoChannels) 11271 continue; 11272 } else { 11273 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11274 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11275 } 11276 11277 switch (Idx) { 11278 default: break; 11279 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11280 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11281 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11282 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11283 } 11284 } 11285 11286 DAG.RemoveDeadNode(Node); 11287 return nullptr; 11288 } 11289 11290 static bool isFrameIndexOp(SDValue Op) { 11291 if (Op.getOpcode() == ISD::AssertZext) 11292 Op = Op.getOperand(0); 11293 11294 return isa<FrameIndexSDNode>(Op); 11295 } 11296 11297 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11298 /// with frame index operands. 11299 /// LLVM assumes that inputs are to these instructions are registers. 11300 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11301 SelectionDAG &DAG) const { 11302 if (Node->getOpcode() == ISD::CopyToReg) { 11303 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11304 SDValue SrcVal = Node->getOperand(2); 11305 11306 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11307 // to try understanding copies to physical registers. 11308 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11309 SDLoc SL(Node); 11310 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11311 SDValue VReg = DAG.getRegister( 11312 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11313 11314 SDNode *Glued = Node->getGluedNode(); 11315 SDValue ToVReg 11316 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11317 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11318 SDValue ToResultReg 11319 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11320 VReg, ToVReg.getValue(1)); 11321 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11322 DAG.RemoveDeadNode(Node); 11323 return ToResultReg.getNode(); 11324 } 11325 } 11326 11327 SmallVector<SDValue, 8> Ops; 11328 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11329 if (!isFrameIndexOp(Node->getOperand(i))) { 11330 Ops.push_back(Node->getOperand(i)); 11331 continue; 11332 } 11333 11334 SDLoc DL(Node); 11335 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11336 Node->getOperand(i).getValueType(), 11337 Node->getOperand(i)), 0)); 11338 } 11339 11340 return DAG.UpdateNodeOperands(Node, Ops); 11341 } 11342 11343 /// Fold the instructions after selecting them. 11344 /// Returns null if users were already updated. 11345 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11346 SelectionDAG &DAG) const { 11347 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11348 unsigned Opcode = Node->getMachineOpcode(); 11349 11350 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11351 !TII->isGather4(Opcode) && 11352 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11353 return adjustWritemask(Node, DAG); 11354 } 11355 11356 if (Opcode == AMDGPU::INSERT_SUBREG || 11357 Opcode == AMDGPU::REG_SEQUENCE) { 11358 legalizeTargetIndependentNode(Node, DAG); 11359 return Node; 11360 } 11361 11362 switch (Opcode) { 11363 case AMDGPU::V_DIV_SCALE_F32_e64: 11364 case AMDGPU::V_DIV_SCALE_F64_e64: { 11365 // Satisfy the operand register constraint when one of the inputs is 11366 // undefined. Ordinarily each undef value will have its own implicit_def of 11367 // a vreg, so force these to use a single register. 11368 SDValue Src0 = Node->getOperand(1); 11369 SDValue Src1 = Node->getOperand(3); 11370 SDValue Src2 = Node->getOperand(5); 11371 11372 if ((Src0.isMachineOpcode() && 11373 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11374 (Src0 == Src1 || Src0 == Src2)) 11375 break; 11376 11377 MVT VT = Src0.getValueType().getSimpleVT(); 11378 const TargetRegisterClass *RC = 11379 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11380 11381 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11382 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11383 11384 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11385 UndefReg, Src0, SDValue()); 11386 11387 // src0 must be the same register as src1 or src2, even if the value is 11388 // undefined, so make sure we don't violate this constraint. 11389 if (Src0.isMachineOpcode() && 11390 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11391 if (Src1.isMachineOpcode() && 11392 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11393 Src0 = Src1; 11394 else if (Src2.isMachineOpcode() && 11395 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11396 Src0 = Src2; 11397 else { 11398 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11399 Src0 = UndefReg; 11400 Src1 = UndefReg; 11401 } 11402 } else 11403 break; 11404 11405 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11406 Ops[1] = Src0; 11407 Ops[3] = Src1; 11408 Ops[5] = Src2; 11409 Ops.push_back(ImpDef.getValue(1)); 11410 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11411 } 11412 default: 11413 break; 11414 } 11415 11416 return Node; 11417 } 11418 11419 // Any MIMG instructions that use tfe or lwe require an initialization of the 11420 // result register that will be written in the case of a memory access failure. 11421 // The required code is also added to tie this init code to the result of the 11422 // img instruction. 11423 void SITargetLowering::AddIMGInit(MachineInstr &MI) const { 11424 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11425 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 11426 MachineRegisterInfo &MRI = MI.getMF()->getRegInfo(); 11427 MachineBasicBlock &MBB = *MI.getParent(); 11428 11429 MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe); 11430 MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe); 11431 MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16); 11432 11433 if (!TFE && !LWE) // intersect_ray 11434 return; 11435 11436 unsigned TFEVal = TFE ? TFE->getImm() : 0; 11437 unsigned LWEVal = LWE->getImm(); 11438 unsigned D16Val = D16 ? D16->getImm() : 0; 11439 11440 if (!TFEVal && !LWEVal) 11441 return; 11442 11443 // At least one of TFE or LWE are non-zero 11444 // We have to insert a suitable initialization of the result value and 11445 // tie this to the dest of the image instruction. 11446 11447 const DebugLoc &DL = MI.getDebugLoc(); 11448 11449 int DstIdx = 11450 AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata); 11451 11452 // Calculate which dword we have to initialize to 0. 11453 MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask); 11454 11455 // check that dmask operand is found. 11456 assert(MO_Dmask && "Expected dmask operand in instruction"); 11457 11458 unsigned dmask = MO_Dmask->getImm(); 11459 // Determine the number of active lanes taking into account the 11460 // Gather4 special case 11461 unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask); 11462 11463 bool Packed = !Subtarget->hasUnpackedD16VMem(); 11464 11465 unsigned InitIdx = 11466 D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1; 11467 11468 // Abandon attempt if the dst size isn't large enough 11469 // - this is in fact an error but this is picked up elsewhere and 11470 // reported correctly. 11471 uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32; 11472 if (DstSize < InitIdx) 11473 return; 11474 11475 // Create a register for the intialization value. 11476 Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11477 unsigned NewDst = 0; // Final initialized value will be in here 11478 11479 // If PRTStrictNull feature is enabled (the default) then initialize 11480 // all the result registers to 0, otherwise just the error indication 11481 // register (VGPRn+1) 11482 unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1; 11483 unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1); 11484 11485 BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst); 11486 for (; SizeLeft; SizeLeft--, CurrIdx++) { 11487 NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx)); 11488 // Initialize dword 11489 Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 11490 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg) 11491 .addImm(0); 11492 // Insert into the super-reg 11493 BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst) 11494 .addReg(PrevDst) 11495 .addReg(SubReg) 11496 .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx)); 11497 11498 PrevDst = NewDst; 11499 } 11500 11501 // Add as an implicit operand 11502 MI.addOperand(MachineOperand::CreateReg(NewDst, false, true)); 11503 11504 // Tie the just added implicit operand to the dst 11505 MI.tieOperands(DstIdx, MI.getNumOperands() - 1); 11506 } 11507 11508 /// Assign the register class depending on the number of 11509 /// bits set in the writemask 11510 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11511 SDNode *Node) const { 11512 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11513 11514 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11515 11516 if (TII->isVOP3(MI.getOpcode())) { 11517 // Make sure constant bus requirements are respected. 11518 TII->legalizeOperandsVOP3(MRI, MI); 11519 11520 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11521 // This saves a chain-copy of registers and better ballance register 11522 // use between vgpr and agpr as agpr tuples tend to be big. 11523 if (MI.getDesc().OpInfo) { 11524 unsigned Opc = MI.getOpcode(); 11525 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11526 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11527 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11528 if (I == -1) 11529 break; 11530 MachineOperand &Op = MI.getOperand(I); 11531 if (!Op.isReg() || !Op.getReg().isVirtual()) 11532 continue; 11533 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11534 if (!TRI->hasAGPRs(RC)) 11535 continue; 11536 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11537 if (!Src || !Src->isCopy() || 11538 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11539 continue; 11540 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11541 // All uses of agpr64 and agpr32 can also accept vgpr except for 11542 // v_accvgpr_read, but we do not produce agpr reads during selection, 11543 // so no use checks are needed. 11544 MRI.setRegClass(Op.getReg(), NewRC); 11545 } 11546 } 11547 11548 return; 11549 } 11550 11551 // Replace unused atomics with the no return version. 11552 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11553 if (NoRetAtomicOp != -1) { 11554 if (!Node->hasAnyUseOfValue(0)) { 11555 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11556 AMDGPU::OpName::cpol); 11557 if (CPolIdx != -1) { 11558 MachineOperand &CPol = MI.getOperand(CPolIdx); 11559 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11560 } 11561 MI.RemoveOperand(0); 11562 MI.setDesc(TII->get(NoRetAtomicOp)); 11563 return; 11564 } 11565 11566 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11567 // instruction, because the return type of these instructions is a vec2 of 11568 // the memory type, so it can be tied to the input operand. 11569 // This means these instructions always have a use, so we need to add a 11570 // special case to check if the atomic has only one extract_subreg use, 11571 // which itself has no uses. 11572 if ((Node->hasNUsesOfValue(1, 0) && 11573 Node->use_begin()->isMachineOpcode() && 11574 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11575 !Node->use_begin()->hasAnyUseOfValue(0))) { 11576 Register Def = MI.getOperand(0).getReg(); 11577 11578 // Change this into a noret atomic. 11579 MI.setDesc(TII->get(NoRetAtomicOp)); 11580 MI.RemoveOperand(0); 11581 11582 // If we only remove the def operand from the atomic instruction, the 11583 // extract_subreg will be left with a use of a vreg without a def. 11584 // So we need to insert an implicit_def to avoid machine verifier 11585 // errors. 11586 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11587 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11588 } 11589 return; 11590 } 11591 11592 if (TII->isMIMG(MI) && !MI.mayStore()) 11593 AddIMGInit(MI); 11594 } 11595 11596 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11597 uint64_t Val) { 11598 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11599 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11600 } 11601 11602 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11603 const SDLoc &DL, 11604 SDValue Ptr) const { 11605 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11606 11607 // Build the half of the subregister with the constants before building the 11608 // full 128-bit register. If we are building multiple resource descriptors, 11609 // this will allow CSEing of the 2-component register. 11610 const SDValue Ops0[] = { 11611 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11612 buildSMovImm32(DAG, DL, 0), 11613 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11614 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11615 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11616 }; 11617 11618 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11619 MVT::v2i32, Ops0), 0); 11620 11621 // Combine the constants and the pointer. 11622 const SDValue Ops1[] = { 11623 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11624 Ptr, 11625 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11626 SubRegHi, 11627 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11628 }; 11629 11630 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11631 } 11632 11633 /// Return a resource descriptor with the 'Add TID' bit enabled 11634 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11635 /// of the resource descriptor) to create an offset, which is added to 11636 /// the resource pointer. 11637 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11638 SDValue Ptr, uint32_t RsrcDword1, 11639 uint64_t RsrcDword2And3) const { 11640 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11641 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11642 if (RsrcDword1) { 11643 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11644 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11645 0); 11646 } 11647 11648 SDValue DataLo = buildSMovImm32(DAG, DL, 11649 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11650 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11651 11652 const SDValue Ops[] = { 11653 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11654 PtrLo, 11655 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11656 PtrHi, 11657 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11658 DataLo, 11659 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11660 DataHi, 11661 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11662 }; 11663 11664 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11665 } 11666 11667 //===----------------------------------------------------------------------===// 11668 // SI Inline Assembly Support 11669 //===----------------------------------------------------------------------===// 11670 11671 std::pair<unsigned, const TargetRegisterClass *> 11672 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11673 StringRef Constraint, 11674 MVT VT) const { 11675 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11676 11677 const TargetRegisterClass *RC = nullptr; 11678 if (Constraint.size() == 1) { 11679 const unsigned BitWidth = VT.getSizeInBits(); 11680 switch (Constraint[0]) { 11681 default: 11682 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11683 case 's': 11684 case 'r': 11685 switch (BitWidth) { 11686 case 16: 11687 RC = &AMDGPU::SReg_32RegClass; 11688 break; 11689 case 64: 11690 RC = &AMDGPU::SGPR_64RegClass; 11691 break; 11692 default: 11693 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11694 if (!RC) 11695 return std::make_pair(0U, nullptr); 11696 break; 11697 } 11698 break; 11699 case 'v': 11700 switch (BitWidth) { 11701 case 16: 11702 RC = &AMDGPU::VGPR_32RegClass; 11703 break; 11704 default: 11705 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11706 if (!RC) 11707 return std::make_pair(0U, nullptr); 11708 break; 11709 } 11710 break; 11711 case 'a': 11712 if (!Subtarget->hasMAIInsts()) 11713 break; 11714 switch (BitWidth) { 11715 case 16: 11716 RC = &AMDGPU::AGPR_32RegClass; 11717 break; 11718 default: 11719 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11720 if (!RC) 11721 return std::make_pair(0U, nullptr); 11722 break; 11723 } 11724 break; 11725 } 11726 // We actually support i128, i16 and f16 as inline parameters 11727 // even if they are not reported as legal 11728 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11729 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11730 return std::make_pair(0U, RC); 11731 } 11732 11733 if (Constraint.size() > 1) { 11734 if (Constraint[1] == 'v') { 11735 RC = &AMDGPU::VGPR_32RegClass; 11736 } else if (Constraint[1] == 's') { 11737 RC = &AMDGPU::SGPR_32RegClass; 11738 } else if (Constraint[1] == 'a') { 11739 RC = &AMDGPU::AGPR_32RegClass; 11740 } 11741 11742 if (RC) { 11743 uint32_t Idx; 11744 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11745 if (!Failed && Idx < RC->getNumRegs()) 11746 return std::make_pair(RC->getRegister(Idx), RC); 11747 } 11748 } 11749 11750 // FIXME: Returns VS_32 for physical SGPR constraints 11751 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11752 } 11753 11754 static bool isImmConstraint(StringRef Constraint) { 11755 if (Constraint.size() == 1) { 11756 switch (Constraint[0]) { 11757 default: break; 11758 case 'I': 11759 case 'J': 11760 case 'A': 11761 case 'B': 11762 case 'C': 11763 return true; 11764 } 11765 } else if (Constraint == "DA" || 11766 Constraint == "DB") { 11767 return true; 11768 } 11769 return false; 11770 } 11771 11772 SITargetLowering::ConstraintType 11773 SITargetLowering::getConstraintType(StringRef Constraint) const { 11774 if (Constraint.size() == 1) { 11775 switch (Constraint[0]) { 11776 default: break; 11777 case 's': 11778 case 'v': 11779 case 'a': 11780 return C_RegisterClass; 11781 } 11782 } 11783 if (isImmConstraint(Constraint)) { 11784 return C_Other; 11785 } 11786 return TargetLowering::getConstraintType(Constraint); 11787 } 11788 11789 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11790 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11791 Val = Val & maskTrailingOnes<uint64_t>(Size); 11792 } 11793 return Val; 11794 } 11795 11796 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11797 std::string &Constraint, 11798 std::vector<SDValue> &Ops, 11799 SelectionDAG &DAG) const { 11800 if (isImmConstraint(Constraint)) { 11801 uint64_t Val; 11802 if (getAsmOperandConstVal(Op, Val) && 11803 checkAsmConstraintVal(Op, Constraint, Val)) { 11804 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11805 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11806 } 11807 } else { 11808 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11809 } 11810 } 11811 11812 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11813 unsigned Size = Op.getScalarValueSizeInBits(); 11814 if (Size > 64) 11815 return false; 11816 11817 if (Size == 16 && !Subtarget->has16BitInsts()) 11818 return false; 11819 11820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11821 Val = C->getSExtValue(); 11822 return true; 11823 } 11824 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11825 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11826 return true; 11827 } 11828 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11829 if (Size != 16 || Op.getNumOperands() != 2) 11830 return false; 11831 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11832 return false; 11833 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11834 Val = C->getSExtValue(); 11835 return true; 11836 } 11837 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11838 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11839 return true; 11840 } 11841 } 11842 11843 return false; 11844 } 11845 11846 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11847 const std::string &Constraint, 11848 uint64_t Val) const { 11849 if (Constraint.size() == 1) { 11850 switch (Constraint[0]) { 11851 case 'I': 11852 return AMDGPU::isInlinableIntLiteral(Val); 11853 case 'J': 11854 return isInt<16>(Val); 11855 case 'A': 11856 return checkAsmConstraintValA(Op, Val); 11857 case 'B': 11858 return isInt<32>(Val); 11859 case 'C': 11860 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11861 AMDGPU::isInlinableIntLiteral(Val); 11862 default: 11863 break; 11864 } 11865 } else if (Constraint.size() == 2) { 11866 if (Constraint == "DA") { 11867 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11868 int64_t LoBits = static_cast<int32_t>(Val); 11869 return checkAsmConstraintValA(Op, HiBits, 32) && 11870 checkAsmConstraintValA(Op, LoBits, 32); 11871 } 11872 if (Constraint == "DB") { 11873 return true; 11874 } 11875 } 11876 llvm_unreachable("Invalid asm constraint"); 11877 } 11878 11879 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11880 uint64_t Val, 11881 unsigned MaxSize) const { 11882 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11883 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11884 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11885 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11886 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11887 return true; 11888 } 11889 return false; 11890 } 11891 11892 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11893 switch (UnalignedClassID) { 11894 case AMDGPU::VReg_64RegClassID: 11895 return AMDGPU::VReg_64_Align2RegClassID; 11896 case AMDGPU::VReg_96RegClassID: 11897 return AMDGPU::VReg_96_Align2RegClassID; 11898 case AMDGPU::VReg_128RegClassID: 11899 return AMDGPU::VReg_128_Align2RegClassID; 11900 case AMDGPU::VReg_160RegClassID: 11901 return AMDGPU::VReg_160_Align2RegClassID; 11902 case AMDGPU::VReg_192RegClassID: 11903 return AMDGPU::VReg_192_Align2RegClassID; 11904 case AMDGPU::VReg_224RegClassID: 11905 return AMDGPU::VReg_224_Align2RegClassID; 11906 case AMDGPU::VReg_256RegClassID: 11907 return AMDGPU::VReg_256_Align2RegClassID; 11908 case AMDGPU::VReg_512RegClassID: 11909 return AMDGPU::VReg_512_Align2RegClassID; 11910 case AMDGPU::VReg_1024RegClassID: 11911 return AMDGPU::VReg_1024_Align2RegClassID; 11912 case AMDGPU::AReg_64RegClassID: 11913 return AMDGPU::AReg_64_Align2RegClassID; 11914 case AMDGPU::AReg_96RegClassID: 11915 return AMDGPU::AReg_96_Align2RegClassID; 11916 case AMDGPU::AReg_128RegClassID: 11917 return AMDGPU::AReg_128_Align2RegClassID; 11918 case AMDGPU::AReg_160RegClassID: 11919 return AMDGPU::AReg_160_Align2RegClassID; 11920 case AMDGPU::AReg_192RegClassID: 11921 return AMDGPU::AReg_192_Align2RegClassID; 11922 case AMDGPU::AReg_256RegClassID: 11923 return AMDGPU::AReg_256_Align2RegClassID; 11924 case AMDGPU::AReg_512RegClassID: 11925 return AMDGPU::AReg_512_Align2RegClassID; 11926 case AMDGPU::AReg_1024RegClassID: 11927 return AMDGPU::AReg_1024_Align2RegClassID; 11928 default: 11929 return -1; 11930 } 11931 } 11932 11933 // Figure out which registers should be reserved for stack access. Only after 11934 // the function is legalized do we know all of the non-spill stack objects or if 11935 // calls are present. 11936 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11937 MachineRegisterInfo &MRI = MF.getRegInfo(); 11938 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11939 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11940 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11941 const SIInstrInfo *TII = ST.getInstrInfo(); 11942 11943 if (Info->isEntryFunction()) { 11944 // Callable functions have fixed registers used for stack access. 11945 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11946 } 11947 11948 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11949 Info->getStackPtrOffsetReg())); 11950 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11951 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11952 11953 // We need to worry about replacing the default register with itself in case 11954 // of MIR testcases missing the MFI. 11955 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11956 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11957 11958 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11959 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11960 11961 Info->limitOccupancy(MF); 11962 11963 if (ST.isWave32() && !MF.empty()) { 11964 for (auto &MBB : MF) { 11965 for (auto &MI : MBB) { 11966 TII->fixImplicitOperands(MI); 11967 } 11968 } 11969 } 11970 11971 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11972 // classes if required. Ideally the register class constraints would differ 11973 // per-subtarget, but there's no easy way to achieve that right now. This is 11974 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11975 // from using them as the register class for legal types. 11976 if (ST.needsAlignedVGPRs()) { 11977 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11978 const Register Reg = Register::index2VirtReg(I); 11979 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11980 if (!RC) 11981 continue; 11982 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11983 if (NewClassID != -1) 11984 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11985 } 11986 } 11987 11988 TargetLoweringBase::finalizeLowering(MF); 11989 } 11990 11991 void SITargetLowering::computeKnownBitsForFrameIndex( 11992 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11993 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11994 11995 // Set the high bits to zero based on the maximum allowed scratch size per 11996 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11997 // calculation won't overflow, so assume the sign bit is never set. 11998 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11999 } 12000 12001 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 12002 KnownBits &Known, unsigned Dim) { 12003 unsigned MaxValue = 12004 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 12005 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 12006 } 12007 12008 void SITargetLowering::computeKnownBitsForTargetInstr( 12009 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 12010 const MachineRegisterInfo &MRI, unsigned Depth) const { 12011 const MachineInstr *MI = MRI.getVRegDef(R); 12012 switch (MI->getOpcode()) { 12013 case AMDGPU::G_INTRINSIC: { 12014 switch (MI->getIntrinsicID()) { 12015 case Intrinsic::amdgcn_workitem_id_x: 12016 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 12017 break; 12018 case Intrinsic::amdgcn_workitem_id_y: 12019 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 12020 break; 12021 case Intrinsic::amdgcn_workitem_id_z: 12022 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 12023 break; 12024 case Intrinsic::amdgcn_mbcnt_lo: 12025 case Intrinsic::amdgcn_mbcnt_hi: { 12026 // These return at most the wavefront size - 1. 12027 unsigned Size = MRI.getType(R).getSizeInBits(); 12028 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 12029 break; 12030 } 12031 case Intrinsic::amdgcn_groupstaticsize: { 12032 // We can report everything over the maximum size as 0. We can't report 12033 // based on the actual size because we don't know if it's accurate or not 12034 // at any given point. 12035 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 12036 break; 12037 } 12038 } 12039 break; 12040 } 12041 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 12042 Known.Zero.setHighBits(24); 12043 break; 12044 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 12045 Known.Zero.setHighBits(16); 12046 break; 12047 } 12048 } 12049 12050 Align SITargetLowering::computeKnownAlignForTargetInstr( 12051 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 12052 unsigned Depth) const { 12053 const MachineInstr *MI = MRI.getVRegDef(R); 12054 switch (MI->getOpcode()) { 12055 case AMDGPU::G_INTRINSIC: 12056 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 12057 // FIXME: Can this move to generic code? What about the case where the call 12058 // site specifies a lower alignment? 12059 Intrinsic::ID IID = MI->getIntrinsicID(); 12060 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 12061 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 12062 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 12063 return *RetAlign; 12064 return Align(1); 12065 } 12066 default: 12067 return Align(1); 12068 } 12069 } 12070 12071 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 12072 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 12073 const Align CacheLineAlign = Align(64); 12074 12075 // Pre-GFX10 target did not benefit from loop alignment 12076 if (!ML || DisableLoopAlignment || 12077 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 12078 getSubtarget()->hasInstFwdPrefetchBug()) 12079 return PrefAlign; 12080 12081 // On GFX10 I$ is 4 x 64 bytes cache lines. 12082 // By default prefetcher keeps one cache line behind and reads two ahead. 12083 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 12084 // behind and one ahead. 12085 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 12086 // If loop fits 64 bytes it always spans no more than two cache lines and 12087 // does not need an alignment. 12088 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 12089 // Else if loop is less or equal 192 bytes we need two lines behind. 12090 12091 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 12092 const MachineBasicBlock *Header = ML->getHeader(); 12093 if (Header->getAlignment() != PrefAlign) 12094 return Header->getAlignment(); // Already processed. 12095 12096 unsigned LoopSize = 0; 12097 for (const MachineBasicBlock *MBB : ML->blocks()) { 12098 // If inner loop block is aligned assume in average half of the alignment 12099 // size to be added as nops. 12100 if (MBB != Header) 12101 LoopSize += MBB->getAlignment().value() / 2; 12102 12103 for (const MachineInstr &MI : *MBB) { 12104 LoopSize += TII->getInstSizeInBytes(MI); 12105 if (LoopSize > 192) 12106 return PrefAlign; 12107 } 12108 } 12109 12110 if (LoopSize <= 64) 12111 return PrefAlign; 12112 12113 if (LoopSize <= 128) 12114 return CacheLineAlign; 12115 12116 // If any of parent loops is surrounded by prefetch instructions do not 12117 // insert new for inner loop, which would reset parent's settings. 12118 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 12119 if (MachineBasicBlock *Exit = P->getExitBlock()) { 12120 auto I = Exit->getFirstNonDebugInstr(); 12121 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 12122 return CacheLineAlign; 12123 } 12124 } 12125 12126 MachineBasicBlock *Pre = ML->getLoopPreheader(); 12127 MachineBasicBlock *Exit = ML->getExitBlock(); 12128 12129 if (Pre && Exit) { 12130 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 12131 TII->get(AMDGPU::S_INST_PREFETCH)) 12132 .addImm(1); // prefetch 2 lines behind PC 12133 12134 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 12135 TII->get(AMDGPU::S_INST_PREFETCH)) 12136 .addImm(2); // prefetch 1 line behind PC 12137 } 12138 12139 return CacheLineAlign; 12140 } 12141 12142 LLVM_ATTRIBUTE_UNUSED 12143 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 12144 assert(N->getOpcode() == ISD::CopyFromReg); 12145 do { 12146 // Follow the chain until we find an INLINEASM node. 12147 N = N->getOperand(0).getNode(); 12148 if (N->getOpcode() == ISD::INLINEASM || 12149 N->getOpcode() == ISD::INLINEASM_BR) 12150 return true; 12151 } while (N->getOpcode() == ISD::CopyFromReg); 12152 return false; 12153 } 12154 12155 bool SITargetLowering::isSDNodeSourceOfDivergence( 12156 const SDNode *N, FunctionLoweringInfo *FLI, 12157 LegacyDivergenceAnalysis *KDA) const { 12158 switch (N->getOpcode()) { 12159 case ISD::CopyFromReg: { 12160 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 12161 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 12162 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12163 Register Reg = R->getReg(); 12164 12165 // FIXME: Why does this need to consider isLiveIn? 12166 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 12167 return !TRI->isSGPRReg(MRI, Reg); 12168 12169 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 12170 return KDA->isDivergent(V); 12171 12172 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 12173 return !TRI->isSGPRReg(MRI, Reg); 12174 } 12175 case ISD::LOAD: { 12176 const LoadSDNode *L = cast<LoadSDNode>(N); 12177 unsigned AS = L->getAddressSpace(); 12178 // A flat load may access private memory. 12179 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 12180 } 12181 case ISD::CALLSEQ_END: 12182 return true; 12183 case ISD::INTRINSIC_WO_CHAIN: 12184 return AMDGPU::isIntrinsicSourceOfDivergence( 12185 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 12186 case ISD::INTRINSIC_W_CHAIN: 12187 return AMDGPU::isIntrinsicSourceOfDivergence( 12188 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 12189 case AMDGPUISD::ATOMIC_CMP_SWAP: 12190 case AMDGPUISD::ATOMIC_INC: 12191 case AMDGPUISD::ATOMIC_DEC: 12192 case AMDGPUISD::ATOMIC_LOAD_FMIN: 12193 case AMDGPUISD::ATOMIC_LOAD_FMAX: 12194 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 12195 case AMDGPUISD::BUFFER_ATOMIC_ADD: 12196 case AMDGPUISD::BUFFER_ATOMIC_SUB: 12197 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 12198 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 12199 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 12200 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 12201 case AMDGPUISD::BUFFER_ATOMIC_AND: 12202 case AMDGPUISD::BUFFER_ATOMIC_OR: 12203 case AMDGPUISD::BUFFER_ATOMIC_XOR: 12204 case AMDGPUISD::BUFFER_ATOMIC_INC: 12205 case AMDGPUISD::BUFFER_ATOMIC_DEC: 12206 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 12207 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 12208 case AMDGPUISD::BUFFER_ATOMIC_FADD: 12209 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 12210 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 12211 // Target-specific read-modify-write atomics are sources of divergence. 12212 return true; 12213 default: 12214 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 12215 // Generic read-modify-write atomics are sources of divergence. 12216 return A->readMem() && A->writeMem(); 12217 } 12218 return false; 12219 } 12220 } 12221 12222 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 12223 EVT VT) const { 12224 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 12225 case MVT::f32: 12226 return hasFP32Denormals(DAG.getMachineFunction()); 12227 case MVT::f64: 12228 case MVT::f16: 12229 return hasFP64FP16Denormals(DAG.getMachineFunction()); 12230 default: 12231 return false; 12232 } 12233 } 12234 12235 bool SITargetLowering::denormalsEnabledForType(LLT Ty, 12236 MachineFunction &MF) const { 12237 switch (Ty.getScalarSizeInBits()) { 12238 case 32: 12239 return hasFP32Denormals(MF); 12240 case 64: 12241 case 16: 12242 return hasFP64FP16Denormals(MF); 12243 default: 12244 return false; 12245 } 12246 } 12247 12248 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 12249 const SelectionDAG &DAG, 12250 bool SNaN, 12251 unsigned Depth) const { 12252 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 12253 const MachineFunction &MF = DAG.getMachineFunction(); 12254 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 12255 12256 if (Info->getMode().DX10Clamp) 12257 return true; // Clamped to 0. 12258 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 12259 } 12260 12261 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 12262 SNaN, Depth); 12263 } 12264 12265 // Global FP atomic instructions have a hardcoded FP mode and do not support 12266 // FP32 denormals, and only support v2f16 denormals. 12267 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 12268 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 12269 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 12270 if (&Flt == &APFloat::IEEEsingle()) 12271 return DenormMode == DenormalMode::getPreserveSign(); 12272 return DenormMode == DenormalMode::getIEEE(); 12273 } 12274 12275 TargetLowering::AtomicExpansionKind 12276 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 12277 12278 auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) { 12279 OptimizationRemarkEmitter ORE(RMW->getFunction()); 12280 LLVMContext &Ctx = RMW->getFunction()->getContext(); 12281 SmallVector<StringRef> SSNs; 12282 Ctx.getSyncScopeNames(SSNs); 12283 auto MemScope = SSNs[RMW->getSyncScopeID()].empty() 12284 ? "system" 12285 : SSNs[RMW->getSyncScopeID()]; 12286 ORE.emit([&]() { 12287 return OptimizationRemark(DEBUG_TYPE, "Passed", RMW) 12288 << "Hardware instruction generated for atomic " 12289 << RMW->getOperationName(RMW->getOperation()) 12290 << " operation at memory scope " << MemScope 12291 << " due to an unsafe request."; 12292 }); 12293 return Kind; 12294 }; 12295 12296 switch (RMW->getOperation()) { 12297 case AtomicRMWInst::FAdd: { 12298 Type *Ty = RMW->getType(); 12299 12300 // We don't have a way to support 16-bit atomics now, so just leave them 12301 // as-is. 12302 if (Ty->isHalfTy()) 12303 return AtomicExpansionKind::None; 12304 12305 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 12306 return AtomicExpansionKind::CmpXChg; 12307 12308 unsigned AS = RMW->getPointerAddressSpace(); 12309 12310 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 12311 Subtarget->hasAtomicFaddInsts()) { 12312 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe 12313 // floating point atomic instructions. May generate more efficient code, 12314 // but may not respect rounding and denormal modes, and may give incorrect 12315 // results for certain memory destinations. 12316 if (RMW->getFunction() 12317 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12318 .getValueAsString() != "true") 12319 return AtomicExpansionKind::CmpXChg; 12320 12321 if (Subtarget->hasGFX90AInsts()) { 12322 if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) 12323 return AtomicExpansionKind::CmpXChg; 12324 12325 auto SSID = RMW->getSyncScopeID(); 12326 if (SSID == SyncScope::System || 12327 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 12328 return AtomicExpansionKind::CmpXChg; 12329 12330 return ReportUnsafeHWInst(AtomicExpansionKind::None); 12331 } 12332 12333 if (AS == AMDGPUAS::FLAT_ADDRESS) 12334 return AtomicExpansionKind::CmpXChg; 12335 12336 return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12337 : AtomicExpansionKind::CmpXChg; 12338 } 12339 12340 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 12341 // to round-to-nearest-even. 12342 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 12343 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) { 12344 if (!Ty->isDoubleTy()) 12345 return AtomicExpansionKind::None; 12346 12347 if (fpModeMatchesGlobalFPAtomicMode(RMW)) 12348 return AtomicExpansionKind::None; 12349 12350 return RMW->getFunction() 12351 ->getFnAttribute("amdgpu-unsafe-fp-atomics") 12352 .getValueAsString() == "true" 12353 ? ReportUnsafeHWInst(AtomicExpansionKind::None) 12354 : AtomicExpansionKind::CmpXChg; 12355 } 12356 12357 return AtomicExpansionKind::CmpXChg; 12358 } 12359 default: 12360 break; 12361 } 12362 12363 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 12364 } 12365 12366 const TargetRegisterClass * 12367 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 12368 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 12369 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 12370 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 12371 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 12372 : &AMDGPU::SReg_32RegClass; 12373 if (!TRI->isSGPRClass(RC) && !isDivergent) 12374 return TRI->getEquivalentSGPRClass(RC); 12375 else if (TRI->isSGPRClass(RC) && isDivergent) 12376 return TRI->getEquivalentVGPRClass(RC); 12377 12378 return RC; 12379 } 12380 12381 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 12382 // uniform values (as produced by the mask results of control flow intrinsics) 12383 // used outside of divergent blocks. The phi users need to also be treated as 12384 // always uniform. 12385 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 12386 unsigned WaveSize) { 12387 // FIXME: We asssume we never cast the mask results of a control flow 12388 // intrinsic. 12389 // Early exit if the type won't be consistent as a compile time hack. 12390 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 12391 if (!IT || IT->getBitWidth() != WaveSize) 12392 return false; 12393 12394 if (!isa<Instruction>(V)) 12395 return false; 12396 if (!Visited.insert(V).second) 12397 return false; 12398 bool Result = false; 12399 for (auto U : V->users()) { 12400 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12401 if (V == U->getOperand(1)) { 12402 switch (Intrinsic->getIntrinsicID()) { 12403 default: 12404 Result = false; 12405 break; 12406 case Intrinsic::amdgcn_if_break: 12407 case Intrinsic::amdgcn_if: 12408 case Intrinsic::amdgcn_else: 12409 Result = true; 12410 break; 12411 } 12412 } 12413 if (V == U->getOperand(0)) { 12414 switch (Intrinsic->getIntrinsicID()) { 12415 default: 12416 Result = false; 12417 break; 12418 case Intrinsic::amdgcn_end_cf: 12419 case Intrinsic::amdgcn_loop: 12420 Result = true; 12421 break; 12422 } 12423 } 12424 } else { 12425 Result = hasCFUser(U, Visited, WaveSize); 12426 } 12427 if (Result) 12428 break; 12429 } 12430 return Result; 12431 } 12432 12433 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12434 const Value *V) const { 12435 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12436 if (CI->isInlineAsm()) { 12437 // FIXME: This cannot give a correct answer. This should only trigger in 12438 // the case where inline asm returns mixed SGPR and VGPR results, used 12439 // outside the defining block. We don't have a specific result to 12440 // consider, so this assumes if any value is SGPR, the overall register 12441 // also needs to be SGPR. 12442 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12443 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12444 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12445 for (auto &TC : TargetConstraints) { 12446 if (TC.Type == InlineAsm::isOutput) { 12447 ComputeConstraintToUse(TC, SDValue()); 12448 unsigned AssignedReg; 12449 const TargetRegisterClass *RC; 12450 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12451 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12452 if (RC) { 12453 MachineRegisterInfo &MRI = MF.getRegInfo(); 12454 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12455 return true; 12456 else if (SIRI->isSGPRClass(RC)) 12457 return true; 12458 } 12459 } 12460 } 12461 } 12462 } 12463 SmallPtrSet<const Value *, 16> Visited; 12464 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12465 } 12466 12467 std::pair<InstructionCost, MVT> 12468 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12469 Type *Ty) const { 12470 std::pair<InstructionCost, MVT> Cost = 12471 TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12472 auto Size = DL.getTypeSizeInBits(Ty); 12473 // Maximum load or store can handle 8 dwords for scalar and 4 for 12474 // vector ALU. Let's assume anything above 8 dwords is expensive 12475 // even if legal. 12476 if (Size <= 256) 12477 return Cost; 12478 12479 Cost.first += (Size + 255) / 256; 12480 return Cost; 12481 } 12482