1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
20 #include "SIISelLowering.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/MachineValueType.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Target/TargetOptions.h"
88 #define DEBUG_TYPE "si-lower"
90 STATISTIC(NumTailCalls, "Number of tail calls");
92 static cl::opt<bool> EnableVGPRIndexMode(
93 "amdgpu-vgpr-index-mode",
94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
97 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
98 "amdgpu-frame-index-zero-bits",
99 cl::desc("High bits of frame index assumed to be zero"),
103 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107 return AMDGPU::SGPR0 + Reg;
110 llvm_unreachable("Cannot allocate sgpr");
113 SITargetLowering::SITargetLowering(const TargetMachine &TM,
114 const SISubtarget &STI)
115 : AMDGPUTargetLowering(TM, STI) {
116 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
117 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
119 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
120 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
122 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
123 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
124 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
126 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
127 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
129 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
130 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
132 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
133 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
135 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
136 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
138 if (Subtarget->has16BitInsts()) {
139 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
140 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
143 if (Subtarget->hasVOP3PInsts()) {
144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
148 computeRegisterProperties(STI.getRegisterInfo());
150 // We need to custom lower vector stores from local memory
151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
155 setOperationAction(ISD::LOAD, MVT::i1, Custom);
157 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
158 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
159 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
160 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
161 setOperationAction(ISD::STORE, MVT::i1, Custom);
163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
178 setOperationAction(ISD::SELECT, MVT::i1, Promote);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f64, Promote);
181 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
183 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
184 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
185 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
186 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189 setOperationAction(ISD::SETCC, MVT::i1, Promote);
190 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
191 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
192 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
194 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
195 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
210 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
212 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
213 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
214 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
216 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
217 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
218 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
219 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
220 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
221 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
223 setOperationAction(ISD::UADDO, MVT::i32, Legal);
224 setOperationAction(ISD::USUBO, MVT::i32, Legal);
226 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
227 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
230 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
231 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
234 //setOperationAction(ISD::ADDC, MVT::i64, Expand);
235 //setOperationAction(ISD::SUBC, MVT::i64, Expand);
237 // We only support LOAD/STORE and vector manipulation ops for vectors
238 // with > 4 elements.
239 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
240 MVT::v2i64, MVT::v2f64}) {
241 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245 case ISD::BUILD_VECTOR:
247 case ISD::EXTRACT_VECTOR_ELT:
248 case ISD::INSERT_VECTOR_ELT:
249 case ISD::INSERT_SUBVECTOR:
250 case ISD::EXTRACT_SUBVECTOR:
251 case ISD::SCALAR_TO_VECTOR:
253 case ISD::CONCAT_VECTORS:
254 setOperationAction(Op, VT, Custom);
257 setOperationAction(Op, VT, Expand);
263 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
264 // is expanded to avoid having two separate loops in case the index is a VGPR.
266 // Most operations are naturally 32-bit vector operations. We only support
267 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
268 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
269 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
270 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
272 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
273 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
275 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
276 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
278 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
279 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
282 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
283 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
284 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
285 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
287 // Avoid stack access for these.
288 // TODO: Generalize to more vector types.
289 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
290 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
291 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
292 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
294 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
295 // and output demarshalling
296 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
297 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
299 // We can't return success/failure, only the old value,
300 // let LLVM add the comparison
301 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
302 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
304 if (getSubtarget()->hasFlatAddressSpace()) {
305 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
306 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
309 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
310 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
312 // On SI this is s_memtime and s_memrealtime on VI.
313 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
314 setOperationAction(ISD::TRAP, MVT::Other, Custom);
315 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
317 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
318 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
320 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
321 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
322 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
323 setOperationAction(ISD::FRINT, MVT::f64, Legal);
326 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
328 setOperationAction(ISD::FSIN, MVT::f32, Custom);
329 setOperationAction(ISD::FCOS, MVT::f32, Custom);
330 setOperationAction(ISD::FDIV, MVT::f32, Custom);
331 setOperationAction(ISD::FDIV, MVT::f64, Custom);
333 if (Subtarget->has16BitInsts()) {
334 setOperationAction(ISD::Constant, MVT::i16, Legal);
336 setOperationAction(ISD::SMIN, MVT::i16, Legal);
337 setOperationAction(ISD::SMAX, MVT::i16, Legal);
339 setOperationAction(ISD::UMIN, MVT::i16, Legal);
340 setOperationAction(ISD::UMAX, MVT::i16, Legal);
342 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
343 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
345 setOperationAction(ISD::ROTR, MVT::i16, Promote);
346 setOperationAction(ISD::ROTL, MVT::i16, Promote);
348 setOperationAction(ISD::SDIV, MVT::i16, Promote);
349 setOperationAction(ISD::UDIV, MVT::i16, Promote);
350 setOperationAction(ISD::SREM, MVT::i16, Promote);
351 setOperationAction(ISD::UREM, MVT::i16, Promote);
353 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
354 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
356 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
357 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
358 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
361 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
363 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
365 setOperationAction(ISD::LOAD, MVT::i16, Custom);
367 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
369 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
370 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
371 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
372 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
374 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
379 // F16 - Constant Actions.
380 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
382 // F16 - Load/Store Actions.
383 setOperationAction(ISD::LOAD, MVT::f16, Promote);
384 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
385 setOperationAction(ISD::STORE, MVT::f16, Promote);
386 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
388 // F16 - VOP1 Actions.
389 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
390 setOperationAction(ISD::FCOS, MVT::f16, Promote);
391 setOperationAction(ISD::FSIN, MVT::f16, Promote);
392 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
393 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
394 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
395 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
396 setOperationAction(ISD::FROUND, MVT::f16, Custom);
398 // F16 - VOP2 Actions.
399 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
400 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
401 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
402 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
403 setOperationAction(ISD::FDIV, MVT::f16, Custom);
405 // F16 - VOP3 Actions.
406 setOperationAction(ISD::FMA, MVT::f16, Legal);
407 if (!Subtarget->hasFP16Denormals())
408 setOperationAction(ISD::FMAD, MVT::f16, Legal);
411 if (Subtarget->hasVOP3PInsts()) {
412 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
413 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
417 case ISD::BUILD_VECTOR:
419 case ISD::EXTRACT_VECTOR_ELT:
420 case ISD::INSERT_VECTOR_ELT:
421 case ISD::INSERT_SUBVECTOR:
422 case ISD::EXTRACT_SUBVECTOR:
423 case ISD::SCALAR_TO_VECTOR:
425 case ISD::CONCAT_VECTORS:
426 setOperationAction(Op, VT, Custom);
429 setOperationAction(Op, VT, Expand);
435 // XXX - Do these do anything? Vector constants turn into build_vector.
436 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
437 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
439 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
440 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
441 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
442 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
444 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
445 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
446 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
447 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
449 setOperationAction(ISD::AND, MVT::v2i16, Promote);
450 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
451 setOperationAction(ISD::OR, MVT::v2i16, Promote);
452 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
453 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
454 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
455 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
456 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
457 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
458 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
460 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
461 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
462 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
463 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
464 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
465 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
466 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
467 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
468 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
469 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
471 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
472 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
473 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
474 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
475 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
476 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
478 // This isn't really legal, but this avoids the legalizer unrolling it (and
479 // allows matching fneg (fabs x) patterns)
480 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
482 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
483 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
485 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
486 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
487 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
488 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
490 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
491 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
494 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
495 setOperationAction(ISD::SELECT, VT, Custom);
498 setTargetDAGCombine(ISD::ADD);
499 setTargetDAGCombine(ISD::ADDCARRY);
500 setTargetDAGCombine(ISD::SUB);
501 setTargetDAGCombine(ISD::SUBCARRY);
502 setTargetDAGCombine(ISD::FADD);
503 setTargetDAGCombine(ISD::FSUB);
504 setTargetDAGCombine(ISD::FMINNUM);
505 setTargetDAGCombine(ISD::FMAXNUM);
506 setTargetDAGCombine(ISD::SMIN);
507 setTargetDAGCombine(ISD::SMAX);
508 setTargetDAGCombine(ISD::UMIN);
509 setTargetDAGCombine(ISD::UMAX);
510 setTargetDAGCombine(ISD::SETCC);
511 setTargetDAGCombine(ISD::AND);
512 setTargetDAGCombine(ISD::OR);
513 setTargetDAGCombine(ISD::XOR);
514 setTargetDAGCombine(ISD::SINT_TO_FP);
515 setTargetDAGCombine(ISD::UINT_TO_FP);
516 setTargetDAGCombine(ISD::FCANONICALIZE);
517 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
518 setTargetDAGCombine(ISD::ZERO_EXTEND);
519 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
520 setTargetDAGCombine(ISD::BUILD_VECTOR);
522 // All memory operations. Some folding on the pointer operand is done to help
523 // matching the constant offsets in the addressing modes.
524 setTargetDAGCombine(ISD::LOAD);
525 setTargetDAGCombine(ISD::STORE);
526 setTargetDAGCombine(ISD::ATOMIC_LOAD);
527 setTargetDAGCombine(ISD::ATOMIC_STORE);
528 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
529 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
530 setTargetDAGCombine(ISD::ATOMIC_SWAP);
531 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
532 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
533 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
534 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
535 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
536 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
537 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
538 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
539 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
540 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
542 setSchedulingPreference(Sched::RegPressure);
545 const SISubtarget *SITargetLowering::getSubtarget() const {
546 return static_cast<const SISubtarget *>(Subtarget);
549 //===----------------------------------------------------------------------===//
550 // TargetLowering queries
551 //===----------------------------------------------------------------------===//
553 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
554 // SI has some legal vector types, but no legal vector operations. Say no
555 // shuffles are legal in order to prefer scalarizing some vector operations.
559 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
562 unsigned IntrID) const {
564 case Intrinsic::amdgcn_atomic_inc:
565 case Intrinsic::amdgcn_atomic_dec: {
566 Info.opc = ISD::INTRINSIC_W_CHAIN;
567 Info.memVT = MVT::getVT(CI.getType());
568 Info.ptrVal = CI.getOperand(0);
570 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
572 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
573 if (!Vol || !Vol->isZero())
574 Info.flags |= MachineMemOperand::MOVolatile;
583 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
584 SmallVectorImpl<Value*> &Ops,
585 Type *&AccessTy) const {
586 switch (II->getIntrinsicID()) {
587 case Intrinsic::amdgcn_atomic_inc:
588 case Intrinsic::amdgcn_atomic_dec: {
589 Value *Ptr = II->getArgOperand(0);
590 AccessTy = II->getType();
599 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
600 if (!Subtarget->hasFlatInstOffsets()) {
601 // Flat instructions do not have offsets, and only have the register
603 return AM.BaseOffs == 0 && AM.Scale == 0;
606 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
607 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
610 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
613 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
614 if (Subtarget->hasFlatGlobalInsts())
615 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
617 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
618 // Assume the we will use FLAT for all global memory accesses
620 // FIXME: This assumption is currently wrong. On VI we still use
621 // MUBUF instructions for the r + i addressing mode. As currently
622 // implemented, the MUBUF instructions only work on buffer < 4GB.
623 // It may be possible to support > 4GB buffers with MUBUF instructions,
624 // by setting the stride value in the resource descriptor which would
625 // increase the size limit to (stride * 4GB). However, this is risky,
626 // because it has never been validated.
627 return isLegalFlatAddressingMode(AM);
630 return isLegalMUBUFAddressingMode(AM);
633 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
634 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
635 // additionally can do r + r + i with addr64. 32-bit has more addressing
636 // mode options. Depending on the resource constant, it can also do
637 // (i64 r0) + (i32 r1) * (i14 i).
639 // Private arrays end up using a scratch buffer most of the time, so also
640 // assume those use MUBUF instructions. Scratch loads / stores are currently
641 // implemented as mubuf instructions with offen bit set, so slightly
642 // different than the normal addr64.
643 if (!isUInt<12>(AM.BaseOffs))
646 // FIXME: Since we can split immediate into soffset and immediate offset,
647 // would it make sense to allow any immediate?
650 case 0: // r + i or just i, depending on HasBaseReg.
653 return true; // We have r + r or r + i.
660 // Allow 2 * r as r + r
661 // Or 2 * r + i is allowed as r + r + i.
663 default: // Don't allow n * r
668 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
669 const AddrMode &AM, Type *Ty,
670 unsigned AS, Instruction *I) const {
671 // No global is ever allowed as a base.
675 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
676 return isLegalGlobalAddressingMode(AM);
678 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
679 // If the offset isn't a multiple of 4, it probably isn't going to be
680 // correctly aligned.
681 // FIXME: Can we get the real alignment here?
682 if (AM.BaseOffs % 4 != 0)
683 return isLegalMUBUFAddressingMode(AM);
685 // There are no SMRD extloads, so if we have to do a small type access we
686 // will use a MUBUF load.
687 // FIXME?: We also need to do this if unaligned, but we don't know the
689 if (DL.getTypeStoreSize(Ty) < 4)
690 return isLegalGlobalAddressingMode(AM);
692 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
693 // SMRD instructions have an 8-bit, dword offset on SI.
694 if (!isUInt<8>(AM.BaseOffs / 4))
696 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
697 // On CI+, this can also be a 32-bit literal constant offset. If it fits
698 // in 8-bits, it can use a smaller encoding.
699 if (!isUInt<32>(AM.BaseOffs / 4))
701 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
702 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
703 if (!isUInt<20>(AM.BaseOffs))
706 llvm_unreachable("unhandled generation");
708 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
711 if (AM.Scale == 1 && AM.HasBaseReg)
716 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
717 return isLegalMUBUFAddressingMode(AM);
718 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
719 AS == AMDGPUASI.REGION_ADDRESS) {
720 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
722 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
723 // an 8-bit dword offset but we don't know the alignment here.
724 if (!isUInt<16>(AM.BaseOffs))
727 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
730 if (AM.Scale == 1 && AM.HasBaseReg)
734 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
735 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
736 // For an unknown address space, this usually means that this is for some
737 // reason being used for pure arithmetic, and not based on some addressing
738 // computation. We don't have instructions that compute pointers with any
739 // addressing modes, so treat them as having no offset like flat
741 return isLegalFlatAddressingMode(AM);
743 llvm_unreachable("unhandled address space");
747 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
748 const SelectionDAG &DAG) const {
749 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
750 return (MemVT.getSizeInBits() <= 4 * 32);
751 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
752 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
753 return (MemVT.getSizeInBits() <= MaxPrivateBits);
754 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
755 return (MemVT.getSizeInBits() <= 2 * 32);
760 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
763 bool *IsFast) const {
767 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
768 // which isn't a simple VT.
769 // Until MVT is extended to handle this, simply check for the size and
770 // rely on the condition below: allow accesses if the size is a multiple of 4.
771 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
772 VT.getStoreSize() > 16)) {
776 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
777 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
778 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
779 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
780 // with adjacent offsets.
781 bool AlignedBy4 = (Align % 4 == 0);
783 *IsFast = AlignedBy4;
788 // FIXME: We have to be conservative here and assume that flat operations
789 // will access scratch. If we had access to the IR function, then we
790 // could determine if any private memory was used in the function.
791 if (!Subtarget->hasUnalignedScratchAccess() &&
792 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
793 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
797 if (Subtarget->hasUnalignedBufferAccess()) {
798 // If we have an uniform constant load, it still requires using a slow
799 // buffer instruction if unaligned.
801 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
802 (Align % 4 == 0) : true;
808 // Smaller than dword value must be aligned.
809 if (VT.bitsLT(MVT::i32))
812 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
813 // byte-address are ignored, thus forcing Dword alignment.
814 // This applies to private, global, and constant memory.
818 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
821 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
822 unsigned SrcAlign, bool IsMemset,
825 MachineFunction &MF) const {
826 // FIXME: Should account for address space here.
828 // The default fallback uses the private pointer size as a guess for a type to
829 // use. Make sure we switch these to 64-bit accesses.
831 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
834 if (Size >= 8 && DstAlign >= 4)
841 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
842 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
843 AS == AMDGPUASI.FLAT_ADDRESS ||
844 AS == AMDGPUASI.CONSTANT_ADDRESS;
847 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
848 unsigned DestAS) const {
849 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
850 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
853 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
854 const MemSDNode *MemNode = cast<MemSDNode>(N);
855 const Value *Ptr = MemNode->getMemOperand()->getValue();
856 const Instruction *I = dyn_cast<Instruction>(Ptr);
857 return I && I->getMetadata("amdgpu.noclobber");
860 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
861 unsigned DestAS) const {
862 // Flat -> private/local is a simple truncate.
863 // Flat -> global is no-op
864 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
867 return isNoopAddrSpaceCast(SrcAS, DestAS);
870 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
871 const MemSDNode *MemNode = cast<MemSDNode>(N);
873 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
876 TargetLoweringBase::LegalizeTypeAction
877 SITargetLowering::getPreferredVectorAction(EVT VT) const {
878 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
879 return TypeSplitVector;
881 return TargetLoweringBase::getPreferredVectorAction(VT);
884 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
886 // FIXME: Could be smarter if called for vector constants.
890 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
891 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
896 // These operations are done with 32-bit instructions anyway.
908 // SimplifySetCC uses this function to determine whether or not it should
909 // create setcc with i1 operands. We don't have instructions for i1 setcc.
910 if (VT == MVT::i1 && Op == ISD::SETCC)
913 return TargetLowering::isTypeDesirableForOp(Op, VT);
916 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
919 uint64_t Offset) const {
920 const DataLayout &DL = DAG.getDataLayout();
921 MachineFunction &MF = DAG.getMachineFunction();
922 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
924 const ArgDescriptor *InputPtrReg;
925 const TargetRegisterClass *RC;
927 std::tie(InputPtrReg, RC)
928 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
930 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
931 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
932 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
933 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
935 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
936 DAG.getConstant(Offset, SL, PtrVT));
939 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
940 const SDLoc &SL) const {
941 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
942 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
943 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
946 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
947 const SDLoc &SL, SDValue Val,
949 const ISD::InputArg *Arg) const {
950 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
952 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
953 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
956 if (MemVT.isFloatingPoint())
957 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
959 Val = DAG.getSExtOrTrunc(Val, SL, VT);
961 Val = DAG.getZExtOrTrunc(Val, SL, VT);
966 SDValue SITargetLowering::lowerKernargMemParameter(
967 SelectionDAG &DAG, EVT VT, EVT MemVT,
968 const SDLoc &SL, SDValue Chain,
969 uint64_t Offset, bool Signed,
970 const ISD::InputArg *Arg) const {
971 const DataLayout &DL = DAG.getDataLayout();
972 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
973 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
974 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
976 unsigned Align = DL.getABITypeAlignment(Ty);
978 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
979 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
980 MachineMemOperand::MONonTemporal |
981 MachineMemOperand::MODereferenceable |
982 MachineMemOperand::MOInvariant);
984 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
985 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
988 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
989 const SDLoc &SL, SDValue Chain,
990 const ISD::InputArg &Arg) const {
991 MachineFunction &MF = DAG.getMachineFunction();
992 MachineFrameInfo &MFI = MF.getFrameInfo();
994 if (Arg.Flags.isByVal()) {
995 unsigned Size = Arg.Flags.getByValSize();
996 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
997 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1000 unsigned ArgOffset = VA.getLocMemOffset();
1001 unsigned ArgSize = VA.getValVT().getStoreSize();
1003 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1005 // Create load nodes to retrieve arguments from the stack.
1006 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1009 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1010 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1011 MVT MemVT = VA.getValVT();
1013 switch (VA.getLocInfo()) {
1016 case CCValAssign::BCvt:
1017 MemVT = VA.getLocVT();
1019 case CCValAssign::SExt:
1020 ExtType = ISD::SEXTLOAD;
1022 case CCValAssign::ZExt:
1023 ExtType = ISD::ZEXTLOAD;
1025 case CCValAssign::AExt:
1026 ExtType = ISD::EXTLOAD;
1030 ArgValue = DAG.getExtLoad(
1031 ExtType, SL, VA.getLocVT(), Chain, FIN,
1032 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1037 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1038 const SIMachineFunctionInfo &MFI,
1040 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1041 const ArgDescriptor *Reg;
1042 const TargetRegisterClass *RC;
1044 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1045 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1048 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1049 CallingConv::ID CallConv,
1050 ArrayRef<ISD::InputArg> Ins,
1052 FunctionType *FType,
1053 SIMachineFunctionInfo *Info) {
1054 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1055 const ISD::InputArg &Arg = Ins[I];
1057 // First check if it's a PS input addr.
1058 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1059 !Arg.Flags.isByVal() && PSInputNum <= 15) {
1061 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1062 // We can safely skip PS inputs.
1068 Info->markPSInputAllocated(PSInputNum);
1070 Info->markPSInputEnabled(PSInputNum);
1075 // Second split vertices into their elements.
1076 if (Arg.VT.isVector()) {
1077 ISD::InputArg NewArg = Arg;
1078 NewArg.Flags.setSplit();
1079 NewArg.VT = Arg.VT.getVectorElementType();
1081 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1082 // three or five element vertex only needs three or five registers,
1083 // NOT four or eight.
1084 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1085 unsigned NumElements = ParamType->getVectorNumElements();
1087 for (unsigned J = 0; J != NumElements; ++J) {
1088 Splits.push_back(NewArg);
1089 NewArg.PartOffset += NewArg.VT.getStoreSize();
1092 Splits.push_back(Arg);
1097 // Allocate special inputs passed in VGPRs.
1098 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1099 MachineFunction &MF,
1100 const SIRegisterInfo &TRI,
1101 SIMachineFunctionInfo &Info) {
1102 if (Info.hasWorkItemIDX()) {
1103 unsigned Reg = AMDGPU::VGPR0;
1104 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1106 CCInfo.AllocateReg(Reg);
1107 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1110 if (Info.hasWorkItemIDY()) {
1111 unsigned Reg = AMDGPU::VGPR1;
1112 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1114 CCInfo.AllocateReg(Reg);
1115 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1118 if (Info.hasWorkItemIDZ()) {
1119 unsigned Reg = AMDGPU::VGPR2;
1120 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1122 CCInfo.AllocateReg(Reg);
1123 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1127 // Try to allocate a VGPR at the end of the argument list, or if no argument
1128 // VGPRs are left allocating a stack slot.
1129 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1130 ArrayRef<MCPhysReg> ArgVGPRs
1131 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1132 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1133 if (RegIdx == ArgVGPRs.size()) {
1134 // Spill to stack required.
1135 int64_t Offset = CCInfo.AllocateStack(4, 4);
1137 return ArgDescriptor::createStack(Offset);
1140 unsigned Reg = ArgVGPRs[RegIdx];
1141 Reg = CCInfo.AllocateReg(Reg);
1142 assert(Reg != AMDGPU::NoRegister);
1144 MachineFunction &MF = CCInfo.getMachineFunction();
1145 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1146 return ArgDescriptor::createRegister(Reg);
1149 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1150 const TargetRegisterClass *RC,
1151 unsigned NumArgRegs) {
1152 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1153 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1154 if (RegIdx == ArgSGPRs.size())
1155 report_fatal_error("ran out of SGPRs for arguments");
1157 unsigned Reg = ArgSGPRs[RegIdx];
1158 Reg = CCInfo.AllocateReg(Reg);
1159 assert(Reg != AMDGPU::NoRegister);
1161 MachineFunction &MF = CCInfo.getMachineFunction();
1162 MF.addLiveIn(Reg, RC);
1163 return ArgDescriptor::createRegister(Reg);
1166 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1167 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1170 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1171 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1174 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1175 MachineFunction &MF,
1176 const SIRegisterInfo &TRI,
1177 SIMachineFunctionInfo &Info) {
1178 if (Info.hasWorkItemIDX())
1179 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1181 if (Info.hasWorkItemIDY())
1182 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1184 if (Info.hasWorkItemIDZ())
1185 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1188 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1189 MachineFunction &MF,
1190 const SIRegisterInfo &TRI,
1191 SIMachineFunctionInfo &Info) {
1192 auto &ArgInfo = Info.getArgInfo();
1194 // TODO: Unify handling with private memory pointers.
1196 if (Info.hasDispatchPtr())
1197 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1199 if (Info.hasQueuePtr())
1200 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1202 if (Info.hasKernargSegmentPtr())
1203 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1205 if (Info.hasDispatchID())
1206 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1208 // flat_scratch_init is not applicable for non-kernel functions.
1210 if (Info.hasWorkGroupIDX())
1211 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1213 if (Info.hasWorkGroupIDY())
1214 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1216 if (Info.hasWorkGroupIDZ())
1217 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1219 if (Info.hasImplicitArgPtr())
1220 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1223 // Allocate special inputs passed in user SGPRs.
1224 static void allocateHSAUserSGPRs(CCState &CCInfo,
1225 MachineFunction &MF,
1226 const SIRegisterInfo &TRI,
1227 SIMachineFunctionInfo &Info) {
1228 if (Info.hasImplicitBufferPtr()) {
1229 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1230 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1231 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1234 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1235 if (Info.hasPrivateSegmentBuffer()) {
1236 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1237 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1238 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1241 if (Info.hasDispatchPtr()) {
1242 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1243 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1244 CCInfo.AllocateReg(DispatchPtrReg);
1247 if (Info.hasQueuePtr()) {
1248 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1249 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1250 CCInfo.AllocateReg(QueuePtrReg);
1253 if (Info.hasKernargSegmentPtr()) {
1254 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1255 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1256 CCInfo.AllocateReg(InputPtrReg);
1259 if (Info.hasDispatchID()) {
1260 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1261 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1262 CCInfo.AllocateReg(DispatchIDReg);
1265 if (Info.hasFlatScratchInit()) {
1266 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1267 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1268 CCInfo.AllocateReg(FlatScratchInitReg);
1271 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1272 // these from the dispatch pointer.
1275 // Allocate special input registers that are initialized per-wave.
1276 static void allocateSystemSGPRs(CCState &CCInfo,
1277 MachineFunction &MF,
1278 SIMachineFunctionInfo &Info,
1279 CallingConv::ID CallConv,
1281 if (Info.hasWorkGroupIDX()) {
1282 unsigned Reg = Info.addWorkGroupIDX();
1283 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1284 CCInfo.AllocateReg(Reg);
1287 if (Info.hasWorkGroupIDY()) {
1288 unsigned Reg = Info.addWorkGroupIDY();
1289 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1290 CCInfo.AllocateReg(Reg);
1293 if (Info.hasWorkGroupIDZ()) {
1294 unsigned Reg = Info.addWorkGroupIDZ();
1295 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1296 CCInfo.AllocateReg(Reg);
1299 if (Info.hasWorkGroupInfo()) {
1300 unsigned Reg = Info.addWorkGroupInfo();
1301 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1302 CCInfo.AllocateReg(Reg);
1305 if (Info.hasPrivateSegmentWaveByteOffset()) {
1306 // Scratch wave offset passed in system SGPR.
1307 unsigned PrivateSegmentWaveByteOffsetReg;
1310 PrivateSegmentWaveByteOffsetReg =
1311 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1313 // This is true if the scratch wave byte offset doesn't have a fixed
1315 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1316 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1317 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1320 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1322 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1323 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1327 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1328 MachineFunction &MF,
1329 const SIRegisterInfo &TRI,
1330 SIMachineFunctionInfo &Info) {
1331 // Now that we've figured out where the scratch register inputs are, see if
1332 // should reserve the arguments and use them directly.
1333 MachineFrameInfo &MFI = MF.getFrameInfo();
1334 bool HasStackObjects = MFI.hasStackObjects();
1336 // Record that we know we have non-spill stack objects so we don't need to
1337 // check all stack objects later.
1338 if (HasStackObjects)
1339 Info.setHasNonSpillStackObjects(true);
1341 // Everything live out of a block is spilled with fast regalloc, so it's
1342 // almost certain that spilling will be required.
1343 if (TM.getOptLevel() == CodeGenOpt::None)
1344 HasStackObjects = true;
1346 // For now assume stack access is needed in any callee functions, so we need
1347 // the scratch registers to pass in.
1348 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1350 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1351 if (ST.isAmdCodeObjectV2(MF)) {
1352 if (RequiresStackAccess) {
1353 // If we have stack objects, we unquestionably need the private buffer
1354 // resource. For the Code Object V2 ABI, this will be the first 4 user
1355 // SGPR inputs. We can reserve those and use them directly.
1357 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1358 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1359 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1361 if (MFI.hasCalls()) {
1362 // If we have calls, we need to keep the frame register in a register
1363 // that won't be clobbered by a call, so ensure it is copied somewhere.
1365 // This is not a problem for the scratch wave offset, because the same
1366 // registers are reserved in all functions.
1368 // FIXME: Nothing is really ensuring this is a call preserved register,
1369 // it's just selected from the end so it happens to be.
1370 unsigned ReservedOffsetReg
1371 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1372 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1374 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1375 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1376 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1379 unsigned ReservedBufferReg
1380 = TRI.reservedPrivateSegmentBufferReg(MF);
1381 unsigned ReservedOffsetReg
1382 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1384 // We tentatively reserve the last registers (skipping the last two
1385 // which may contain VCC). After register allocation, we'll replace
1386 // these with the ones immediately after those which were really
1387 // allocated. In the prologue copies will be inserted from the argument
1388 // to these reserved registers.
1389 Info.setScratchRSrcReg(ReservedBufferReg);
1390 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1393 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1395 // Without HSA, relocations are used for the scratch pointer and the
1396 // buffer resource setup is always inserted in the prologue. Scratch wave
1397 // offset is still in an input SGPR.
1398 Info.setScratchRSrcReg(ReservedBufferReg);
1400 if (HasStackObjects && !MFI.hasCalls()) {
1401 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1402 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1403 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1405 unsigned ReservedOffsetReg
1406 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1407 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1412 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1413 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1414 return !Info->isEntryFunction();
1417 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1421 void SITargetLowering::insertCopiesSplitCSR(
1422 MachineBasicBlock *Entry,
1423 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1424 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1426 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1430 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1431 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1432 MachineBasicBlock::iterator MBBI = Entry->begin();
1433 for (const MCPhysReg *I = IStart; *I; ++I) {
1434 const TargetRegisterClass *RC = nullptr;
1435 if (AMDGPU::SReg_64RegClass.contains(*I))
1436 RC = &AMDGPU::SGPR_64RegClass;
1437 else if (AMDGPU::SReg_32RegClass.contains(*I))
1438 RC = &AMDGPU::SGPR_32RegClass;
1440 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1442 unsigned NewVR = MRI->createVirtualRegister(RC);
1443 // Create copy from CSR to a virtual register.
1444 Entry->addLiveIn(*I);
1445 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1448 // Insert the copy-back instructions right before the terminator.
1449 for (auto *Exit : Exits)
1450 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1451 TII->get(TargetOpcode::COPY), *I)
1456 SDValue SITargetLowering::LowerFormalArguments(
1457 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1458 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1459 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1460 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1462 MachineFunction &MF = DAG.getMachineFunction();
1463 FunctionType *FType = MF.getFunction().getFunctionType();
1464 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1465 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1467 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1468 const Function &Fn = MF.getFunction();
1469 DiagnosticInfoUnsupported NoGraphicsHSA(
1470 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1471 DAG.getContext()->diagnose(NoGraphicsHSA);
1472 return DAG.getEntryNode();
1475 // Create stack objects that are used for emitting debugger prologue if
1476 // "amdgpu-debugger-emit-prologue" attribute was specified.
1477 if (ST.debuggerEmitPrologue())
1478 createDebuggerPrologueStackObjects(MF);
1480 SmallVector<ISD::InputArg, 16> Splits;
1481 SmallVector<CCValAssign, 16> ArgLocs;
1482 BitVector Skipped(Ins.size());
1483 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1486 bool IsShader = AMDGPU::isShader(CallConv);
1487 bool IsKernel = AMDGPU::isKernel(CallConv);
1488 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1491 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1492 // this when allocating argument fixed offsets.
1493 CCInfo.AllocateStack(4, 4);
1497 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1499 // At least one interpolation mode must be enabled or else the GPU will
1502 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1503 // set PSInputAddr, the user wants to enable some bits after the compilation
1504 // based on run-time states. Since we can't know what the final PSInputEna
1505 // will look like, so we shouldn't do anything here and the user should take
1506 // responsibility for the correct programming.
1508 // Otherwise, the following restrictions apply:
1509 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1510 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1512 if (CallConv == CallingConv::AMDGPU_PS) {
1513 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1514 ((Info->getPSInputAddr() & 0xF) == 0 &&
1515 Info->isPSInputAllocated(11))) {
1516 CCInfo.AllocateReg(AMDGPU::VGPR0);
1517 CCInfo.AllocateReg(AMDGPU::VGPR1);
1518 Info->markPSInputAllocated(0);
1519 Info->markPSInputEnabled(0);
1521 if (Subtarget->isAmdPalOS()) {
1522 // For isAmdPalOS, the user does not enable some bits after compilation
1523 // based on run-time states; the register values being generated here are
1524 // the final ones set in hardware. Therefore we need to apply the
1525 // workaround to PSInputAddr and PSInputEnable together. (The case where
1526 // a bit is set in PSInputAddr but not PSInputEnable is where the
1527 // frontend set up an input arg for a particular interpolation mode, but
1528 // nothing uses that input arg. Really we should have an earlier pass
1529 // that removes such an arg.)
1530 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1531 if ((PsInputBits & 0x7F) == 0 ||
1532 ((PsInputBits & 0xF) == 0 &&
1533 (PsInputBits >> 11 & 1)))
1534 Info->markPSInputEnabled(
1535 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1539 assert(!Info->hasDispatchPtr() &&
1540 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1541 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1542 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1543 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1544 !Info->hasWorkItemIDZ());
1545 } else if (IsKernel) {
1546 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1548 Splits.append(Ins.begin(), Ins.end());
1552 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1553 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1557 analyzeFormalArgumentsCompute(CCInfo, Ins);
1559 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1560 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1563 SmallVector<SDValue, 16> Chains;
1565 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1566 const ISD::InputArg &Arg = Ins[i];
1568 InVals.push_back(DAG.getUNDEF(Arg.VT));
1572 CCValAssign &VA = ArgLocs[ArgIdx++];
1573 MVT VT = VA.getLocVT();
1575 if (IsEntryFunc && VA.isMemLoc()) {
1577 EVT MemVT = VA.getLocVT();
1579 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1580 VA.getLocMemOffset();
1581 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1583 // The first 36 bytes of the input buffer contains information about
1584 // thread group and global sizes.
1585 SDValue Arg = lowerKernargMemParameter(
1586 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1587 Chains.push_back(Arg.getValue(1));
1590 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1591 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1592 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1593 // On SI local pointers are just offsets into LDS, so they are always
1594 // less than 16-bits. On CI and newer they could potentially be
1595 // real pointers, so we can't guarantee their size.
1596 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1597 DAG.getValueType(MVT::i16));
1600 InVals.push_back(Arg);
1602 } else if (!IsEntryFunc && VA.isMemLoc()) {
1603 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1604 InVals.push_back(Val);
1605 if (!Arg.Flags.isByVal())
1606 Chains.push_back(Val.getValue(1));
1610 assert(VA.isRegLoc() && "Parameter must be in a register!");
1612 unsigned Reg = VA.getLocReg();
1613 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1614 EVT ValVT = VA.getValVT();
1616 Reg = MF.addLiveIn(Reg, RC);
1617 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1619 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1620 // The return object should be reasonably addressable.
1622 // FIXME: This helps when the return is a real sret. If it is a
1623 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1624 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1625 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1626 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1627 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1630 // If this is an 8 or 16-bit value, it is really passed promoted
1631 // to 32 bits. Insert an assert[sz]ext to capture this, then
1632 // truncate to the right size.
1633 switch (VA.getLocInfo()) {
1634 case CCValAssign::Full:
1636 case CCValAssign::BCvt:
1637 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1639 case CCValAssign::SExt:
1640 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1641 DAG.getValueType(ValVT));
1642 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1644 case CCValAssign::ZExt:
1645 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1646 DAG.getValueType(ValVT));
1647 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1649 case CCValAssign::AExt:
1650 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1653 llvm_unreachable("Unknown loc info!");
1656 if (IsShader && Arg.VT.isVector()) {
1657 // Build a vector from the registers
1658 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1659 unsigned NumElements = ParamType->getVectorNumElements();
1661 SmallVector<SDValue, 4> Regs;
1662 Regs.push_back(Val);
1663 for (unsigned j = 1; j != NumElements; ++j) {
1664 Reg = ArgLocs[ArgIdx++].getLocReg();
1665 Reg = MF.addLiveIn(Reg, RC);
1667 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1668 Regs.push_back(Copy);
1671 // Fill up the missing vector elements
1672 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1673 Regs.append(NumElements, DAG.getUNDEF(VT));
1675 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1679 InVals.push_back(Val);
1683 // Special inputs come after user arguments.
1684 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1687 // Start adding system SGPRs.
1689 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1691 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1692 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1693 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1694 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1697 auto &ArgUsageInfo =
1698 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1699 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo());
1701 unsigned StackArgSize = CCInfo.getNextStackOffset();
1702 Info->setBytesInStackArgArea(StackArgSize);
1704 return Chains.empty() ? Chain :
1705 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1708 // TODO: If return values can't fit in registers, we should return as many as
1709 // possible in registers before passing on stack.
1710 bool SITargetLowering::CanLowerReturn(
1711 CallingConv::ID CallConv,
1712 MachineFunction &MF, bool IsVarArg,
1713 const SmallVectorImpl<ISD::OutputArg> &Outs,
1714 LLVMContext &Context) const {
1715 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1716 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1717 // for shaders. Vector types should be explicitly handled by CC.
1718 if (AMDGPU::isEntryFunctionCC(CallConv))
1721 SmallVector<CCValAssign, 16> RVLocs;
1722 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1723 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1727 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1729 const SmallVectorImpl<ISD::OutputArg> &Outs,
1730 const SmallVectorImpl<SDValue> &OutVals,
1731 const SDLoc &DL, SelectionDAG &DAG) const {
1732 MachineFunction &MF = DAG.getMachineFunction();
1733 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1735 if (AMDGPU::isKernel(CallConv)) {
1736 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1740 bool IsShader = AMDGPU::isShader(CallConv);
1742 Info->setIfReturnsVoid(Outs.size() == 0);
1743 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1745 SmallVector<ISD::OutputArg, 48> Splits;
1746 SmallVector<SDValue, 48> SplitVals;
1748 // Split vectors into their elements.
1749 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1750 const ISD::OutputArg &Out = Outs[i];
1752 if (IsShader && Out.VT.isVector()) {
1753 MVT VT = Out.VT.getVectorElementType();
1754 ISD::OutputArg NewOut = Out;
1755 NewOut.Flags.setSplit();
1758 // We want the original number of vector elements here, e.g.
1759 // three or five, not four or eight.
1760 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1762 for (unsigned j = 0; j != NumElements; ++j) {
1763 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1764 DAG.getConstant(j, DL, MVT::i32));
1765 SplitVals.push_back(Elem);
1766 Splits.push_back(NewOut);
1767 NewOut.PartOffset += NewOut.VT.getStoreSize();
1770 SplitVals.push_back(OutVals[i]);
1771 Splits.push_back(Out);
1775 // CCValAssign - represent the assignment of the return value to a location.
1776 SmallVector<CCValAssign, 48> RVLocs;
1778 // CCState - Info about the registers and stack slots.
1779 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1782 // Analyze outgoing return values.
1783 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
1786 SmallVector<SDValue, 48> RetOps;
1787 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1789 // Add return address for callable functions.
1790 if (!Info->isEntryFunction()) {
1791 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1792 SDValue ReturnAddrReg = CreateLiveInRegister(
1793 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
1795 // FIXME: Should be able to use a vreg here, but need a way to prevent it
1796 // from being allcoated to a CSR.
1798 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
1801 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
1802 Flag = Chain.getValue(1);
1804 RetOps.push_back(PhysReturnAddrReg);
1807 // Copy the result values into the output registers.
1808 for (unsigned i = 0, realRVLocIdx = 0;
1810 ++i, ++realRVLocIdx) {
1811 CCValAssign &VA = RVLocs[i];
1812 assert(VA.isRegLoc() && "Can only return in registers!");
1813 // TODO: Partially return in registers if return values don't fit.
1815 SDValue Arg = SplitVals[realRVLocIdx];
1817 // Copied from other backends.
1818 switch (VA.getLocInfo()) {
1819 case CCValAssign::Full:
1821 case CCValAssign::BCvt:
1822 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1824 case CCValAssign::SExt:
1825 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1827 case CCValAssign::ZExt:
1828 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1830 case CCValAssign::AExt:
1831 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1834 llvm_unreachable("Unknown loc info!");
1837 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1838 Flag = Chain.getValue(1);
1839 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1842 // FIXME: Does sret work properly?
1843 if (!Info->isEntryFunction()) {
1844 const SIRegisterInfo *TRI
1845 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
1846 const MCPhysReg *I =
1847 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
1850 if (AMDGPU::SReg_64RegClass.contains(*I))
1851 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
1852 else if (AMDGPU::SReg_32RegClass.contains(*I))
1853 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
1855 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1860 // Update chain and glue.
1863 RetOps.push_back(Flag);
1865 unsigned Opc = AMDGPUISD::ENDPGM;
1867 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
1868 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1871 SDValue SITargetLowering::LowerCallResult(
1872 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
1873 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1874 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
1875 SDValue ThisVal) const {
1876 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
1878 // Assign locations to each value returned by this call.
1879 SmallVector<CCValAssign, 16> RVLocs;
1880 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
1882 CCInfo.AnalyzeCallResult(Ins, RetCC);
1884 // Copy all of the result registers out of their specified physreg.
1885 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1886 CCValAssign VA = RVLocs[i];
1889 if (VA.isRegLoc()) {
1890 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1891 Chain = Val.getValue(1);
1892 InFlag = Val.getValue(2);
1893 } else if (VA.isMemLoc()) {
1894 report_fatal_error("TODO: return values in memory");
1896 llvm_unreachable("unknown argument location type");
1898 switch (VA.getLocInfo()) {
1899 case CCValAssign::Full:
1901 case CCValAssign::BCvt:
1902 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1904 case CCValAssign::ZExt:
1905 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
1906 DAG.getValueType(VA.getValVT()));
1907 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1909 case CCValAssign::SExt:
1910 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
1911 DAG.getValueType(VA.getValVT()));
1912 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1914 case CCValAssign::AExt:
1915 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
1918 llvm_unreachable("Unknown loc info!");
1921 InVals.push_back(Val);
1927 // Add code to pass special inputs required depending on used features separate
1928 // from the explicit user arguments present in the IR.
1929 void SITargetLowering::passSpecialInputs(
1930 CallLoweringInfo &CLI,
1931 const SIMachineFunctionInfo &Info,
1932 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
1933 SmallVectorImpl<SDValue> &MemOpChains,
1935 SDValue StackPtr) const {
1936 // If we don't have a call site, this was a call inserted by
1937 // legalization. These can never use special inputs.
1941 const Function *CalleeFunc = CLI.CS.getCalledFunction();
1944 SelectionDAG &DAG = CLI.DAG;
1945 const SDLoc &DL = CLI.DL;
1947 const SISubtarget *ST = getSubtarget();
1948 const SIRegisterInfo *TRI = ST->getRegisterInfo();
1950 auto &ArgUsageInfo =
1951 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1952 const AMDGPUFunctionArgInfo &CalleeArgInfo
1953 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
1955 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
1957 // TODO: Unify with private memory register handling. This is complicated by
1958 // the fact that at least in kernels, the input argument is not necessarily
1959 // in the same location as the input.
1960 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
1961 AMDGPUFunctionArgInfo::DISPATCH_PTR,
1962 AMDGPUFunctionArgInfo::QUEUE_PTR,
1963 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
1964 AMDGPUFunctionArgInfo::DISPATCH_ID,
1965 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
1966 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
1967 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
1968 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
1969 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
1970 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
1971 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
1974 for (auto InputID : InputRegs) {
1975 const ArgDescriptor *OutgoingArg;
1976 const TargetRegisterClass *ArgRC;
1978 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
1982 const ArgDescriptor *IncomingArg;
1983 const TargetRegisterClass *IncomingArgRC;
1984 std::tie(IncomingArg, IncomingArgRC)
1985 = CallerArgInfo.getPreloadedValue(InputID);
1986 assert(IncomingArgRC == ArgRC);
1988 // All special arguments are ints for now.
1989 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
1993 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
1995 // The implicit arg ptr is special because it doesn't have a corresponding
1996 // input for kernels, and is computed from the kernarg segment pointer.
1997 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
1998 InputReg = getImplicitArgPtr(DAG, DL);
2001 if (OutgoingArg->isRegister()) {
2002 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2004 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2006 OutgoingArg->getStackOffset());
2007 MemOpChains.push_back(ArgStore);
2012 static bool canGuaranteeTCO(CallingConv::ID CC) {
2013 return CC == CallingConv::Fast;
2016 /// Return true if we might ever do TCO for calls with this calling convention.
2017 static bool mayTailCallThisCC(CallingConv::ID CC) {
2019 case CallingConv::C:
2022 return canGuaranteeTCO(CC);
2026 bool SITargetLowering::isEligibleForTailCallOptimization(
2027 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2028 const SmallVectorImpl<ISD::OutputArg> &Outs,
2029 const SmallVectorImpl<SDValue> &OutVals,
2030 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2031 if (!mayTailCallThisCC(CalleeCC))
2034 MachineFunction &MF = DAG.getMachineFunction();
2035 const Function &CallerF = MF.getFunction();
2036 CallingConv::ID CallerCC = CallerF.getCallingConv();
2037 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2038 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2040 // Kernels aren't callable, and don't have a live in return address so it
2041 // doesn't make sense to do a tail call with entry functions.
2042 if (!CallerPreserved)
2045 bool CCMatch = CallerCC == CalleeCC;
2047 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2048 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2053 // TODO: Can we handle var args?
2057 for (const Argument &Arg : CallerF.args()) {
2058 if (Arg.hasByValAttr())
2062 LLVMContext &Ctx = *DAG.getContext();
2064 // Check that the call results are passed in the same way.
2065 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2066 CCAssignFnForCall(CalleeCC, IsVarArg),
2067 CCAssignFnForCall(CallerCC, IsVarArg)))
2070 // The callee has to preserve all registers the caller needs to preserve.
2072 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2073 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2077 // Nothing more to check if the callee is taking no arguments.
2081 SmallVector<CCValAssign, 16> ArgLocs;
2082 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2084 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2086 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2087 // If the stack arguments for this call do not fit into our own save area then
2088 // the call cannot be made tail.
2089 // TODO: Is this really necessary?
2090 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2093 const MachineRegisterInfo &MRI = MF.getRegInfo();
2094 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2097 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2098 if (!CI->isTailCall())
2101 const Function *ParentFn = CI->getParent()->getParent();
2102 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2105 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2106 return (Attr.getValueAsString() != "true");
2109 // The wave scratch offset register is used as the global base pointer.
2110 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2111 SmallVectorImpl<SDValue> &InVals) const {
2112 SelectionDAG &DAG = CLI.DAG;
2113 const SDLoc &DL = CLI.DL;
2114 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2115 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2116 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2117 SDValue Chain = CLI.Chain;
2118 SDValue Callee = CLI.Callee;
2119 bool &IsTailCall = CLI.IsTailCall;
2120 CallingConv::ID CallConv = CLI.CallConv;
2121 bool IsVarArg = CLI.IsVarArg;
2122 bool IsSibCall = false;
2123 bool IsThisReturn = false;
2124 MachineFunction &MF = DAG.getMachineFunction();
2127 return lowerUnhandledCall(CLI, InVals,
2128 "unsupported call to variadic function ");
2131 if (!CLI.CS.getCalledFunction()) {
2132 return lowerUnhandledCall(CLI, InVals,
2133 "unsupported indirect call to function ");
2136 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2137 return lowerUnhandledCall(CLI, InVals,
2138 "unsupported required tail call to function ");
2141 // The first 4 bytes are reserved for the callee's emergency stack slot.
2142 const unsigned CalleeUsableStackOffset = 4;
2145 IsTailCall = isEligibleForTailCallOptimization(
2146 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2147 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2148 report_fatal_error("failed to perform tail call elimination on a call "
2149 "site marked musttail");
2152 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2154 // A sibling call is one where we're under the usual C ABI and not planning
2155 // to change that but can still do a tail call:
2156 if (!TailCallOpt && IsTailCall)
2163 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2164 // FIXME: Remove this hack for function pointer types after removing
2165 // support of old address space mapping. In the new address space
2166 // mapping the pointer in default address space is 64 bit, therefore
2167 // does not need this hack.
2168 if (Callee.getValueType() == MVT::i32) {
2169 const GlobalValue *GV = GA->getGlobal();
2170 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2171 GA->getTargetFlags());
2174 assert(Callee.getValueType() == MVT::i64);
2176 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2178 // Analyze operands of the call, assigning locations to each operand.
2179 SmallVector<CCValAssign, 16> ArgLocs;
2180 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2181 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2182 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2184 // Get a count of how many bytes are to be pushed on the stack.
2185 unsigned NumBytes = CCInfo.getNextStackOffset();
2188 // Since we're not changing the ABI to make this a tail call, the memory
2189 // operands are already available in the caller's incoming argument space.
2193 // FPDiff is the byte offset of the call's argument area from the callee's.
2194 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2195 // by this amount for a tail call. In a sibling call it must be 0 because the
2196 // caller will deallocate the entire stack and the callee still expects its
2197 // arguments to begin at SP+0. Completely unused for non-tail calls.
2199 MachineFrameInfo &MFI = MF.getFrameInfo();
2200 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2202 SDValue CallerSavedFP;
2204 // Adjust the stack pointer for the new arguments...
2205 // These operations are automatically eliminated by the prolog/epilog pass
2207 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2209 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2211 // In the HSA case, this should be an identity copy.
2212 SDValue ScratchRSrcReg
2213 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2214 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2216 // TODO: Don't hardcode these registers and get from the callee function.
2217 SDValue ScratchWaveOffsetReg
2218 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2219 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2221 if (!Info->isEntryFunction()) {
2222 // Avoid clobbering this function's FP value. In the current convention
2223 // callee will overwrite this, so do save/restore around the call site.
2224 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2225 Info->getFrameOffsetReg(), MVT::i32);
2229 // Stack pointer relative accesses are done by changing the offset SGPR. This
2230 // is just the VGPR offset component.
2231 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2233 SmallVector<SDValue, 8> MemOpChains;
2234 MVT PtrVT = MVT::i32;
2236 // Walk the register/memloc assignments, inserting copies/loads.
2237 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2238 ++i, ++realArgIdx) {
2239 CCValAssign &VA = ArgLocs[i];
2240 SDValue Arg = OutVals[realArgIdx];
2242 // Promote the value if needed.
2243 switch (VA.getLocInfo()) {
2244 case CCValAssign::Full:
2246 case CCValAssign::BCvt:
2247 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2249 case CCValAssign::ZExt:
2250 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2252 case CCValAssign::SExt:
2253 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2255 case CCValAssign::AExt:
2256 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2258 case CCValAssign::FPExt:
2259 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2262 llvm_unreachable("Unknown loc info!");
2265 if (VA.isRegLoc()) {
2266 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2268 assert(VA.isMemLoc());
2271 MachinePointerInfo DstInfo;
2273 unsigned LocMemOffset = VA.getLocMemOffset();
2274 int32_t Offset = LocMemOffset;
2276 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2279 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2280 unsigned OpSize = Flags.isByVal() ?
2281 Flags.getByValSize() : VA.getValVT().getStoreSize();
2283 Offset = Offset + FPDiff;
2284 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2286 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2288 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2290 // Make sure any stack arguments overlapping with where we're storing
2291 // are loaded before this eventual operation. Otherwise they'll be
2294 // FIXME: Why is this really necessary? This seems to just result in a
2295 // lot of code to copy the stack and write them back to the same
2296 // locations, which are supposed to be immutable?
2297 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2300 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2303 if (Outs[i].Flags.isByVal()) {
2305 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2306 SDValue Cpy = DAG.getMemcpy(
2307 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2308 /*isVol = */ false, /*AlwaysInline = */ true,
2309 /*isTailCall = */ false, DstInfo,
2310 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2311 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2313 MemOpChains.push_back(Cpy);
2315 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2316 MemOpChains.push_back(Store);
2321 // Copy special input registers after user input arguments.
2322 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2324 if (!MemOpChains.empty())
2325 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2327 // Build a sequence of copy-to-reg nodes chained together with token chain
2328 // and flag operands which copy the outgoing args into the appropriate regs.
2330 for (auto &RegToPass : RegsToPass) {
2331 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2332 RegToPass.second, InFlag);
2333 InFlag = Chain.getValue(1);
2337 SDValue PhysReturnAddrReg;
2339 // Since the return is being combined with the call, we need to pass on the
2342 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2343 SDValue ReturnAddrReg = CreateLiveInRegister(
2344 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2346 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2348 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2349 InFlag = Chain.getValue(1);
2352 // We don't usually want to end the call-sequence here because we would tidy
2353 // the frame up *after* the call, however in the ABI-changing tail-call case
2354 // we've carefully laid out the parameters so that when sp is reset they'll be
2355 // in the correct location.
2356 if (IsTailCall && !IsSibCall) {
2357 Chain = DAG.getCALLSEQ_END(Chain,
2358 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2359 DAG.getTargetConstant(0, DL, MVT::i32),
2361 InFlag = Chain.getValue(1);
2364 std::vector<SDValue> Ops;
2365 Ops.push_back(Chain);
2366 Ops.push_back(Callee);
2369 // Each tail call may have to adjust the stack by a different amount, so
2370 // this information must travel along with the operation for eventual
2371 // consumption by emitEpilogue.
2372 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2374 Ops.push_back(PhysReturnAddrReg);
2377 // Add argument registers to the end of the list so that they are known live
2379 for (auto &RegToPass : RegsToPass) {
2380 Ops.push_back(DAG.getRegister(RegToPass.first,
2381 RegToPass.second.getValueType()));
2384 // Add a register mask operand representing the call-preserved registers.
2386 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2387 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2388 assert(Mask && "Missing call preserved mask for calling convention");
2389 Ops.push_back(DAG.getRegisterMask(Mask));
2391 if (InFlag.getNode())
2392 Ops.push_back(InFlag);
2394 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2396 // If we're doing a tall call, use a TC_RETURN here rather than an
2397 // actual call instruction.
2399 MFI.setHasTailCall();
2400 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2403 // Returns a chain and a flag for retval copy to use.
2404 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2405 Chain = Call.getValue(0);
2406 InFlag = Call.getValue(1);
2408 if (CallerSavedFP) {
2409 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2410 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2411 InFlag = Chain.getValue(1);
2414 uint64_t CalleePopBytes = NumBytes;
2415 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2416 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2419 InFlag = Chain.getValue(1);
2421 // Handle result values, copying them out of physregs into vregs that we
2423 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2424 InVals, IsThisReturn,
2425 IsThisReturn ? OutVals[0] : SDValue());
2428 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2429 SelectionDAG &DAG) const {
2430 unsigned Reg = StringSwitch<unsigned>(RegName)
2431 .Case("m0", AMDGPU::M0)
2432 .Case("exec", AMDGPU::EXEC)
2433 .Case("exec_lo", AMDGPU::EXEC_LO)
2434 .Case("exec_hi", AMDGPU::EXEC_HI)
2435 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2436 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2437 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2438 .Default(AMDGPU::NoRegister);
2440 if (Reg == AMDGPU::NoRegister) {
2441 report_fatal_error(Twine("invalid register name \""
2442 + StringRef(RegName) + "\"."));
2446 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2447 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2448 report_fatal_error(Twine("invalid register \""
2449 + StringRef(RegName) + "\" for subtarget."));
2454 case AMDGPU::EXEC_LO:
2455 case AMDGPU::EXEC_HI:
2456 case AMDGPU::FLAT_SCR_LO:
2457 case AMDGPU::FLAT_SCR_HI:
2458 if (VT.getSizeInBits() == 32)
2462 case AMDGPU::FLAT_SCR:
2463 if (VT.getSizeInBits() == 64)
2467 llvm_unreachable("missing register type checking");
2470 report_fatal_error(Twine("invalid type for register \""
2471 + StringRef(RegName) + "\"."));
2474 // If kill is not the last instruction, split the block so kill is always a
2475 // proper terminator.
2476 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2477 MachineBasicBlock *BB) const {
2478 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2480 MachineBasicBlock::iterator SplitPoint(&MI);
2483 if (SplitPoint == BB->end()) {
2484 // Don't bother with a new block.
2485 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2489 MachineFunction *MF = BB->getParent();
2490 MachineBasicBlock *SplitBB
2491 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2493 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2494 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2496 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2497 BB->addSuccessor(SplitBB);
2499 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2503 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2504 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2505 // will only do one iteration. In the worst case, this will loop 64 times.
2507 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2508 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2509 const SIInstrInfo *TII,
2510 MachineRegisterInfo &MRI,
2511 MachineBasicBlock &OrigBB,
2512 MachineBasicBlock &LoopBB,
2514 const MachineOperand &IdxReg,
2518 unsigned InitSaveExecReg,
2520 bool UseGPRIdxMode) {
2521 MachineBasicBlock::iterator I = LoopBB.begin();
2523 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2524 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2525 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2526 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2528 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2534 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2535 .addReg(InitSaveExecReg)
2540 // Read the next variant <- also loop target.
2541 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2542 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2544 // Compare the just read M0 value to all possible Idx values.
2545 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2546 .addReg(CurrentIdxReg)
2547 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2549 if (UseGPRIdxMode) {
2552 IdxReg = CurrentIdxReg;
2554 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2555 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2556 .addReg(CurrentIdxReg, RegState::Kill)
2560 MachineInstr *SetIdx =
2561 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
2562 .addReg(IdxReg, RegState::Kill);
2563 SetIdx->getOperand(2).setIsUndef();
2565 // Move index from VCC into M0
2567 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2568 .addReg(CurrentIdxReg, RegState::Kill);
2570 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2571 .addReg(CurrentIdxReg, RegState::Kill)
2576 // Update EXEC, save the original EXEC value to VCC.
2577 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2578 .addReg(CondReg, RegState::Kill);
2580 MRI.setSimpleHint(NewExec, CondReg);
2582 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2583 MachineInstr *InsertPt =
2584 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2585 .addReg(AMDGPU::EXEC)
2588 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2591 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2592 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2595 return InsertPt->getIterator();
2598 // This has slightly sub-optimal regalloc when the source vector is killed by
2599 // the read. The register allocator does not understand that the kill is
2600 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2601 // subregister from it, using 1 more VGPR than necessary. This was saved when
2602 // this was expanded after register allocation.
2603 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2604 MachineBasicBlock &MBB,
2606 unsigned InitResultReg,
2609 bool UseGPRIdxMode) {
2610 MachineFunction *MF = MBB.getParent();
2611 MachineRegisterInfo &MRI = MF->getRegInfo();
2612 const DebugLoc &DL = MI.getDebugLoc();
2613 MachineBasicBlock::iterator I(&MI);
2615 unsigned DstReg = MI.getOperand(0).getReg();
2616 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2617 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2619 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2621 // Save the EXEC mask
2622 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2623 .addReg(AMDGPU::EXEC);
2625 // To insert the loop we need to split the block. Move everything after this
2626 // point to a new block, and insert a new empty block between the two.
2627 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2628 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2629 MachineFunction::iterator MBBI(MBB);
2632 MF->insert(MBBI, LoopBB);
2633 MF->insert(MBBI, RemainderBB);
2635 LoopBB->addSuccessor(LoopBB);
2636 LoopBB->addSuccessor(RemainderBB);
2638 // Move the rest of the block into a new block.
2639 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2640 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2642 MBB.addSuccessor(LoopBB);
2644 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2646 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2647 InitResultReg, DstReg, PhiReg, TmpExec,
2648 Offset, UseGPRIdxMode);
2650 MachineBasicBlock::iterator First = RemainderBB->begin();
2651 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2657 // Returns subreg index, offset
2658 static std::pair<unsigned, int>
2659 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2660 const TargetRegisterClass *SuperRC,
2663 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2665 // Skip out of bounds offsets, or else we would end up using an undefined
2667 if (Offset >= NumElts || Offset < 0)
2668 return std::make_pair(AMDGPU::sub0, Offset);
2670 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2673 // Return true if the index is an SGPR and was set.
2674 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2675 MachineRegisterInfo &MRI,
2679 bool IsIndirectSrc) {
2680 MachineBasicBlock *MBB = MI.getParent();
2681 const DebugLoc &DL = MI.getDebugLoc();
2682 MachineBasicBlock::iterator I(&MI);
2684 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2685 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2687 assert(Idx->getReg() != AMDGPU::NoRegister);
2689 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2692 if (UseGPRIdxMode) {
2693 unsigned IdxMode = IsIndirectSrc ?
2694 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2696 MachineInstr *SetOn =
2697 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2701 SetOn->getOperand(3).setIsUndef();
2703 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2704 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2707 MachineInstr *SetOn =
2708 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2709 .addReg(Tmp, RegState::Kill)
2712 SetOn->getOperand(3).setIsUndef();
2719 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2722 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2730 // Control flow needs to be inserted if indexing with a VGPR.
2731 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2732 MachineBasicBlock &MBB,
2733 const SISubtarget &ST) {
2734 const SIInstrInfo *TII = ST.getInstrInfo();
2735 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2736 MachineFunction *MF = MBB.getParent();
2737 MachineRegisterInfo &MRI = MF->getRegInfo();
2739 unsigned Dst = MI.getOperand(0).getReg();
2740 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2741 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2743 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2746 std::tie(SubReg, Offset)
2747 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2749 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2751 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2752 MachineBasicBlock::iterator I(&MI);
2753 const DebugLoc &DL = MI.getDebugLoc();
2755 if (UseGPRIdxMode) {
2756 // TODO: Look at the uses to avoid the copy. This may require rescheduling
2757 // to avoid interfering with other uses, so probably requires a new
2758 // optimization pass.
2759 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2760 .addReg(SrcReg, RegState::Undef, SubReg)
2761 .addReg(SrcReg, RegState::Implicit)
2762 .addReg(AMDGPU::M0, RegState::Implicit);
2763 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2765 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2766 .addReg(SrcReg, RegState::Undef, SubReg)
2767 .addReg(SrcReg, RegState::Implicit);
2770 MI.eraseFromParent();
2775 const DebugLoc &DL = MI.getDebugLoc();
2776 MachineBasicBlock::iterator I(&MI);
2778 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2779 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2781 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
2783 if (UseGPRIdxMode) {
2784 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2785 .addImm(0) // Reset inside loop.
2786 .addImm(VGPRIndexMode::SRC0_ENABLE);
2787 SetOn->getOperand(3).setIsUndef();
2789 // Disable again after the loop.
2790 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2793 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
2794 MachineBasicBlock *LoopBB = InsPt->getParent();
2796 if (UseGPRIdxMode) {
2797 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2798 .addReg(SrcReg, RegState::Undef, SubReg)
2799 .addReg(SrcReg, RegState::Implicit)
2800 .addReg(AMDGPU::M0, RegState::Implicit);
2802 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2803 .addReg(SrcReg, RegState::Undef, SubReg)
2804 .addReg(SrcReg, RegState::Implicit);
2807 MI.eraseFromParent();
2812 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
2813 const TargetRegisterClass *VecRC) {
2814 switch (TRI.getRegSizeInBits(*VecRC)) {
2816 return AMDGPU::V_MOVRELD_B32_V1;
2818 return AMDGPU::V_MOVRELD_B32_V2;
2819 case 128: // 16 bytes
2820 return AMDGPU::V_MOVRELD_B32_V4;
2821 case 256: // 32 bytes
2822 return AMDGPU::V_MOVRELD_B32_V8;
2823 case 512: // 64 bytes
2824 return AMDGPU::V_MOVRELD_B32_V16;
2826 llvm_unreachable("unsupported size for MOVRELD pseudos");
2830 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
2831 MachineBasicBlock &MBB,
2832 const SISubtarget &ST) {
2833 const SIInstrInfo *TII = ST.getInstrInfo();
2834 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2835 MachineFunction *MF = MBB.getParent();
2836 MachineRegisterInfo &MRI = MF->getRegInfo();
2838 unsigned Dst = MI.getOperand(0).getReg();
2839 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
2840 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2841 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
2842 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2843 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
2845 // This can be an immediate, but will be folded later.
2846 assert(Val->getReg());
2849 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
2852 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2854 if (Idx->getReg() == AMDGPU::NoRegister) {
2855 MachineBasicBlock::iterator I(&MI);
2856 const DebugLoc &DL = MI.getDebugLoc();
2858 assert(Offset == 0);
2860 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
2865 MI.eraseFromParent();
2869 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
2870 MachineBasicBlock::iterator I(&MI);
2871 const DebugLoc &DL = MI.getDebugLoc();
2873 if (UseGPRIdxMode) {
2874 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2875 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
2877 .addReg(Dst, RegState::ImplicitDefine)
2878 .addReg(SrcVec->getReg(), RegState::Implicit)
2879 .addReg(AMDGPU::M0, RegState::Implicit);
2881 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2883 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2885 BuildMI(MBB, I, DL, MovRelDesc)
2886 .addReg(Dst, RegState::Define)
2887 .addReg(SrcVec->getReg())
2889 .addImm(SubReg - AMDGPU::sub0);
2892 MI.eraseFromParent();
2897 MRI.clearKillFlags(Val->getReg());
2899 const DebugLoc &DL = MI.getDebugLoc();
2901 if (UseGPRIdxMode) {
2902 MachineBasicBlock::iterator I(&MI);
2904 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2905 .addImm(0) // Reset inside loop.
2906 .addImm(VGPRIndexMode::DST_ENABLE);
2907 SetOn->getOperand(3).setIsUndef();
2909 // Disable again after the loop.
2910 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2913 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
2915 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
2916 Offset, UseGPRIdxMode);
2917 MachineBasicBlock *LoopBB = InsPt->getParent();
2919 if (UseGPRIdxMode) {
2920 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2921 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
2923 .addReg(Dst, RegState::ImplicitDefine)
2924 .addReg(PhiReg, RegState::Implicit)
2925 .addReg(AMDGPU::M0, RegState::Implicit);
2927 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2929 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
2930 .addReg(Dst, RegState::Define)
2933 .addImm(SubReg - AMDGPU::sub0);
2936 MI.eraseFromParent();
2941 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
2942 MachineInstr &MI, MachineBasicBlock *BB) const {
2944 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2945 MachineFunction *MF = BB->getParent();
2946 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
2948 if (TII->isMIMG(MI)) {
2949 if (!MI.memoperands_empty())
2951 // Add a memoperand for mimg instructions so that they aren't assumed to
2952 // be ordered memory instuctions.
2954 MachinePointerInfo PtrInfo(MFI->getImagePSV());
2955 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
2957 Flags |= MachineMemOperand::MOStore;
2960 Flags |= MachineMemOperand::MOLoad;
2962 if (Flags != MachineMemOperand::MODereferenceable) {
2963 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
2964 MI.addMemOperand(*MF, MMO);
2970 switch (MI.getOpcode()) {
2971 case AMDGPU::S_ADD_U64_PSEUDO:
2972 case AMDGPU::S_SUB_U64_PSEUDO: {
2973 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2974 const DebugLoc &DL = MI.getDebugLoc();
2976 MachineOperand &Dest = MI.getOperand(0);
2977 MachineOperand &Src0 = MI.getOperand(1);
2978 MachineOperand &Src1 = MI.getOperand(2);
2980 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2981 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2983 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
2984 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
2985 &AMDGPU::SReg_32_XM0RegClass);
2986 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
2987 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
2988 &AMDGPU::SReg_32_XM0RegClass);
2990 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
2991 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
2992 &AMDGPU::SReg_32_XM0RegClass);
2993 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
2994 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
2995 &AMDGPU::SReg_32_XM0RegClass);
2997 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
2999 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3000 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3001 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3004 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3007 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3009 .addImm(AMDGPU::sub0)
3011 .addImm(AMDGPU::sub1);
3012 MI.eraseFromParent();
3015 case AMDGPU::SI_INIT_M0: {
3016 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3017 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3018 .add(MI.getOperand(0));
3019 MI.eraseFromParent();
3022 case AMDGPU::SI_INIT_EXEC:
3023 // This should be before all vector instructions.
3024 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3026 .addImm(MI.getOperand(0).getImm());
3027 MI.eraseFromParent();
3030 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3031 // Extract the thread count from an SGPR input and set EXEC accordingly.
3032 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3034 // S_BFE_U32 count, input, {shift, 7}
3035 // S_BFM_B64 exec, count, 0
3036 // S_CMP_EQ_U32 count, 64
3037 // S_CMOV_B64 exec, -1
3038 MachineInstr *FirstMI = &*BB->begin();
3039 MachineRegisterInfo &MRI = MF->getRegInfo();
3040 unsigned InputReg = MI.getOperand(0).getReg();
3041 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3044 // Move the COPY of the input reg to the beginning, so that we can use it.
3045 for (auto I = BB->begin(); I != &MI; I++) {
3046 if (I->getOpcode() != TargetOpcode::COPY ||
3047 I->getOperand(0).getReg() != InputReg)
3051 FirstMI = &*++BB->begin();
3053 I->removeFromParent();
3054 BB->insert(FirstMI, &*I);
3062 // This should be before all vector instructions.
3063 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3065 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3066 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3070 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3071 .addReg(CountReg, RegState::Kill)
3073 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3076 MI.eraseFromParent();
3080 case AMDGPU::GET_GROUPSTATICSIZE: {
3081 DebugLoc DL = MI.getDebugLoc();
3082 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3083 .add(MI.getOperand(0))
3084 .addImm(MFI->getLDSSize());
3085 MI.eraseFromParent();
3088 case AMDGPU::SI_INDIRECT_SRC_V1:
3089 case AMDGPU::SI_INDIRECT_SRC_V2:
3090 case AMDGPU::SI_INDIRECT_SRC_V4:
3091 case AMDGPU::SI_INDIRECT_SRC_V8:
3092 case AMDGPU::SI_INDIRECT_SRC_V16:
3093 return emitIndirectSrc(MI, *BB, *getSubtarget());
3094 case AMDGPU::SI_INDIRECT_DST_V1:
3095 case AMDGPU::SI_INDIRECT_DST_V2:
3096 case AMDGPU::SI_INDIRECT_DST_V4:
3097 case AMDGPU::SI_INDIRECT_DST_V8:
3098 case AMDGPU::SI_INDIRECT_DST_V16:
3099 return emitIndirectDst(MI, *BB, *getSubtarget());
3100 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3101 case AMDGPU::SI_KILL_I1_PSEUDO:
3102 return splitKillBlock(MI, BB);
3103 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3104 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3106 unsigned Dst = MI.getOperand(0).getReg();
3107 unsigned Src0 = MI.getOperand(1).getReg();
3108 unsigned Src1 = MI.getOperand(2).getReg();
3109 const DebugLoc &DL = MI.getDebugLoc();
3110 unsigned SrcCond = MI.getOperand(3).getReg();
3112 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3113 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3114 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3116 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3118 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3119 .addReg(Src0, 0, AMDGPU::sub0)
3120 .addReg(Src1, 0, AMDGPU::sub0)
3121 .addReg(SrcCondCopy);
3122 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3123 .addReg(Src0, 0, AMDGPU::sub1)
3124 .addReg(Src1, 0, AMDGPU::sub1)
3125 .addReg(SrcCondCopy);
3127 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3129 .addImm(AMDGPU::sub0)
3131 .addImm(AMDGPU::sub1);
3132 MI.eraseFromParent();
3135 case AMDGPU::SI_BR_UNDEF: {
3136 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3137 const DebugLoc &DL = MI.getDebugLoc();
3138 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3139 .add(MI.getOperand(0));
3140 Br->getOperand(1).setIsUndef(true); // read undef SCC
3141 MI.eraseFromParent();
3144 case AMDGPU::ADJCALLSTACKUP:
3145 case AMDGPU::ADJCALLSTACKDOWN: {
3146 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3147 MachineInstrBuilder MIB(*MF, &MI);
3148 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3149 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
3152 case AMDGPU::SI_CALL_ISEL:
3153 case AMDGPU::SI_TCRETURN_ISEL: {
3154 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3155 const DebugLoc &DL = MI.getDebugLoc();
3156 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3158 MachineRegisterInfo &MRI = MF->getRegInfo();
3159 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3160 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3161 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3163 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3165 MachineInstrBuilder MIB;
3166 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3167 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3168 .add(MI.getOperand(0))
3169 .addGlobalAddress(G);
3171 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3172 .add(MI.getOperand(0))
3173 .addGlobalAddress(G);
3175 // There is an additional imm operand for tcreturn, but it should be in the
3176 // right place already.
3179 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3180 MIB.add(MI.getOperand(I));
3182 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3183 MI.eraseFromParent();
3187 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3191 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3192 return isTypeLegal(VT.getScalarType());
3195 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3196 // This currently forces unfolding various combinations of fsub into fma with
3197 // free fneg'd operands. As long as we have fast FMA (controlled by
3198 // isFMAFasterThanFMulAndFAdd), we should perform these.
3200 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3201 // most of these combines appear to be cycle neutral but save on instruction
3202 // count / code size.
3206 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3208 if (!VT.isVector()) {
3211 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3214 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3215 // TODO: Should i16 be used always if legal? For now it would force VALU
3217 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3220 // Answering this is somewhat tricky and depends on the specific device which
3221 // have different rates for fma or all f64 operations.
3223 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3224 // regardless of which device (although the number of cycles differs between
3225 // devices), so it is always profitable for f64.
3227 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3228 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3229 // which we can always do even without fused FP ops since it returns the same
3230 // result as the separate operations and since it is always full
3231 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3232 // however does not support denormals, so we do report fma as faster if we have
3233 // a fast fma device and require denormals.
3235 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3236 VT = VT.getScalarType();
3238 switch (VT.getSimpleVT().SimpleTy) {
3240 // This is as fast on some subtargets. However, we always have full rate f32
3241 // mad available which returns the same result as the separate operations
3242 // which we should prefer over fma. We can't use this if we want to support
3243 // denormals, so only report this in these cases.
3244 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
3248 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3256 //===----------------------------------------------------------------------===//
3257 // Custom DAG Lowering Operations
3258 //===----------------------------------------------------------------------===//
3260 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3261 switch (Op.getOpcode()) {
3262 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3263 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3265 SDValue Result = LowerLOAD(Op, DAG);
3266 assert((!Result.getNode() ||
3267 Result.getNode()->getNumValues() == 2) &&
3268 "Load should return a value and a chain");
3274 return LowerTrig(Op, DAG);
3275 case ISD::SELECT: return LowerSELECT(Op, DAG);
3276 case ISD::FDIV: return LowerFDIV(Op, DAG);
3277 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3278 case ISD::STORE: return LowerSTORE(Op, DAG);
3279 case ISD::GlobalAddress: {
3280 MachineFunction &MF = DAG.getMachineFunction();
3281 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3282 return LowerGlobalAddress(MFI, Op, DAG);
3284 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3285 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3286 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3287 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3288 case ISD::INSERT_VECTOR_ELT:
3289 return lowerINSERT_VECTOR_ELT(Op, DAG);
3290 case ISD::EXTRACT_VECTOR_ELT:
3291 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3293 return lowerFP_ROUND(Op, DAG);
3295 case ISD::DEBUGTRAP:
3296 return lowerTRAP(Op, DAG);
3301 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3302 SmallVectorImpl<SDValue> &Results,
3303 SelectionDAG &DAG) const {
3304 switch (N->getOpcode()) {
3305 case ISD::INSERT_VECTOR_ELT: {
3306 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3307 Results.push_back(Res);
3310 case ISD::EXTRACT_VECTOR_ELT: {
3311 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3312 Results.push_back(Res);
3315 case ISD::INTRINSIC_WO_CHAIN: {
3316 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3317 if (IID == Intrinsic::amdgcn_cvt_pkrtz) {
3318 SDValue Src0 = N->getOperand(1);
3319 SDValue Src1 = N->getOperand(2);
3321 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3323 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3330 EVT VT = N->getValueType(0);
3331 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3332 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3333 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3335 EVT SelectVT = NewVT;
3336 if (NewVT.bitsLT(MVT::i32)) {
3337 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3338 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3339 SelectVT = MVT::i32;
3342 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3343 N->getOperand(0), LHS, RHS);
3345 if (NewVT != SelectVT)
3346 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3347 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3355 /// \brief Helper function for LowerBRCOND
3356 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3358 SDNode *Parent = Value.getNode();
3359 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3362 if (I.getUse().get() != Value)
3365 if (I->getOpcode() == Opcode)
3371 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3372 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3373 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3374 case Intrinsic::amdgcn_if:
3375 return AMDGPUISD::IF;
3376 case Intrinsic::amdgcn_else:
3377 return AMDGPUISD::ELSE;
3378 case Intrinsic::amdgcn_loop:
3379 return AMDGPUISD::LOOP;
3380 case Intrinsic::amdgcn_end_cf:
3381 llvm_unreachable("should not occur");
3387 // break, if_break, else_break are all only used as inputs to loop, not
3388 // directly as branch conditions.
3392 void SITargetLowering::createDebuggerPrologueStackObjects(
3393 MachineFunction &MF) const {
3394 // Create stack objects that are used for emitting debugger prologue.
3396 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3397 // at fixed location in the following format:
3398 // offset 0: work group ID x
3399 // offset 4: work group ID y
3400 // offset 8: work group ID z
3401 // offset 16: work item ID x
3402 // offset 20: work item ID y
3403 // offset 24: work item ID z
3404 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3407 // For each dimension:
3408 for (unsigned i = 0; i < 3; ++i) {
3409 // Create fixed stack object for work group ID.
3410 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3411 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3412 // Create fixed stack object for work item ID.
3413 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3414 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3418 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3419 const Triple &TT = getTargetMachine().getTargetTriple();
3420 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
3421 AMDGPU::shouldEmitConstantsToTextSection(TT);
3424 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3425 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3426 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
3427 !shouldEmitFixup(GV) &&
3428 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3431 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3432 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3435 /// This transforms the control flow intrinsics to get the branch destination as
3436 /// last parameter, also switches branch target with BR if the need arise
3437 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3438 SelectionDAG &DAG) const {
3441 SDNode *Intr = BRCOND.getOperand(1).getNode();
3442 SDValue Target = BRCOND.getOperand(2);
3443 SDNode *BR = nullptr;
3444 SDNode *SetCC = nullptr;
3446 if (Intr->getOpcode() == ISD::SETCC) {
3447 // As long as we negate the condition everything is fine
3449 Intr = SetCC->getOperand(0).getNode();
3452 // Get the target from BR if we don't negate the condition
3453 BR = findUser(BRCOND, ISD::BR);
3454 Target = BR->getOperand(1);
3457 // FIXME: This changes the types of the intrinsics instead of introducing new
3458 // nodes with the correct types.
3459 // e.g. llvm.amdgcn.loop
3461 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3462 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3464 unsigned CFNode = isCFIntrinsic(Intr);
3466 // This is a uniform branch so we don't need to legalize.
3470 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3471 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3474 (SetCC->getConstantOperandVal(1) == 1 &&
3475 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3478 // operands of the new intrinsic call
3479 SmallVector<SDValue, 4> Ops;
3481 Ops.push_back(BRCOND.getOperand(0));
3483 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
3484 Ops.push_back(Target);
3486 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3488 // build the new intrinsic call
3489 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3494 BRCOND.getOperand(0)
3497 Result = DAG.getMergeValues(Ops, DL).getNode();
3501 // Give the branch instruction our target
3504 BRCOND.getOperand(2)
3506 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3507 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3508 BR = NewBR.getNode();
3511 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3513 // Copy the intrinsic results to registers
3514 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3515 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3519 Chain = DAG.getCopyToReg(
3521 CopyToReg->getOperand(1),
3522 SDValue(Result, i - 1),
3525 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3528 // Remove the old intrinsic from the chain
3529 DAG.ReplaceAllUsesOfValueWith(
3530 SDValue(Intr, Intr->getNumValues() - 1),
3531 Intr->getOperand(0));
3536 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3540 return Op.getValueType().bitsLE(VT) ?
3541 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3542 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3545 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3546 assert(Op.getValueType() == MVT::f16 &&
3547 "Do not know how to custom lower FP_ROUND for non-f16 type");
3549 SDValue Src = Op.getOperand(0);
3550 EVT SrcVT = Src.getValueType();
3551 if (SrcVT != MVT::f64)
3556 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3557 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3558 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3561 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3563 MachineFunction &MF = DAG.getMachineFunction();
3564 SDValue Chain = Op.getOperand(0);
3566 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
3567 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
3569 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
3570 Subtarget->isTrapHandlerEnabled()) {
3571 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3572 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3573 assert(UserSGPR != AMDGPU::NoRegister);
3575 SDValue QueuePtr = CreateLiveInRegister(
3576 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3578 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3580 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3581 QueuePtr, SDValue());
3585 DAG.getTargetConstant(TrapID, SL, MVT::i16),
3590 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
3594 case SISubtarget::TrapIDLLVMTrap:
3595 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3596 case SISubtarget::TrapIDLLVMDebugTrap: {
3597 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
3598 "debugtrap handler not supported",
3601 LLVMContext &Ctx = MF.getFunction().getContext();
3602 Ctx.diagnose(NoTrap);
3606 llvm_unreachable("unsupported trap handler type!");
3612 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
3613 SelectionDAG &DAG) const {
3614 // FIXME: Use inline constants (src_{shared, private}_base) instead.
3615 if (Subtarget->hasApertureRegs()) {
3616 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
3617 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
3618 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
3619 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
3620 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
3621 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
3623 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
3624 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
3625 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
3627 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
3628 SDValue ApertureReg = SDValue(
3629 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
3630 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
3631 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
3634 MachineFunction &MF = DAG.getMachineFunction();
3635 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3636 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3637 assert(UserSGPR != AMDGPU::NoRegister);
3639 SDValue QueuePtr = CreateLiveInRegister(
3640 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3642 // Offset into amd_queue_t for group_segment_aperture_base_hi /
3643 // private_segment_aperture_base_hi.
3644 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
3646 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
3648 // TODO: Use custom target PseudoSourceValue.
3649 // TODO: We should use the value from the IR intrinsic call, but it might not
3650 // be available and how do we get it?
3651 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
3652 AMDGPUASI.CONSTANT_ADDRESS));
3654 MachinePointerInfo PtrInfo(V, StructOffset);
3655 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
3656 MinAlign(64, StructOffset),
3657 MachineMemOperand::MODereferenceable |
3658 MachineMemOperand::MOInvariant);
3661 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
3662 SelectionDAG &DAG) const {
3664 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
3666 SDValue Src = ASC->getOperand(0);
3667 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
3669 const AMDGPUTargetMachine &TM =
3670 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
3672 // flat -> local/private
3673 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3674 unsigned DestAS = ASC->getDestAddressSpace();
3676 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
3677 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
3678 unsigned NullVal = TM.getNullPointerValue(DestAS);
3679 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3680 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
3681 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
3683 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
3684 NonNull, Ptr, SegmentNullPtr);
3688 // local/private -> flat
3689 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
3690 unsigned SrcAS = ASC->getSrcAddressSpace();
3692 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
3693 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
3694 unsigned NullVal = TM.getNullPointerValue(SrcAS);
3695 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
3698 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
3700 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
3702 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
3704 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
3705 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
3710 // global <-> flat are no-ops and never emitted.
3712 const MachineFunction &MF = DAG.getMachineFunction();
3713 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
3714 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
3715 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
3717 return DAG.getUNDEF(ASC->getValueType(0));
3720 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3721 SelectionDAG &DAG) const {
3722 SDValue Idx = Op.getOperand(2);
3723 if (isa<ConstantSDNode>(Idx))
3726 // Avoid stack access for dynamic indexing.
3728 SDValue Vec = Op.getOperand(0);
3729 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
3731 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
3732 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
3734 // Convert vector index to bit-index.
3735 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
3736 DAG.getConstant(16, SL, MVT::i32));
3738 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3740 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
3741 DAG.getConstant(0xffff, SL, MVT::i32),
3744 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
3745 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
3746 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
3748 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
3749 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
3752 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3753 SelectionDAG &DAG) const {
3756 EVT ResultVT = Op.getValueType();
3757 SDValue Vec = Op.getOperand(0);
3758 SDValue Idx = Op.getOperand(1);
3760 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
3762 // Make sure we we do any optimizations that will make it easier to fold
3763 // source modifiers before obscuring it with bit operations.
3765 // XXX - Why doesn't this get called when vector_shuffle is expanded?
3766 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
3769 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3770 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3772 if (CIdx->getZExtValue() == 1) {
3773 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
3774 DAG.getConstant(16, SL, MVT::i32));
3776 assert(CIdx->getZExtValue() == 0);
3779 if (ResultVT.bitsLT(MVT::i32))
3780 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3781 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
3784 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
3786 // Convert vector index to bit-index.
3787 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
3789 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3790 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
3792 SDValue Result = Elt;
3793 if (ResultVT.bitsLT(MVT::i32))
3794 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
3796 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
3800 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3801 // We can fold offsets for anything that doesn't require a GOT relocation.
3802 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3803 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
3804 !shouldEmitGOTReloc(GA->getGlobal());
3808 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
3809 const SDLoc &DL, unsigned Offset, EVT PtrVT,
3810 unsigned GAFlags = SIInstrInfo::MO_NONE) {
3811 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
3812 // lowered to the following code sequence:
3814 // For constant address space:
3815 // s_getpc_b64 s[0:1]
3816 // s_add_u32 s0, s0, $symbol
3817 // s_addc_u32 s1, s1, 0
3819 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3820 // a fixup or relocation is emitted to replace $symbol with a literal
3821 // constant, which is a pc-relative offset from the encoding of the $symbol
3822 // operand to the global variable.
3824 // For global address space:
3825 // s_getpc_b64 s[0:1]
3826 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
3827 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
3829 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
3830 // fixups or relocations are emitted to replace $symbol@*@lo and
3831 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
3832 // which is a 64-bit pc-relative offset from the encoding of the $symbol
3833 // operand to the global variable.
3835 // What we want here is an offset from the value returned by s_getpc
3836 // (which is the address of the s_add_u32 instruction) to the global
3837 // variable, but since the encoding of $symbol starts 4 bytes after the start
3838 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
3839 // small. This requires us to add 4 to the global variable offset in order to
3840 // compute the correct address.
3841 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
3843 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
3844 GAFlags == SIInstrInfo::MO_NONE ?
3845 GAFlags : GAFlags + 1);
3846 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
3849 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
3851 SelectionDAG &DAG) const {
3852 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
3853 const GlobalValue *GV = GSD->getGlobal();
3855 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
3856 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
3857 // FIXME: It isn't correct to rely on the type of the pointer. This should
3858 // be removed when address space 0 is 64-bit.
3859 !GV->getType()->getElementType()->isFunctionTy())
3860 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
3863 EVT PtrVT = Op.getValueType();
3865 if (shouldEmitFixup(GV))
3866 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
3867 else if (shouldEmitPCReloc(GV))
3868 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
3869 SIInstrInfo::MO_REL32);
3871 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
3872 SIInstrInfo::MO_GOTPCREL32);
3874 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
3875 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
3876 const DataLayout &DataLayout = DAG.getDataLayout();
3877 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
3878 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
3879 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
3881 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
3882 MachineMemOperand::MODereferenceable |
3883 MachineMemOperand::MOInvariant);
3886 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
3887 const SDLoc &DL, SDValue V) const {
3888 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
3889 // the destination register.
3891 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
3892 // so we will end up with redundant moves to m0.
3894 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
3896 // A Null SDValue creates a glue result.
3897 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
3899 return SDValue(M0, 0);
3902 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
3905 unsigned Offset) const {
3907 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
3908 DAG.getEntryNode(), Offset, false);
3909 // The local size values will have the hi 16-bits as zero.
3910 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
3911 DAG.getValueType(VT));
3914 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
3916 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
3917 "non-hsa intrinsic with hsa target",
3919 DAG.getContext()->diagnose(BadIntrin);
3920 return DAG.getUNDEF(VT);
3923 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
3925 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
3926 "intrinsic not supported on subtarget",
3928 DAG.getContext()->diagnose(BadIntrin);
3929 return DAG.getUNDEF(VT);
3932 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3933 SelectionDAG &DAG) const {
3934 MachineFunction &MF = DAG.getMachineFunction();
3935 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
3937 EVT VT = Op.getValueType();
3939 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3941 // TODO: Should this propagate fast-math-flags?
3943 switch (IntrinsicID) {
3944 case Intrinsic::amdgcn_implicit_buffer_ptr: {
3945 if (getSubtarget()->isAmdCodeObjectV2(MF))
3946 return emitNonHSAIntrinsicError(DAG, DL, VT);
3947 return getPreloadedValue(DAG, *MFI, VT,
3948 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
3950 case Intrinsic::amdgcn_dispatch_ptr:
3951 case Intrinsic::amdgcn_queue_ptr: {
3952 if (!Subtarget->isAmdCodeObjectV2(MF)) {
3953 DiagnosticInfoUnsupported BadIntrin(
3954 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
3956 DAG.getContext()->diagnose(BadIntrin);
3957 return DAG.getUNDEF(VT);
3960 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
3961 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
3962 return getPreloadedValue(DAG, *MFI, VT, RegID);
3964 case Intrinsic::amdgcn_implicitarg_ptr: {
3965 if (MFI->isEntryFunction())
3966 return getImplicitArgPtr(DAG, DL);
3967 return getPreloadedValue(DAG, *MFI, VT,
3968 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
3970 case Intrinsic::amdgcn_kernarg_segment_ptr: {
3971 return getPreloadedValue(DAG, *MFI, VT,
3972 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
3974 case Intrinsic::amdgcn_dispatch_id: {
3975 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
3977 case Intrinsic::amdgcn_rcp:
3978 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
3979 case Intrinsic::amdgcn_rsq:
3980 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3981 case Intrinsic::amdgcn_rsq_legacy:
3982 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3983 return emitRemovedIntrinsicError(DAG, DL, VT);
3985 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
3986 case Intrinsic::amdgcn_rcp_legacy:
3987 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3988 return emitRemovedIntrinsicError(DAG, DL, VT);
3989 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
3990 case Intrinsic::amdgcn_rsq_clamp: {
3991 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3992 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
3994 Type *Type = VT.getTypeForEVT(*DAG.getContext());
3995 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
3996 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
3998 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3999 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4000 DAG.getConstantFP(Max, DL, VT));
4001 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4002 DAG.getConstantFP(Min, DL, VT));
4004 case Intrinsic::r600_read_ngroups_x:
4005 if (Subtarget->isAmdHsaOS())
4006 return emitNonHSAIntrinsicError(DAG, DL, VT);
4008 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4009 SI::KernelInputOffsets::NGROUPS_X, false);
4010 case Intrinsic::r600_read_ngroups_y:
4011 if (Subtarget->isAmdHsaOS())
4012 return emitNonHSAIntrinsicError(DAG, DL, VT);
4014 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4015 SI::KernelInputOffsets::NGROUPS_Y, false);
4016 case Intrinsic::r600_read_ngroups_z:
4017 if (Subtarget->isAmdHsaOS())
4018 return emitNonHSAIntrinsicError(DAG, DL, VT);
4020 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4021 SI::KernelInputOffsets::NGROUPS_Z, false);
4022 case Intrinsic::r600_read_global_size_x:
4023 if (Subtarget->isAmdHsaOS())
4024 return emitNonHSAIntrinsicError(DAG, DL, VT);
4026 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4027 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
4028 case Intrinsic::r600_read_global_size_y:
4029 if (Subtarget->isAmdHsaOS())
4030 return emitNonHSAIntrinsicError(DAG, DL, VT);
4032 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4033 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
4034 case Intrinsic::r600_read_global_size_z:
4035 if (Subtarget->isAmdHsaOS())
4036 return emitNonHSAIntrinsicError(DAG, DL, VT);
4038 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4039 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
4040 case Intrinsic::r600_read_local_size_x:
4041 if (Subtarget->isAmdHsaOS())
4042 return emitNonHSAIntrinsicError(DAG, DL, VT);
4044 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4045 SI::KernelInputOffsets::LOCAL_SIZE_X);
4046 case Intrinsic::r600_read_local_size_y:
4047 if (Subtarget->isAmdHsaOS())
4048 return emitNonHSAIntrinsicError(DAG, DL, VT);
4050 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4051 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4052 case Intrinsic::r600_read_local_size_z:
4053 if (Subtarget->isAmdHsaOS())
4054 return emitNonHSAIntrinsicError(DAG, DL, VT);
4056 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4057 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4058 case Intrinsic::amdgcn_workgroup_id_x:
4059 case Intrinsic::r600_read_tgid_x:
4060 return getPreloadedValue(DAG, *MFI, VT,
4061 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4062 case Intrinsic::amdgcn_workgroup_id_y:
4063 case Intrinsic::r600_read_tgid_y:
4064 return getPreloadedValue(DAG, *MFI, VT,
4065 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4066 case Intrinsic::amdgcn_workgroup_id_z:
4067 case Intrinsic::r600_read_tgid_z:
4068 return getPreloadedValue(DAG, *MFI, VT,
4069 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4070 case Intrinsic::amdgcn_workitem_id_x: {
4071 case Intrinsic::r600_read_tidig_x:
4072 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4073 SDLoc(DAG.getEntryNode()),
4074 MFI->getArgInfo().WorkItemIDX);
4076 case Intrinsic::amdgcn_workitem_id_y:
4077 case Intrinsic::r600_read_tidig_y:
4078 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4079 SDLoc(DAG.getEntryNode()),
4080 MFI->getArgInfo().WorkItemIDY);
4081 case Intrinsic::amdgcn_workitem_id_z:
4082 case Intrinsic::r600_read_tidig_z:
4083 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4084 SDLoc(DAG.getEntryNode()),
4085 MFI->getArgInfo().WorkItemIDZ);
4086 case AMDGPUIntrinsic::SI_load_const: {
4092 MachineMemOperand *MMO = MF.getMachineMemOperand(
4093 MachinePointerInfo(),
4094 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4095 MachineMemOperand::MOInvariant,
4096 VT.getStoreSize(), 4);
4097 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4098 Op->getVTList(), Ops, VT, MMO);
4100 case Intrinsic::amdgcn_fdiv_fast:
4101 return lowerFDIV_FAST(Op, DAG);
4102 case Intrinsic::amdgcn_interp_mov: {
4103 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4104 SDValue Glue = M0.getValue(1);
4105 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4106 Op.getOperand(2), Op.getOperand(3), Glue);
4108 case Intrinsic::amdgcn_interp_p1: {
4109 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4110 SDValue Glue = M0.getValue(1);
4111 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4112 Op.getOperand(2), Op.getOperand(3), Glue);
4114 case Intrinsic::amdgcn_interp_p2: {
4115 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4116 SDValue Glue = SDValue(M0.getNode(), 1);
4117 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4118 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4121 case Intrinsic::amdgcn_sin:
4122 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4124 case Intrinsic::amdgcn_cos:
4125 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4127 case Intrinsic::amdgcn_log_clamp: {
4128 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4131 DiagnosticInfoUnsupported BadIntrin(
4132 MF.getFunction(), "intrinsic not supported on subtarget",
4134 DAG.getContext()->diagnose(BadIntrin);
4135 return DAG.getUNDEF(VT);
4137 case Intrinsic::amdgcn_ldexp:
4138 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4139 Op.getOperand(1), Op.getOperand(2));
4141 case Intrinsic::amdgcn_fract:
4142 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4144 case Intrinsic::amdgcn_class:
4145 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4146 Op.getOperand(1), Op.getOperand(2));
4147 case Intrinsic::amdgcn_div_fmas:
4148 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4149 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4152 case Intrinsic::amdgcn_div_fixup:
4153 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4154 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4156 case Intrinsic::amdgcn_trig_preop:
4157 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4158 Op.getOperand(1), Op.getOperand(2));
4159 case Intrinsic::amdgcn_div_scale: {
4160 // 3rd parameter required to be a constant.
4161 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4163 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4165 // Translate to the operands expected by the machine instruction. The
4166 // first parameter must be the same as the first instruction.
4167 SDValue Numerator = Op.getOperand(1);
4168 SDValue Denominator = Op.getOperand(2);
4170 // Note this order is opposite of the machine instruction's operations,
4171 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4172 // intrinsic has the numerator as the first operand to match a normal
4173 // division operation.
4175 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4177 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4178 Denominator, Numerator);
4180 case Intrinsic::amdgcn_icmp: {
4181 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4183 return DAG.getUNDEF(VT);
4185 int CondCode = CD->getSExtValue();
4186 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4187 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4188 return DAG.getUNDEF(VT);
4190 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4191 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4192 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4193 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4195 case Intrinsic::amdgcn_fcmp: {
4196 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4198 return DAG.getUNDEF(VT);
4200 int CondCode = CD->getSExtValue();
4201 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4202 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4203 return DAG.getUNDEF(VT);
4205 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4206 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4207 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4208 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4210 case Intrinsic::amdgcn_fmed3:
4211 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4212 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4213 case Intrinsic::amdgcn_fmul_legacy:
4214 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4215 Op.getOperand(1), Op.getOperand(2));
4216 case Intrinsic::amdgcn_sffbh:
4217 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4218 case Intrinsic::amdgcn_sbfe:
4219 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4220 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4221 case Intrinsic::amdgcn_ubfe:
4222 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4223 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4224 case Intrinsic::amdgcn_cvt_pkrtz: {
4225 // FIXME: Stop adding cast if v2f16 legal.
4226 EVT VT = Op.getValueType();
4227 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
4228 Op.getOperand(1), Op.getOperand(2));
4229 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4231 case Intrinsic::amdgcn_wqm: {
4232 SDValue Src = Op.getOperand(1);
4233 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4236 case Intrinsic::amdgcn_wwm: {
4237 SDValue Src = Op.getOperand(1);
4238 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4241 case Intrinsic::amdgcn_image_getlod:
4242 case Intrinsic::amdgcn_image_getresinfo: {
4243 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4;
4245 // Replace dmask with everything disabled with undef.
4246 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx));
4247 if (!DMask || DMask->isNullValue())
4248 return DAG.getUNDEF(Op.getValueType());
4256 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4257 SelectionDAG &DAG) const {
4258 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4260 MachineFunction &MF = DAG.getMachineFunction();
4263 case Intrinsic::amdgcn_atomic_inc:
4264 case Intrinsic::amdgcn_atomic_dec: {
4265 MemSDNode *M = cast<MemSDNode>(Op);
4266 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
4267 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
4269 M->getOperand(0), // Chain
4270 M->getOperand(2), // Ptr
4271 M->getOperand(3) // Value
4274 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4275 M->getMemoryVT(), M->getMemOperand());
4277 case Intrinsic::amdgcn_buffer_load:
4278 case Intrinsic::amdgcn_buffer_load_format: {
4280 Op.getOperand(0), // Chain
4281 Op.getOperand(2), // rsrc
4282 Op.getOperand(3), // vindex
4283 Op.getOperand(4), // offset
4284 Op.getOperand(5), // glc
4285 Op.getOperand(6) // slc
4287 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4289 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4290 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4291 EVT VT = Op.getValueType();
4292 EVT IntVT = VT.changeTypeToInteger();
4294 MachineMemOperand *MMO = MF.getMachineMemOperand(
4295 MachinePointerInfo(MFI->getBufferPSV()),
4296 MachineMemOperand::MOLoad,
4297 VT.getStoreSize(), VT.getStoreSize());
4299 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
4301 case Intrinsic::amdgcn_tbuffer_load: {
4303 Op.getOperand(0), // Chain
4304 Op.getOperand(2), // rsrc
4305 Op.getOperand(3), // vindex
4306 Op.getOperand(4), // voffset
4307 Op.getOperand(5), // soffset
4308 Op.getOperand(6), // offset
4309 Op.getOperand(7), // dfmt
4310 Op.getOperand(8), // nfmt
4311 Op.getOperand(9), // glc
4312 Op.getOperand(10) // slc
4315 EVT VT = Op.getOperand(2).getValueType();
4317 MachineMemOperand *MMO = MF.getMachineMemOperand(
4318 MachinePointerInfo(),
4319 MachineMemOperand::MOLoad,
4320 VT.getStoreSize(), VT.getStoreSize());
4321 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
4322 Op->getVTList(), Ops, VT, MMO);
4324 case Intrinsic::amdgcn_buffer_atomic_swap:
4325 case Intrinsic::amdgcn_buffer_atomic_add:
4326 case Intrinsic::amdgcn_buffer_atomic_sub:
4327 case Intrinsic::amdgcn_buffer_atomic_smin:
4328 case Intrinsic::amdgcn_buffer_atomic_umin:
4329 case Intrinsic::amdgcn_buffer_atomic_smax:
4330 case Intrinsic::amdgcn_buffer_atomic_umax:
4331 case Intrinsic::amdgcn_buffer_atomic_and:
4332 case Intrinsic::amdgcn_buffer_atomic_or:
4333 case Intrinsic::amdgcn_buffer_atomic_xor: {
4335 Op.getOperand(0), // Chain
4336 Op.getOperand(2), // vdata
4337 Op.getOperand(3), // rsrc
4338 Op.getOperand(4), // vindex
4339 Op.getOperand(5), // offset
4340 Op.getOperand(6) // slc
4342 EVT VT = Op.getOperand(3).getValueType();
4343 MachineMemOperand *MMO = MF.getMachineMemOperand(
4344 MachinePointerInfo(),
4345 MachineMemOperand::MOLoad |
4346 MachineMemOperand::MOStore |
4347 MachineMemOperand::MODereferenceable |
4348 MachineMemOperand::MOVolatile,
4349 VT.getStoreSize(), 4);
4350 unsigned Opcode = 0;
4353 case Intrinsic::amdgcn_buffer_atomic_swap:
4354 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
4356 case Intrinsic::amdgcn_buffer_atomic_add:
4357 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
4359 case Intrinsic::amdgcn_buffer_atomic_sub:
4360 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
4362 case Intrinsic::amdgcn_buffer_atomic_smin:
4363 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
4365 case Intrinsic::amdgcn_buffer_atomic_umin:
4366 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
4368 case Intrinsic::amdgcn_buffer_atomic_smax:
4369 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
4371 case Intrinsic::amdgcn_buffer_atomic_umax:
4372 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
4374 case Intrinsic::amdgcn_buffer_atomic_and:
4375 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
4377 case Intrinsic::amdgcn_buffer_atomic_or:
4378 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
4380 case Intrinsic::amdgcn_buffer_atomic_xor:
4381 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
4384 llvm_unreachable("unhandled atomic opcode");
4387 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, MMO);
4390 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
4392 Op.getOperand(0), // Chain
4393 Op.getOperand(2), // src
4394 Op.getOperand(3), // cmp
4395 Op.getOperand(4), // rsrc
4396 Op.getOperand(5), // vindex
4397 Op.getOperand(6), // offset
4398 Op.getOperand(7) // slc
4400 EVT VT = Op.getOperand(4).getValueType();
4401 MachineMemOperand *MMO = MF.getMachineMemOperand(
4402 MachinePointerInfo(),
4403 MachineMemOperand::MOLoad |
4404 MachineMemOperand::MOStore |
4405 MachineMemOperand::MODereferenceable |
4406 MachineMemOperand::MOVolatile,
4407 VT.getStoreSize(), 4);
4409 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
4410 Op->getVTList(), Ops, VT, MMO);
4414 case Intrinsic::amdgcn_image_sample:
4415 case Intrinsic::amdgcn_image_sample_cl:
4416 case Intrinsic::amdgcn_image_sample_d:
4417 case Intrinsic::amdgcn_image_sample_d_cl:
4418 case Intrinsic::amdgcn_image_sample_l:
4419 case Intrinsic::amdgcn_image_sample_b:
4420 case Intrinsic::amdgcn_image_sample_b_cl:
4421 case Intrinsic::amdgcn_image_sample_lz:
4422 case Intrinsic::amdgcn_image_sample_cd:
4423 case Intrinsic::amdgcn_image_sample_cd_cl:
4425 // Sample with comparison.
4426 case Intrinsic::amdgcn_image_sample_c:
4427 case Intrinsic::amdgcn_image_sample_c_cl:
4428 case Intrinsic::amdgcn_image_sample_c_d:
4429 case Intrinsic::amdgcn_image_sample_c_d_cl:
4430 case Intrinsic::amdgcn_image_sample_c_l:
4431 case Intrinsic::amdgcn_image_sample_c_b:
4432 case Intrinsic::amdgcn_image_sample_c_b_cl:
4433 case Intrinsic::amdgcn_image_sample_c_lz:
4434 case Intrinsic::amdgcn_image_sample_c_cd:
4435 case Intrinsic::amdgcn_image_sample_c_cd_cl:
4437 // Sample with offsets.
4438 case Intrinsic::amdgcn_image_sample_o:
4439 case Intrinsic::amdgcn_image_sample_cl_o:
4440 case Intrinsic::amdgcn_image_sample_d_o:
4441 case Intrinsic::amdgcn_image_sample_d_cl_o:
4442 case Intrinsic::amdgcn_image_sample_l_o:
4443 case Intrinsic::amdgcn_image_sample_b_o:
4444 case Intrinsic::amdgcn_image_sample_b_cl_o:
4445 case Intrinsic::amdgcn_image_sample_lz_o:
4446 case Intrinsic::amdgcn_image_sample_cd_o:
4447 case Intrinsic::amdgcn_image_sample_cd_cl_o:
4449 // Sample with comparison and offsets.
4450 case Intrinsic::amdgcn_image_sample_c_o:
4451 case Intrinsic::amdgcn_image_sample_c_cl_o:
4452 case Intrinsic::amdgcn_image_sample_c_d_o:
4453 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
4454 case Intrinsic::amdgcn_image_sample_c_l_o:
4455 case Intrinsic::amdgcn_image_sample_c_b_o:
4456 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
4457 case Intrinsic::amdgcn_image_sample_c_lz_o:
4458 case Intrinsic::amdgcn_image_sample_c_cd_o:
4459 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: {
4460 // Replace dmask with everything disabled with undef.
4461 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
4462 if (!DMask || DMask->isNullValue()) {
4463 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4464 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
4474 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4475 SelectionDAG &DAG) const {
4477 SDValue Chain = Op.getOperand(0);
4478 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4479 MachineFunction &MF = DAG.getMachineFunction();
4481 switch (IntrinsicID) {
4482 case Intrinsic::amdgcn_exp: {
4483 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4484 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4485 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
4486 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
4488 const SDValue Ops[] = {
4490 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4491 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4492 Op.getOperand(4), // src0
4493 Op.getOperand(5), // src1
4494 Op.getOperand(6), // src2
4495 Op.getOperand(7), // src3
4496 DAG.getTargetConstant(0, DL, MVT::i1), // compr
4497 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4500 unsigned Opc = Done->isNullValue() ?
4501 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4502 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4504 case Intrinsic::amdgcn_exp_compr: {
4505 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
4506 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
4507 SDValue Src0 = Op.getOperand(4);
4508 SDValue Src1 = Op.getOperand(5);
4509 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
4510 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
4512 SDValue Undef = DAG.getUNDEF(MVT::f32);
4513 const SDValue Ops[] = {
4515 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
4516 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
4517 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
4518 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
4521 DAG.getTargetConstant(1, DL, MVT::i1), // compr
4522 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
4525 unsigned Opc = Done->isNullValue() ?
4526 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
4527 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
4529 case Intrinsic::amdgcn_s_sendmsg:
4530 case Intrinsic::amdgcn_s_sendmsghalt: {
4531 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
4532 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
4533 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
4534 SDValue Glue = Chain.getValue(1);
4535 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
4536 Op.getOperand(2), Glue);
4538 case Intrinsic::amdgcn_init_exec: {
4539 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
4542 case Intrinsic::amdgcn_init_exec_from_input: {
4543 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
4544 Op.getOperand(2), Op.getOperand(3));
4546 case AMDGPUIntrinsic::AMDGPU_kill: {
4547 SDValue Src = Op.getOperand(2);
4548 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
4549 if (!K->isNegative())
4552 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
4553 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
4556 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
4557 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
4559 case Intrinsic::amdgcn_s_barrier: {
4560 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
4561 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
4562 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
4563 if (WGSize <= ST.getWavefrontSize())
4564 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
4565 Op.getOperand(0)), 0);
4569 case AMDGPUIntrinsic::SI_tbuffer_store: {
4571 // Extract vindex and voffset from vaddr as appropriate
4572 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
4573 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
4574 SDValue VAddr = Op.getOperand(5);
4576 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
4578 assert(!(OffEn->isOne() && IdxEn->isOne()) &&
4579 "Legacy intrinsic doesn't support both offset and index - use new version");
4581 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
4582 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
4584 // Deal with the vec-3 case
4585 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
4586 auto Opcode = NumChannels->getZExtValue() == 3 ?
4587 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
4591 Op.getOperand(3), // vdata
4592 Op.getOperand(2), // rsrc
4595 Op.getOperand(6), // soffset
4596 Op.getOperand(7), // inst_offset
4597 Op.getOperand(8), // dfmt
4598 Op.getOperand(9), // nfmt
4599 Op.getOperand(12), // glc
4600 Op.getOperand(13), // slc
4603 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
4604 "Value of tfe other than zero is unsupported");
4606 EVT VT = Op.getOperand(3).getValueType();
4607 MachineMemOperand *MMO = MF.getMachineMemOperand(
4608 MachinePointerInfo(),
4609 MachineMemOperand::MOStore,
4610 VT.getStoreSize(), 4);
4611 return DAG.getMemIntrinsicNode(Opcode, DL,
4612 Op->getVTList(), Ops, VT, MMO);
4615 case Intrinsic::amdgcn_tbuffer_store: {
4618 Op.getOperand(2), // vdata
4619 Op.getOperand(3), // rsrc
4620 Op.getOperand(4), // vindex
4621 Op.getOperand(5), // voffset
4622 Op.getOperand(6), // soffset
4623 Op.getOperand(7), // offset
4624 Op.getOperand(8), // dfmt
4625 Op.getOperand(9), // nfmt
4626 Op.getOperand(10), // glc
4627 Op.getOperand(11) // slc
4629 EVT VT = Op.getOperand(3).getValueType();
4630 MachineMemOperand *MMO = MF.getMachineMemOperand(
4631 MachinePointerInfo(),
4632 MachineMemOperand::MOStore,
4633 VT.getStoreSize(), 4);
4634 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
4635 Op->getVTList(), Ops, VT, MMO);
4638 case Intrinsic::amdgcn_buffer_store:
4639 case Intrinsic::amdgcn_buffer_store_format: {
4642 Op.getOperand(2), // vdata
4643 Op.getOperand(3), // rsrc
4644 Op.getOperand(4), // vindex
4645 Op.getOperand(5), // offset
4646 Op.getOperand(6), // glc
4647 Op.getOperand(7) // slc
4649 EVT VT = Op.getOperand(3).getValueType();
4650 MachineMemOperand *MMO = MF.getMachineMemOperand(
4651 MachinePointerInfo(),
4652 MachineMemOperand::MOStore |
4653 MachineMemOperand::MODereferenceable,
4654 VT.getStoreSize(), 4);
4656 unsigned Opcode = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
4657 AMDGPUISD::BUFFER_STORE :
4658 AMDGPUISD::BUFFER_STORE_FORMAT;
4659 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, MMO);
4667 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4669 LoadSDNode *Load = cast<LoadSDNode>(Op);
4670 ISD::LoadExtType ExtType = Load->getExtensionType();
4671 EVT MemVT = Load->getMemoryVT();
4673 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
4674 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
4677 // FIXME: Copied from PPC
4678 // First, load into 32 bits, then truncate to 1 bit.
4680 SDValue Chain = Load->getChain();
4681 SDValue BasePtr = Load->getBasePtr();
4682 MachineMemOperand *MMO = Load->getMemOperand();
4684 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
4686 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
4687 BasePtr, RealMemVT, MMO);
4690 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
4694 return DAG.getMergeValues(Ops, DL);
4697 if (!MemVT.isVector())
4700 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
4701 "Custom lowering for non-i32 vectors hasn't been implemented.");
4703 unsigned AS = Load->getAddressSpace();
4704 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
4705 AS, Load->getAlignment())) {
4707 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
4708 return DAG.getMergeValues(Ops, DL);
4711 MachineFunction &MF = DAG.getMachineFunction();
4712 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4713 // If there is a possibilty that flat instruction access scratch memory
4714 // then we need to use the same legalization rules we use for private.
4715 if (AS == AMDGPUASI.FLAT_ADDRESS)
4716 AS = MFI->hasFlatScratchInit() ?
4717 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
4719 unsigned NumElements = MemVT.getVectorNumElements();
4720 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
4721 if (isMemOpUniform(Load))
4723 // Non-uniform loads will be selected to MUBUF instructions, so they
4724 // have the same legalization requirements as global and private
4728 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
4729 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
4730 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load))
4732 // Non-uniform loads will be selected to MUBUF instructions, so they
4733 // have the same legalization requirements as global and private
4737 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
4738 AS == AMDGPUASI.FLAT_ADDRESS) {
4739 if (NumElements > 4)
4740 return SplitVectorLoad(Op, DAG);
4741 // v4 loads are supported for private and global memory.
4744 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
4745 // Depending on the setting of the private_element_size field in the
4746 // resource descriptor, we can only make private accesses up to a certain
4748 switch (Subtarget->getMaxPrivateElementSize()) {
4750 return scalarizeVectorLoad(Load, DAG);
4752 if (NumElements > 2)
4753 return SplitVectorLoad(Op, DAG);
4756 // Same as global/flat
4757 if (NumElements > 4)
4758 return SplitVectorLoad(Op, DAG);
4761 llvm_unreachable("unsupported private_element_size");
4763 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
4764 if (NumElements > 2)
4765 return SplitVectorLoad(Op, DAG);
4767 if (NumElements == 2)
4770 // If properly aligned, if we split we might be able to use ds_read_b64.
4771 return SplitVectorLoad(Op, DAG);
4776 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4777 if (Op.getValueType() != MVT::i64)
4781 SDValue Cond = Op.getOperand(0);
4783 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
4784 SDValue One = DAG.getConstant(1, DL, MVT::i32);
4786 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
4787 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
4789 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
4790 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
4792 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
4794 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
4795 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
4797 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
4799 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
4800 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
4803 // Catch division cases where we can use shortcuts with rcp and rsq
4805 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
4806 SelectionDAG &DAG) const {
4808 SDValue LHS = Op.getOperand(0);
4809 SDValue RHS = Op.getOperand(1);
4810 EVT VT = Op.getValueType();
4811 const SDNodeFlags Flags = Op->getFlags();
4812 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath ||
4813 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal();
4815 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
4818 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
4819 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
4820 if (CLHS->isExactlyValue(1.0)) {
4821 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
4822 // the CI documentation has a worst case error of 1 ulp.
4823 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
4824 // use it as long as we aren't trying to use denormals.
4826 // v_rcp_f16 and v_rsq_f16 DO support denormals.
4828 // 1.0 / sqrt(x) -> rsq(x)
4830 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
4831 // error seems really high at 2^29 ULP.
4832 if (RHS.getOpcode() == ISD::FSQRT)
4833 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
4835 // 1.0 / x -> rcp(x)
4836 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
4839 // Same as for 1.0, but expand the sign out of the constant.
4840 if (CLHS->isExactlyValue(-1.0)) {
4841 // -1.0 / x -> rcp (fneg x)
4842 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4843 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
4849 // Turn into multiply by the reciprocal.
4850 // x / y -> x * (1.0 / y)
4851 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
4852 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
4858 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
4859 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
4860 if (GlueChain->getNumValues() <= 1) {
4861 return DAG.getNode(Opcode, SL, VT, A, B);
4864 assert(GlueChain->getNumValues() == 3);
4866 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
4868 default: llvm_unreachable("no chain equivalent for opcode");
4870 Opcode = AMDGPUISD::FMUL_W_CHAIN;
4874 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
4875 GlueChain.getValue(2));
4878 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
4879 EVT VT, SDValue A, SDValue B, SDValue C,
4880 SDValue GlueChain) {
4881 if (GlueChain->getNumValues() <= 1) {
4882 return DAG.getNode(Opcode, SL, VT, A, B, C);
4885 assert(GlueChain->getNumValues() == 3);
4887 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
4889 default: llvm_unreachable("no chain equivalent for opcode");
4891 Opcode = AMDGPUISD::FMA_W_CHAIN;
4895 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
4896 GlueChain.getValue(2));
4899 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
4900 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
4904 SDValue Src0 = Op.getOperand(0);
4905 SDValue Src1 = Op.getOperand(1);
4907 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4908 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4910 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
4911 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
4913 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
4914 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
4916 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
4919 // Faster 2.5 ULP division that does not support denormals.
4920 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
4922 SDValue LHS = Op.getOperand(1);
4923 SDValue RHS = Op.getOperand(2);
4925 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
4927 const APFloat K0Val(BitsToFloat(0x6f800000));
4928 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
4930 const APFloat K1Val(BitsToFloat(0x2f800000));
4931 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
4933 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
4936 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
4938 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
4940 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
4942 // TODO: Should this propagate fast-math-flags?
4943 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
4945 // rcp does not support denormals.
4946 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
4948 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
4950 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
4953 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
4954 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
4958 SDValue LHS = Op.getOperand(0);
4959 SDValue RHS = Op.getOperand(1);
4961 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
4963 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
4965 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
4967 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
4970 // Denominator is scaled to not be denormal, so using rcp is ok.
4971 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
4973 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
4976 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
4977 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
4978 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
4980 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
4982 if (!Subtarget->hasFP32Denormals()) {
4983 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
4984 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
4986 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
4988 EnableDenormValue, BitField);
4991 EnableDenorm.getValue(0),
4992 EnableDenorm.getValue(1)
4995 NegDivScale0 = DAG.getMergeValues(Ops, SL);
4998 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
4999 ApproxRcp, One, NegDivScale0);
5001 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5004 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5007 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5008 NumeratorScaled, Mul);
5010 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5012 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5013 NumeratorScaled, Fma3);
5015 if (!Subtarget->hasFP32Denormals()) {
5016 const SDValue DisableDenormValue =
5017 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5018 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5024 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5025 DisableDenorm, DAG.getRoot());
5026 DAG.setRoot(OutputChain);
5029 SDValue Scale = NumeratorScaled.getValue(1);
5030 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5031 Fma4, Fma1, Fma3, Scale);
5033 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5036 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5037 if (DAG.getTarget().Options.UnsafeFPMath)
5038 return lowerFastUnsafeFDIV(Op, DAG);
5041 SDValue X = Op.getOperand(0);
5042 SDValue Y = Op.getOperand(1);
5044 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5046 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5048 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5050 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5052 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5054 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5056 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5058 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5060 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5062 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5063 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5065 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5066 NegDivScale0, Mul, DivScale1);
5070 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5071 // Workaround a hardware bug on SI where the condition output from div_scale
5074 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5076 // Figure out if the scale to use for div_fmas.
5077 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5078 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5079 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5080 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5082 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5083 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5086 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5088 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5090 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5091 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5092 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5094 Scale = DivScale1.getValue(1);
5097 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5098 Fma4, Fma3, Mul, Scale);
5100 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5103 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5104 EVT VT = Op.getValueType();
5107 return LowerFDIV32(Op, DAG);
5110 return LowerFDIV64(Op, DAG);
5113 return LowerFDIV16(Op, DAG);
5115 llvm_unreachable("Unexpected type for fdiv");
5118 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5120 StoreSDNode *Store = cast<StoreSDNode>(Op);
5121 EVT VT = Store->getMemoryVT();
5123 if (VT == MVT::i1) {
5124 return DAG.getTruncStore(Store->getChain(), DL,
5125 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5126 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5129 assert(VT.isVector() &&
5130 Store->getValue().getValueType().getScalarType() == MVT::i32);
5132 unsigned AS = Store->getAddressSpace();
5133 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5134 AS, Store->getAlignment())) {
5135 return expandUnalignedStore(Store, DAG);
5138 MachineFunction &MF = DAG.getMachineFunction();
5139 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5140 // If there is a possibilty that flat instruction access scratch memory
5141 // then we need to use the same legalization rules we use for private.
5142 if (AS == AMDGPUASI.FLAT_ADDRESS)
5143 AS = MFI->hasFlatScratchInit() ?
5144 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5146 unsigned NumElements = VT.getVectorNumElements();
5147 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5148 AS == AMDGPUASI.FLAT_ADDRESS) {
5149 if (NumElements > 4)
5150 return SplitVectorStore(Op, DAG);
5152 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5153 switch (Subtarget->getMaxPrivateElementSize()) {
5155 return scalarizeVectorStore(Store, DAG);
5157 if (NumElements > 2)
5158 return SplitVectorStore(Op, DAG);
5161 if (NumElements > 4)
5162 return SplitVectorStore(Op, DAG);
5165 llvm_unreachable("unsupported private_element_size");
5167 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5168 if (NumElements > 2)
5169 return SplitVectorStore(Op, DAG);
5171 if (NumElements == 2)
5174 // If properly aligned, if we split we might be able to use ds_write_b64.
5175 return SplitVectorStore(Op, DAG);
5177 llvm_unreachable("unhandled address space");
5181 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5183 EVT VT = Op.getValueType();
5184 SDValue Arg = Op.getOperand(0);
5185 // TODO: Should this propagate fast-math-flags?
5186 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5187 DAG.getNode(ISD::FMUL, DL, VT, Arg,
5188 DAG.getConstantFP(0.5/M_PI, DL,
5191 switch (Op.getOpcode()) {
5193 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5195 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5197 llvm_unreachable("Wrong trig opcode");
5201 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5202 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5203 assert(AtomicNode->isCompareAndSwap());
5204 unsigned AS = AtomicNode->getAddressSpace();
5206 // No custom lowering required for local address space
5207 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5210 // Non-local address space requires custom lowering for atomic compare
5211 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5213 SDValue ChainIn = Op.getOperand(0);
5214 SDValue Addr = Op.getOperand(1);
5215 SDValue Old = Op.getOperand(2);
5216 SDValue New = Op.getOperand(3);
5217 EVT VT = Op.getValueType();
5218 MVT SimpleVT = VT.getSimpleVT();
5219 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5221 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5222 SDValue Ops[] = { ChainIn, Addr, NewOld };
5224 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5225 Ops, VT, AtomicNode->getMemOperand());
5228 //===----------------------------------------------------------------------===//
5229 // Custom DAG optimizations
5230 //===----------------------------------------------------------------------===//
5232 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
5233 DAGCombinerInfo &DCI) const {
5234 EVT VT = N->getValueType(0);
5235 EVT ScalarVT = VT.getScalarType();
5236 if (ScalarVT != MVT::f32)
5239 SelectionDAG &DAG = DCI.DAG;
5242 SDValue Src = N->getOperand(0);
5243 EVT SrcVT = Src.getValueType();
5245 // TODO: We could try to match extracting the higher bytes, which would be
5246 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
5247 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
5248 // about in practice.
5249 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
5250 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
5251 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
5252 DCI.AddToWorklist(Cvt.getNode());
5260 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
5262 // This is a variant of
5263 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
5265 // The normal DAG combiner will do this, but only if the add has one use since
5266 // that would increase the number of instructions.
5268 // This prevents us from seeing a constant offset that can be folded into a
5269 // memory instruction's addressing mode. If we know the resulting add offset of
5270 // a pointer can be folded into an addressing offset, we can replace the pointer
5271 // operand with the add of new constant offset. This eliminates one of the uses,
5272 // and may allow the remaining use to also be simplified.
5274 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
5277 DAGCombinerInfo &DCI) const {
5278 SDValue N0 = N->getOperand(0);
5279 SDValue N1 = N->getOperand(1);
5281 // We only do this to handle cases where it's profitable when there are
5282 // multiple uses of the add, so defer to the standard combine.
5283 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
5287 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
5291 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5295 // If the resulting offset is too large, we can't fold it into the addressing
5297 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
5298 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
5301 AM.HasBaseReg = true;
5302 AM.BaseOffs = Offset.getSExtValue();
5303 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
5306 SelectionDAG &DAG = DCI.DAG;
5308 EVT VT = N->getValueType(0);
5310 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
5311 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
5314 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
5315 (N0.getOpcode() == ISD::OR ||
5316 N0->getFlags().hasNoUnsignedWrap()));
5318 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
5321 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
5322 DAGCombinerInfo &DCI) const {
5323 SDValue Ptr = N->getBasePtr();
5324 SelectionDAG &DAG = DCI.DAG;
5327 // TODO: We could also do this for multiplies.
5328 if (Ptr.getOpcode() == ISD::SHL) {
5329 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
5330 N->getMemoryVT(), DCI);
5332 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
5334 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
5335 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
5342 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
5343 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
5344 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
5345 (Opc == ISD::XOR && Val == 0);
5348 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
5349 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
5350 // integer combine opportunities since most 64-bit operations are decomposed
5351 // this way. TODO: We won't want this for SALU especially if it is an inline
5353 SDValue SITargetLowering::splitBinaryBitConstantOp(
5354 DAGCombinerInfo &DCI,
5356 unsigned Opc, SDValue LHS,
5357 const ConstantSDNode *CRHS) const {
5358 uint64_t Val = CRHS->getZExtValue();
5359 uint32_t ValLo = Lo_32(Val);
5360 uint32_t ValHi = Hi_32(Val);
5361 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5363 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
5364 bitOpWithConstantIsReducible(Opc, ValHi)) ||
5365 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
5366 // If we need to materialize a 64-bit immediate, it will be split up later
5367 // anyway. Avoid creating the harder to understand 64-bit immediate
5369 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
5375 // Returns true if argument is a boolean value which is not serialized into
5376 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
5377 static bool isBoolSGPR(SDValue V) {
5378 if (V.getValueType() != MVT::i1)
5380 switch (V.getOpcode()) {
5386 case AMDGPUISD::FP_CLASS:
5392 SDValue SITargetLowering::performAndCombine(SDNode *N,
5393 DAGCombinerInfo &DCI) const {
5394 if (DCI.isBeforeLegalize())
5397 SelectionDAG &DAG = DCI.DAG;
5398 EVT VT = N->getValueType(0);
5399 SDValue LHS = N->getOperand(0);
5400 SDValue RHS = N->getOperand(1);
5403 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5404 if (VT == MVT::i64 && CRHS) {
5406 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
5410 if (CRHS && VT == MVT::i32) {
5411 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
5412 // nb = number of trailing zeroes in mask
5413 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
5414 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
5415 uint64_t Mask = CRHS->getZExtValue();
5416 unsigned Bits = countPopulation(Mask);
5417 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
5418 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
5419 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
5420 unsigned Shift = CShift->getZExtValue();
5421 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
5422 unsigned Offset = NB + Shift;
5423 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
5425 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
5427 DAG.getConstant(Offset, SL, MVT::i32),
5428 DAG.getConstant(Bits, SL, MVT::i32));
5429 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
5430 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
5431 DAG.getValueType(NarrowVT));
5432 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
5433 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
5440 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
5441 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
5442 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
5443 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
5444 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
5446 SDValue X = LHS.getOperand(0);
5447 SDValue Y = RHS.getOperand(0);
5448 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
5451 if (LCC == ISD::SETO) {
5452 if (X != LHS.getOperand(1))
5455 if (RCC == ISD::SETUNE) {
5456 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
5457 if (!C1 || !C1->isInfinity() || C1->isNegative())
5460 const uint32_t Mask = SIInstrFlags::N_NORMAL |
5461 SIInstrFlags::N_SUBNORMAL |
5462 SIInstrFlags::N_ZERO |
5463 SIInstrFlags::P_ZERO |
5464 SIInstrFlags::P_SUBNORMAL |
5465 SIInstrFlags::P_NORMAL;
5467 static_assert(((~(SIInstrFlags::S_NAN |
5468 SIInstrFlags::Q_NAN |
5469 SIInstrFlags::N_INFINITY |
5470 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
5474 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5475 X, DAG.getConstant(Mask, DL, MVT::i32));
5480 if (VT == MVT::i32 &&
5481 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
5482 // and x, (sext cc from i1) => select cc, x, 0
5483 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
5484 std::swap(LHS, RHS);
5485 if (isBoolSGPR(RHS.getOperand(0)))
5486 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
5487 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
5493 SDValue SITargetLowering::performOrCombine(SDNode *N,
5494 DAGCombinerInfo &DCI) const {
5495 SelectionDAG &DAG = DCI.DAG;
5496 SDValue LHS = N->getOperand(0);
5497 SDValue RHS = N->getOperand(1);
5499 EVT VT = N->getValueType(0);
5500 if (VT == MVT::i1) {
5501 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
5502 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
5503 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
5504 SDValue Src = LHS.getOperand(0);
5505 if (Src != RHS.getOperand(0))
5508 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
5509 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
5513 // Only 10 bits are used.
5514 static const uint32_t MaxMask = 0x3ff;
5516 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
5518 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
5519 Src, DAG.getConstant(NewMask, DL, MVT::i32));
5528 // TODO: This could be a generic combine with a predicate for extracting the
5529 // high half of an integer being free.
5531 // (or i64:x, (zero_extend i32:y)) ->
5532 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
5533 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
5534 RHS.getOpcode() != ISD::ZERO_EXTEND)
5535 std::swap(LHS, RHS);
5537 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
5538 SDValue ExtSrc = RHS.getOperand(0);
5539 EVT SrcVT = ExtSrc.getValueType();
5540 if (SrcVT == MVT::i32) {
5542 SDValue LowLHS, HiBits;
5543 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
5544 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
5546 DCI.AddToWorklist(LowOr.getNode());
5547 DCI.AddToWorklist(HiBits.getNode());
5549 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
5551 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5555 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
5558 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
5565 SDValue SITargetLowering::performXorCombine(SDNode *N,
5566 DAGCombinerInfo &DCI) const {
5567 EVT VT = N->getValueType(0);
5571 SDValue LHS = N->getOperand(0);
5572 SDValue RHS = N->getOperand(1);
5574 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
5577 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
5584 // Instructions that will be lowered with a final instruction that zeros the
5585 // high result bits.
5586 // XXX - probably only need to list legal operations.
5587 static bool fp16SrcZerosHighBits(unsigned Opc) {
5596 case ISD::FCANONICALIZE:
5598 case ISD::UINT_TO_FP:
5599 case ISD::SINT_TO_FP:
5601 // Fabs is lowered to a bit operation, but it's an and which will clear the
5602 // high bits anyway.
5616 case ISD::FNEARBYINT:
5621 case AMDGPUISD::FRACT:
5622 case AMDGPUISD::CLAMP:
5623 case AMDGPUISD::COS_HW:
5624 case AMDGPUISD::SIN_HW:
5625 case AMDGPUISD::FMIN3:
5626 case AMDGPUISD::FMAX3:
5627 case AMDGPUISD::FMED3:
5628 case AMDGPUISD::FMAD_FTZ:
5629 case AMDGPUISD::RCP:
5630 case AMDGPUISD::RSQ:
5631 case AMDGPUISD::LDEXP:
5634 // fcopysign, select and others may be lowered to 32-bit bit operations
5635 // which don't zero the high bits.
5640 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
5641 DAGCombinerInfo &DCI) const {
5642 if (!Subtarget->has16BitInsts() ||
5643 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
5646 EVT VT = N->getValueType(0);
5650 SDValue Src = N->getOperand(0);
5651 if (Src.getValueType() != MVT::i16)
5654 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
5655 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
5656 if (Src.getOpcode() == ISD::BITCAST) {
5657 SDValue BCSrc = Src.getOperand(0);
5658 if (BCSrc.getValueType() == MVT::f16 &&
5659 fp16SrcZerosHighBits(BCSrc.getOpcode()))
5660 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
5666 SDValue SITargetLowering::performClassCombine(SDNode *N,
5667 DAGCombinerInfo &DCI) const {
5668 SelectionDAG &DAG = DCI.DAG;
5669 SDValue Mask = N->getOperand(1);
5671 // fp_class x, 0 -> false
5672 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
5673 if (CMask->isNullValue())
5674 return DAG.getConstant(0, SDLoc(N), MVT::i1);
5677 if (N->getOperand(0).isUndef())
5678 return DAG.getUNDEF(MVT::i1);
5683 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
5684 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
5687 return DAG.isKnownNeverNaN(Op);
5690 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
5691 const SISubtarget *ST, unsigned MaxDepth=5) {
5692 // If source is a result of another standard FP operation it is already in
5695 switch (Op.getOpcode()) {
5699 // These will flush denorms if required.
5709 case ISD::FCANONICALIZE:
5713 return Op.getValueType().getScalarType() != MVT::f16 ||
5714 ST->hasFP16Denormals();
5716 case ISD::FP_EXTEND:
5717 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
5718 ST->hasFP16Denormals();
5720 case ISD::FP16_TO_FP:
5721 case ISD::FP_TO_FP16:
5722 return ST->hasFP16Denormals();
5724 // It can/will be lowered or combined as a bit operation.
5725 // Need to check their input recursively to handle.
5728 return (MaxDepth > 0) &&
5729 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
5734 return Op.getValueType().getScalarType() != MVT::f16;
5736 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
5737 // For such targets need to check their input recursively.
5743 if (ST->supportsMinMaxDenormModes() &&
5744 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
5745 DAG.isKnownNeverNaN(Op.getOperand(1)))
5748 return (MaxDepth > 0) &&
5749 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
5750 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
5752 case ISD::ConstantFP: {
5753 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
5754 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
5760 // Constant fold canonicalize.
5761 SDValue SITargetLowering::performFCanonicalizeCombine(
5763 DAGCombinerInfo &DCI) const {
5764 SelectionDAG &DAG = DCI.DAG;
5765 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
5768 SDValue N0 = N->getOperand(0);
5769 EVT VT = N0.getValueType().getScalarType();
5770 auto ST = getSubtarget();
5772 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
5773 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
5774 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
5775 DAG.isKnownNeverNaN(N0))
5778 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
5780 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
5781 isCanonicalized(DAG, N0, ST))
5787 const APFloat &C = CFP->getValueAPF();
5789 // Flush denormals to 0 if not enabled.
5790 if (C.isDenormal()) {
5791 EVT VT = N->getValueType(0);
5792 EVT SVT = VT.getScalarType();
5793 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
5794 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5796 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
5797 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5799 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
5800 return DAG.getConstantFP(0.0, SDLoc(N), VT);
5804 EVT VT = N->getValueType(0);
5805 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
5806 if (C.isSignaling()) {
5807 // Quiet a signaling NaN.
5808 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
5811 // Make sure it is the canonical NaN bitpattern.
5813 // TODO: Can we use -1 as the canonical NaN value since it's an inline
5815 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
5816 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
5819 return N->getOperand(0);
5822 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
5825 return AMDGPUISD::FMAX3;
5827 return AMDGPUISD::SMAX3;
5829 return AMDGPUISD::UMAX3;
5831 return AMDGPUISD::FMIN3;
5833 return AMDGPUISD::SMIN3;
5835 return AMDGPUISD::UMIN3;
5837 llvm_unreachable("Not a min/max opcode");
5841 SDValue SITargetLowering::performIntMed3ImmCombine(
5842 SelectionDAG &DAG, const SDLoc &SL,
5843 SDValue Op0, SDValue Op1, bool Signed) const {
5844 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
5848 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
5853 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
5856 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
5860 EVT VT = K0->getValueType(0);
5861 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
5862 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
5863 return DAG.getNode(Med3Opc, SL, VT,
5864 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
5867 // If there isn't a 16-bit med3 operation, convert to 32-bit.
5869 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5871 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
5872 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
5873 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
5875 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
5876 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
5879 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
5880 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
5883 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
5884 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
5891 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
5894 SDValue Op1) const {
5895 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
5899 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
5903 // Ordered >= (although NaN inputs should have folded away by now).
5904 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
5905 if (Cmp == APFloat::cmpGreaterThan)
5908 // TODO: Check IEEE bit enabled?
5909 EVT VT = Op0.getValueType();
5910 if (Subtarget->enableDX10Clamp()) {
5911 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
5912 // hardware fmed3 behavior converting to a min.
5913 // FIXME: Should this be allowing -0.0?
5914 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
5915 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
5918 // med3 for f16 is only available on gfx9+, and not available for v2f16.
5919 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
5920 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
5921 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
5922 // then give the other result, which is different from med3 with a NaN
5924 SDValue Var = Op0.getOperand(0);
5925 if (!isKnownNeverSNan(DAG, Var))
5928 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
5929 Var, SDValue(K0, 0), SDValue(K1, 0));
5935 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
5936 DAGCombinerInfo &DCI) const {
5937 SelectionDAG &DAG = DCI.DAG;
5939 EVT VT = N->getValueType(0);
5940 unsigned Opc = N->getOpcode();
5941 SDValue Op0 = N->getOperand(0);
5942 SDValue Op1 = N->getOperand(1);
5944 // Only do this if the inner op has one use since this will just increases
5945 // register pressure for no benefit.
5948 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
5950 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
5951 // max(max(a, b), c) -> max3(a, b, c)
5952 // min(min(a, b), c) -> min3(a, b, c)
5953 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
5955 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
5964 // max(a, max(b, c)) -> max3(a, b, c)
5965 // min(a, min(b, c)) -> min3(a, b, c)
5966 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
5968 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
5977 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
5978 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
5979 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
5983 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
5984 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
5988 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
5989 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
5990 (Opc == AMDGPUISD::FMIN_LEGACY &&
5991 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
5992 (VT == MVT::f32 || VT == MVT::f64 ||
5993 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
5994 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
5996 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
6003 static bool isClampZeroToOne(SDValue A, SDValue B) {
6004 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
6005 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
6006 // FIXME: Should this be allowing -0.0?
6007 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
6008 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
6015 // FIXME: Should only worry about snans for version with chain.
6016 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6017 DAGCombinerInfo &DCI) const {
6018 EVT VT = N->getValueType(0);
6019 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6020 // NaNs. With a NaN input, the order of the operands may change the result.
6022 SelectionDAG &DAG = DCI.DAG;
6025 SDValue Src0 = N->getOperand(0);
6026 SDValue Src1 = N->getOperand(1);
6027 SDValue Src2 = N->getOperand(2);
6029 if (isClampZeroToOne(Src0, Src1)) {
6030 // const_a, const_b, x -> clamp is safe in all cases including signaling
6032 // FIXME: Should this be allowing -0.0?
6033 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
6036 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
6037 // handling no dx10-clamp?
6038 if (Subtarget->enableDX10Clamp()) {
6039 // If NaNs is clamped to 0, we are free to reorder the inputs.
6041 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6042 std::swap(Src0, Src1);
6044 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
6045 std::swap(Src1, Src2);
6047 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6048 std::swap(Src0, Src1);
6050 if (isClampZeroToOne(Src1, Src2))
6051 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
6057 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
6058 DAGCombinerInfo &DCI) const {
6059 SDValue Src0 = N->getOperand(0);
6060 SDValue Src1 = N->getOperand(1);
6061 if (Src0.isUndef() && Src1.isUndef())
6062 return DCI.DAG.getUNDEF(N->getValueType(0));
6066 SDValue SITargetLowering::performExtractVectorEltCombine(
6067 SDNode *N, DAGCombinerInfo &DCI) const {
6068 SDValue Vec = N->getOperand(0);
6070 SelectionDAG &DAG = DCI.DAG;
6071 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
6073 EVT EltVT = N->getValueType(0);
6074 SDValue Idx = N->getOperand(1);
6075 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6076 Vec.getOperand(0), Idx);
6077 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
6083 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
6084 SDValue &Lo, SDValue &Hi) {
6085 if (Hi.getOpcode() == ISD::BITCAST &&
6086 Hi.getOperand(0).getValueType() == MVT::f16 &&
6087 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
6088 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
6089 Hi = Hi.getOperand(0);
6096 SDValue SITargetLowering::performBuildVectorCombine(
6097 SDNode *N, DAGCombinerInfo &DCI) const {
6100 if (!isTypeLegal(MVT::v2i16))
6102 SelectionDAG &DAG = DCI.DAG;
6103 EVT VT = N->getValueType(0);
6105 if (VT == MVT::v2i16) {
6106 SDValue Lo = N->getOperand(0);
6107 SDValue Hi = N->getOperand(1);
6109 // v2i16 build_vector (const|undef), (bitcast f16:$x)
6110 // -> bitcast (v2f16 build_vector const|undef, $x
6111 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
6112 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
6113 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6116 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
6117 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
6118 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6125 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
6127 const SDNode *N1) const {
6128 EVT VT = N0->getValueType(0);
6130 // Only do this if we are not trying to support denormals. v_mad_f32 does not
6131 // support denormals ever.
6132 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
6133 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
6136 const TargetOptions &Options = DAG.getTarget().Options;
6137 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
6138 (N0->getFlags().hasUnsafeAlgebra() &&
6139 N1->getFlags().hasUnsafeAlgebra())) &&
6140 isFMAFasterThanFMulAndFAdd(VT)) {
6147 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
6149 SDValue N0, SDValue N1, SDValue N2,
6151 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
6152 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
6153 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
6154 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
6157 SDValue SITargetLowering::performAddCombine(SDNode *N,
6158 DAGCombinerInfo &DCI) const {
6159 SelectionDAG &DAG = DCI.DAG;
6160 EVT VT = N->getValueType(0);
6162 SDValue LHS = N->getOperand(0);
6163 SDValue RHS = N->getOperand(1);
6165 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
6166 && Subtarget->hasMad64_32() &&
6167 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
6168 VT.getScalarSizeInBits() <= 64) {
6169 if (LHS.getOpcode() != ISD::MUL)
6170 std::swap(LHS, RHS);
6172 SDValue MulLHS = LHS.getOperand(0);
6173 SDValue MulRHS = LHS.getOperand(1);
6174 SDValue AddRHS = RHS;
6176 // TODO: Maybe restrict if SGPR inputs.
6177 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
6178 numBitsUnsigned(MulRHS, DAG) <= 32) {
6179 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
6180 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
6181 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
6182 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
6185 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
6186 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
6187 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
6188 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
6189 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
6198 // add x, zext (setcc) => addcarry x, 0, setcc
6199 // add x, sext (setcc) => subcarry x, 0, setcc
6200 unsigned Opc = LHS.getOpcode();
6201 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
6202 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
6203 std::swap(RHS, LHS);
6205 Opc = RHS.getOpcode();
6208 case ISD::ZERO_EXTEND:
6209 case ISD::SIGN_EXTEND:
6210 case ISD::ANY_EXTEND: {
6211 auto Cond = RHS.getOperand(0);
6212 if (!isBoolSGPR(Cond))
6214 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
6215 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
6216 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
6217 return DAG.getNode(Opc, SL, VTList, Args);
6219 case ISD::ADDCARRY: {
6220 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
6221 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6222 if (!C || C->getZExtValue() != 0) break;
6223 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
6224 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
6230 SDValue SITargetLowering::performSubCombine(SDNode *N,
6231 DAGCombinerInfo &DCI) const {
6232 SelectionDAG &DAG = DCI.DAG;
6233 EVT VT = N->getValueType(0);
6239 SDValue LHS = N->getOperand(0);
6240 SDValue RHS = N->getOperand(1);
6242 unsigned Opc = LHS.getOpcode();
6243 if (Opc != ISD::SUBCARRY)
6244 std::swap(RHS, LHS);
6246 if (LHS.getOpcode() == ISD::SUBCARRY) {
6247 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
6248 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6249 if (!C || C->getZExtValue() != 0)
6251 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
6252 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
6257 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
6258 DAGCombinerInfo &DCI) const {
6260 if (N->getValueType(0) != MVT::i32)
6263 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6264 if (!C || C->getZExtValue() != 0)
6267 SelectionDAG &DAG = DCI.DAG;
6268 SDValue LHS = N->getOperand(0);
6270 // addcarry (add x, y), 0, cc => addcarry x, y, cc
6271 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
6272 unsigned LHSOpc = LHS.getOpcode();
6273 unsigned Opc = N->getOpcode();
6274 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
6275 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
6276 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
6277 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
6282 SDValue SITargetLowering::performFAddCombine(SDNode *N,
6283 DAGCombinerInfo &DCI) const {
6284 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6287 SelectionDAG &DAG = DCI.DAG;
6288 EVT VT = N->getValueType(0);
6291 SDValue LHS = N->getOperand(0);
6292 SDValue RHS = N->getOperand(1);
6294 // These should really be instruction patterns, but writing patterns with
6295 // source modiifiers is a pain.
6297 // fadd (fadd (a, a), b) -> mad 2.0, a, b
6298 if (LHS.getOpcode() == ISD::FADD) {
6299 SDValue A = LHS.getOperand(0);
6300 if (A == LHS.getOperand(1)) {
6301 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6303 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6304 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
6309 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
6310 if (RHS.getOpcode() == ISD::FADD) {
6311 SDValue A = RHS.getOperand(0);
6312 if (A == RHS.getOperand(1)) {
6313 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6315 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6316 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
6324 SDValue SITargetLowering::performFSubCombine(SDNode *N,
6325 DAGCombinerInfo &DCI) const {
6326 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6329 SelectionDAG &DAG = DCI.DAG;
6331 EVT VT = N->getValueType(0);
6332 assert(!VT.isVector());
6334 // Try to get the fneg to fold into the source modifier. This undoes generic
6335 // DAG combines and folds them into the mad.
6337 // Only do this if we are not trying to support denormals. v_mad_f32 does
6338 // not support denormals ever.
6339 SDValue LHS = N->getOperand(0);
6340 SDValue RHS = N->getOperand(1);
6341 if (LHS.getOpcode() == ISD::FADD) {
6342 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
6343 SDValue A = LHS.getOperand(0);
6344 if (A == LHS.getOperand(1)) {
6345 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6347 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6348 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
6350 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
6355 if (RHS.getOpcode() == ISD::FADD) {
6356 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
6358 SDValue A = RHS.getOperand(0);
6359 if (A == RHS.getOperand(1)) {
6360 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6362 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
6363 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
6371 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
6372 DAGCombinerInfo &DCI) const {
6373 SelectionDAG &DAG = DCI.DAG;
6376 SDValue LHS = N->getOperand(0);
6377 SDValue RHS = N->getOperand(1);
6378 EVT VT = LHS.getValueType();
6379 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
6381 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
6383 CRHS = dyn_cast<ConstantSDNode>(LHS);
6385 std::swap(LHS, RHS);
6386 CC = getSetCCSwappedOperands(CC);
6390 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
6391 isBoolSGPR(LHS.getOperand(0))) {
6392 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
6393 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
6394 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
6395 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
6396 if ((CRHS->isAllOnesValue() &&
6397 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
6398 (CRHS->isNullValue() &&
6399 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
6400 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
6401 DAG.getConstant(-1, SL, MVT::i1));
6402 if ((CRHS->isAllOnesValue() &&
6403 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
6404 (CRHS->isNullValue() &&
6405 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
6406 return LHS.getOperand(0);
6409 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
6413 // Match isinf pattern
6414 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
6415 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
6416 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
6420 const APFloat &APF = CRHS->getValueAPF();
6421 if (APF.isInfinity() && !APF.isNegative()) {
6422 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
6423 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
6424 DAG.getConstant(Mask, SL, MVT::i32));
6431 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
6432 DAGCombinerInfo &DCI) const {
6433 SelectionDAG &DAG = DCI.DAG;
6435 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
6437 SDValue Src = N->getOperand(0);
6438 SDValue Srl = N->getOperand(0);
6439 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
6440 Srl = Srl.getOperand(0);
6442 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
6443 if (Srl.getOpcode() == ISD::SRL) {
6444 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
6445 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
6446 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
6448 if (const ConstantSDNode *C =
6449 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
6450 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
6453 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
6454 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
6455 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
6461 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
6464 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
6465 !DCI.isBeforeLegalizeOps());
6466 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6467 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
6468 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
6469 DCI.CommitTargetLoweringOpt(TLO);
6475 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
6476 DAGCombinerInfo &DCI) const {
6477 switch (N->getOpcode()) {
6479 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6481 return performAddCombine(N, DCI);
6483 return performSubCombine(N, DCI);
6486 return performAddCarrySubCarryCombine(N, DCI);
6488 return performFAddCombine(N, DCI);
6490 return performFSubCombine(N, DCI);
6492 return performSetCCCombine(N, DCI);
6499 case AMDGPUISD::FMIN_LEGACY:
6500 case AMDGPUISD::FMAX_LEGACY: {
6501 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
6502 getTargetMachine().getOptLevel() > CodeGenOpt::None)
6503 return performMinMaxCombine(N, DCI);
6508 case ISD::ATOMIC_LOAD:
6509 case ISD::ATOMIC_STORE:
6510 case ISD::ATOMIC_CMP_SWAP:
6511 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
6512 case ISD::ATOMIC_SWAP:
6513 case ISD::ATOMIC_LOAD_ADD:
6514 case ISD::ATOMIC_LOAD_SUB:
6515 case ISD::ATOMIC_LOAD_AND:
6516 case ISD::ATOMIC_LOAD_OR:
6517 case ISD::ATOMIC_LOAD_XOR:
6518 case ISD::ATOMIC_LOAD_NAND:
6519 case ISD::ATOMIC_LOAD_MIN:
6520 case ISD::ATOMIC_LOAD_MAX:
6521 case ISD::ATOMIC_LOAD_UMIN:
6522 case ISD::ATOMIC_LOAD_UMAX:
6523 case AMDGPUISD::ATOMIC_INC:
6524 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
6525 if (DCI.isBeforeLegalize())
6527 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
6529 return performAndCombine(N, DCI);
6531 return performOrCombine(N, DCI);
6533 return performXorCombine(N, DCI);
6534 case ISD::ZERO_EXTEND:
6535 return performZeroExtendCombine(N, DCI);
6536 case AMDGPUISD::FP_CLASS:
6537 return performClassCombine(N, DCI);
6538 case ISD::FCANONICALIZE:
6539 return performFCanonicalizeCombine(N, DCI);
6540 case AMDGPUISD::FRACT:
6541 case AMDGPUISD::RCP:
6542 case AMDGPUISD::RSQ:
6543 case AMDGPUISD::RCP_LEGACY:
6544 case AMDGPUISD::RSQ_LEGACY:
6545 case AMDGPUISD::RSQ_CLAMP:
6546 case AMDGPUISD::LDEXP: {
6547 SDValue Src = N->getOperand(0);
6552 case ISD::SINT_TO_FP:
6553 case ISD::UINT_TO_FP:
6554 return performUCharToFloatCombine(N, DCI);
6555 case AMDGPUISD::CVT_F32_UBYTE0:
6556 case AMDGPUISD::CVT_F32_UBYTE1:
6557 case AMDGPUISD::CVT_F32_UBYTE2:
6558 case AMDGPUISD::CVT_F32_UBYTE3:
6559 return performCvtF32UByteNCombine(N, DCI);
6560 case AMDGPUISD::FMED3:
6561 return performFMed3Combine(N, DCI);
6562 case AMDGPUISD::CVT_PKRTZ_F16_F32:
6563 return performCvtPkRTZCombine(N, DCI);
6564 case ISD::SCALAR_TO_VECTOR: {
6565 SelectionDAG &DAG = DCI.DAG;
6566 EVT VT = N->getValueType(0);
6568 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
6569 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
6571 SDValue Src = N->getOperand(0);
6572 EVT EltVT = Src.getValueType();
6573 if (EltVT == MVT::f16)
6574 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
6576 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
6577 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
6582 case ISD::EXTRACT_VECTOR_ELT:
6583 return performExtractVectorEltCombine(N, DCI);
6584 case ISD::BUILD_VECTOR:
6585 return performBuildVectorCombine(N, DCI);
6587 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
6590 /// \brief Helper function for adjustWritemask
6591 static unsigned SubIdx2Lane(unsigned Idx) {
6594 case AMDGPU::sub0: return 0;
6595 case AMDGPU::sub1: return 1;
6596 case AMDGPU::sub2: return 2;
6597 case AMDGPU::sub3: return 3;
6601 /// \brief Adjust the writemask of MIMG instructions
6602 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
6603 SelectionDAG &DAG) const {
6604 SDNode *Users[4] = { nullptr };
6606 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
6607 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
6608 unsigned NewDmask = 0;
6609 bool HasChain = Node->getNumValues() > 1;
6611 if (OldDmask == 0) {
6612 // These are folded out, but on the chance it happens don't assert.
6616 // Try to figure out the used register components
6617 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
6620 // Don't look at users of the chain.
6621 if (I.getUse().getResNo() != 0)
6624 // Abort if we can't understand the usage
6625 if (!I->isMachineOpcode() ||
6626 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
6629 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
6630 // Note that subregs are packed, i.e. Lane==0 is the first bit set
6631 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
6633 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
6635 // Set which texture component corresponds to the lane.
6637 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
6638 Comp = countTrailingZeros(Dmask);
6639 Dmask &= ~(1 << Comp);
6642 // Abort if we have more than one user per component
6647 NewDmask |= 1 << Comp;
6650 // Abort if there's no change
6651 if (NewDmask == OldDmask)
6654 unsigned BitsSet = countPopulation(NewDmask);
6656 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6657 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII,
6658 Node->getMachineOpcode(), BitsSet);
6659 assert(NewOpcode != -1 &&
6660 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
6661 "failed to find equivalent MIMG op");
6663 // Adjust the writemask in the node
6664 SmallVector<SDValue, 12> Ops;
6665 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
6666 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
6667 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
6669 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
6671 MVT ResultVT = BitsSet == 1 ?
6672 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
6673 SDVTList NewVTList = HasChain ?
6674 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
6677 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
6682 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
6683 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
6687 assert(Node->hasNUsesOfValue(1, 0));
6688 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
6689 SDLoc(Node), Users[Lane]->getValueType(0),
6690 SDValue(NewNode, 0));
6691 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
6695 // Update the users of the node with the new indices
6696 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
6697 SDNode *User = Users[i];
6701 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
6702 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
6706 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
6707 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
6708 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
6712 DAG.RemoveDeadNode(Node);
6716 static bool isFrameIndexOp(SDValue Op) {
6717 if (Op.getOpcode() == ISD::AssertZext)
6718 Op = Op.getOperand(0);
6720 return isa<FrameIndexSDNode>(Op);
6723 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
6724 /// with frame index operands.
6725 /// LLVM assumes that inputs are to these instructions are registers.
6726 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
6727 SelectionDAG &DAG) const {
6728 if (Node->getOpcode() == ISD::CopyToReg) {
6729 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
6730 SDValue SrcVal = Node->getOperand(2);
6732 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
6733 // to try understanding copies to physical registers.
6734 if (SrcVal.getValueType() == MVT::i1 &&
6735 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
6737 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6738 SDValue VReg = DAG.getRegister(
6739 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
6741 SDNode *Glued = Node->getGluedNode();
6743 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
6744 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
6746 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
6747 VReg, ToVReg.getValue(1));
6748 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
6749 DAG.RemoveDeadNode(Node);
6750 return ToResultReg.getNode();
6754 SmallVector<SDValue, 8> Ops;
6755 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
6756 if (!isFrameIndexOp(Node->getOperand(i))) {
6757 Ops.push_back(Node->getOperand(i));
6762 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
6763 Node->getOperand(i).getValueType(),
6764 Node->getOperand(i)), 0));
6767 return DAG.UpdateNodeOperands(Node, Ops);
6770 /// \brief Fold the instructions after selecting them.
6771 /// Returns null if users were already updated.
6772 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
6773 SelectionDAG &DAG) const {
6774 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6775 unsigned Opcode = Node->getMachineOpcode();
6777 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
6778 !TII->isGather4(Opcode)) {
6779 return adjustWritemask(Node, DAG);
6782 if (Opcode == AMDGPU::INSERT_SUBREG ||
6783 Opcode == AMDGPU::REG_SEQUENCE) {
6784 legalizeTargetIndependentNode(Node, DAG);
6789 case AMDGPU::V_DIV_SCALE_F32:
6790 case AMDGPU::V_DIV_SCALE_F64: {
6791 // Satisfy the operand register constraint when one of the inputs is
6792 // undefined. Ordinarily each undef value will have its own implicit_def of
6793 // a vreg, so force these to use a single register.
6794 SDValue Src0 = Node->getOperand(0);
6795 SDValue Src1 = Node->getOperand(1);
6796 SDValue Src2 = Node->getOperand(2);
6798 if ((Src0.isMachineOpcode() &&
6799 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
6800 (Src0 == Src1 || Src0 == Src2))
6803 MVT VT = Src0.getValueType().getSimpleVT();
6804 const TargetRegisterClass *RC = getRegClassFor(VT);
6806 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
6807 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
6809 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
6810 UndefReg, Src0, SDValue());
6812 // src0 must be the same register as src1 or src2, even if the value is
6813 // undefined, so make sure we don't violate this constraint.
6814 if (Src0.isMachineOpcode() &&
6815 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
6816 if (Src1.isMachineOpcode() &&
6817 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
6819 else if (Src2.isMachineOpcode() &&
6820 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
6823 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
6830 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
6831 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
6832 Ops.push_back(Node->getOperand(I));
6834 Ops.push_back(ImpDef.getValue(1));
6835 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
6844 /// \brief Assign the register class depending on the number of
6845 /// bits set in the writemask
6846 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
6847 SDNode *Node) const {
6848 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6850 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6852 if (TII->isVOP3(MI.getOpcode())) {
6853 // Make sure constant bus requirements are respected.
6854 TII->legalizeOperandsVOP3(MRI, MI);
6858 // Replace unused atomics with the no return version.
6859 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
6860 if (NoRetAtomicOp != -1) {
6861 if (!Node->hasAnyUseOfValue(0)) {
6862 MI.setDesc(TII->get(NoRetAtomicOp));
6863 MI.RemoveOperand(0);
6867 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
6868 // instruction, because the return type of these instructions is a vec2 of
6869 // the memory type, so it can be tied to the input operand.
6870 // This means these instructions always have a use, so we need to add a
6871 // special case to check if the atomic has only one extract_subreg use,
6872 // which itself has no uses.
6873 if ((Node->hasNUsesOfValue(1, 0) &&
6874 Node->use_begin()->isMachineOpcode() &&
6875 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
6876 !Node->use_begin()->hasAnyUseOfValue(0))) {
6877 unsigned Def = MI.getOperand(0).getReg();
6879 // Change this into a noret atomic.
6880 MI.setDesc(TII->get(NoRetAtomicOp));
6881 MI.RemoveOperand(0);
6883 // If we only remove the def operand from the atomic instruction, the
6884 // extract_subreg will be left with a use of a vreg without a def.
6885 // So we need to insert an implicit_def to avoid machine verifier
6887 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
6888 TII->get(AMDGPU::IMPLICIT_DEF), Def);
6894 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
6896 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
6897 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
6900 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
6902 SDValue Ptr) const {
6903 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6905 // Build the half of the subregister with the constants before building the
6906 // full 128-bit register. If we are building multiple resource descriptors,
6907 // this will allow CSEing of the 2-component register.
6908 const SDValue Ops0[] = {
6909 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
6910 buildSMovImm32(DAG, DL, 0),
6911 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
6912 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
6913 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
6916 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
6917 MVT::v2i32, Ops0), 0);
6919 // Combine the constants and the pointer.
6920 const SDValue Ops1[] = {
6921 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
6923 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
6925 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
6928 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
6931 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
6932 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
6933 /// of the resource descriptor) to create an offset, which is added to
6934 /// the resource pointer.
6935 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
6936 SDValue Ptr, uint32_t RsrcDword1,
6937 uint64_t RsrcDword2And3) const {
6938 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
6939 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
6941 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
6942 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
6946 SDValue DataLo = buildSMovImm32(DAG, DL,
6947 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
6948 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
6950 const SDValue Ops[] = {
6951 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
6953 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
6955 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
6957 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
6959 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
6962 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
6965 //===----------------------------------------------------------------------===//
6966 // SI Inline Assembly Support
6967 //===----------------------------------------------------------------------===//
6969 std::pair<unsigned, const TargetRegisterClass *>
6970 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
6971 StringRef Constraint,
6973 if (!isTypeLegal(VT))
6974 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
6976 if (Constraint.size() == 1) {
6977 switch (Constraint[0]) {
6980 switch (VT.getSizeInBits()) {
6982 return std::make_pair(0U, nullptr);
6985 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
6987 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
6989 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
6991 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
6993 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
6997 switch (VT.getSizeInBits()) {
6999 return std::make_pair(0U, nullptr);
7002 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
7004 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
7006 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
7008 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
7010 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
7012 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
7017 if (Constraint.size() > 1) {
7018 const TargetRegisterClass *RC = nullptr;
7019 if (Constraint[1] == 'v') {
7020 RC = &AMDGPU::VGPR_32RegClass;
7021 } else if (Constraint[1] == 's') {
7022 RC = &AMDGPU::SGPR_32RegClass;
7027 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
7028 if (!Failed && Idx < RC->getNumRegs())
7029 return std::make_pair(RC->getRegister(Idx), RC);
7032 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7035 SITargetLowering::ConstraintType
7036 SITargetLowering::getConstraintType(StringRef Constraint) const {
7037 if (Constraint.size() == 1) {
7038 switch (Constraint[0]) {
7042 return C_RegisterClass;
7045 return TargetLowering::getConstraintType(Constraint);
7048 // Figure out which registers should be reserved for stack access. Only after
7049 // the function is legalized do we know all of the non-spill stack objects or if
7050 // calls are present.
7051 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
7052 MachineRegisterInfo &MRI = MF.getRegInfo();
7053 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
7054 const MachineFrameInfo &MFI = MF.getFrameInfo();
7055 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
7056 const SIRegisterInfo *TRI = ST.getRegisterInfo();
7058 if (Info->isEntryFunction()) {
7059 // Callable functions have fixed registers used for stack access.
7060 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
7063 // We have to assume the SP is needed in case there are calls in the function
7064 // during lowering. Calls are only detected after the function is
7065 // lowered. We're about to reserve registers, so don't bother using it if we
7066 // aren't really going to use it.
7067 bool NeedSP = !Info->isEntryFunction() ||
7068 MFI.hasVarSizedObjects() ||
7072 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
7073 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
7075 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
7076 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
7077 Info->getStackPtrOffsetReg()));
7078 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
7081 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
7082 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
7083 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
7084 Info->getScratchWaveOffsetReg());
7086 TargetLoweringBase::finalizeLowering(MF);
7089 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
7091 const APInt &DemandedElts,
7092 const SelectionDAG &DAG,
7093 unsigned Depth) const {
7094 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
7097 if (getSubtarget()->enableHugePrivateBuffer())
7100 // Technically it may be possible to have a dispatch with a single workitem
7101 // that uses the full private memory size, but that's not really useful. We
7102 // can't use vaddr in MUBUF instructions if we don't know the address
7103 // calculation won't overflow, so assume the sign bit is never set.
7104 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);