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 /// 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 "MCTargetDesc/AMDGPUMCTargetDesc.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/CallingConvLower.h"
42 #include "llvm/CodeGen/DAGCombine.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.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/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
89 #define DEBUG_TYPE "si-lower"
91 STATISTIC(NumTailCalls, "Number of tail calls");
93 static cl::opt<bool> EnableVGPRIndexMode(
94 "amdgpu-vgpr-index-mode",
95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
98 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
99 "amdgpu-frame-index-zero-bits",
100 cl::desc("High bits of frame index assumed to be zero"),
104 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
105 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
106 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
107 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
108 return AMDGPU::SGPR0 + Reg;
111 llvm_unreachable("Cannot allocate sgpr");
114 SITargetLowering::SITargetLowering(const TargetMachine &TM,
115 const GCNSubtarget &STI)
116 : AMDGPUTargetLowering(TM, STI),
118 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
119 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
121 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
122 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
124 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
125 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
126 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
128 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
131 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
134 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
135 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
137 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
138 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
140 if (Subtarget->has16BitInsts()) {
141 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
142 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
144 // Unless there are also VOP3P operations, not operations are really legal.
145 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
146 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
147 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
148 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
151 computeRegisterProperties(Subtarget->getRegisterInfo());
153 // We need to custom lower vector stores from local memory
154 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
156 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
157 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
158 setOperationAction(ISD::LOAD, MVT::i1, Custom);
160 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
161 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
162 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
163 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
164 setOperationAction(ISD::STORE, MVT::i1, Custom);
166 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
167 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
168 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
169 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
170 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
171 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
172 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
173 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
174 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
175 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
177 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
178 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i1, Promote);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
182 setOperationAction(ISD::SELECT, MVT::f64, Promote);
183 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
185 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
186 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
187 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
188 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
189 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
191 setOperationAction(ISD::SETCC, MVT::i1, Promote);
192 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
193 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
194 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
196 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
197 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
205 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
209 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
210 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
211 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
213 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
214 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
215 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
217 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
218 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
219 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
220 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
222 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
223 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
224 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
225 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
226 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
227 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
229 setOperationAction(ISD::UADDO, MVT::i32, Legal);
230 setOperationAction(ISD::USUBO, MVT::i32, Legal);
232 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
233 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
236 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
237 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
240 // We only support LOAD/STORE and vector manipulation ops for vectors
241 // with > 4 elements.
242 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
243 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16 }) {
244 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
248 case ISD::BUILD_VECTOR:
250 case ISD::EXTRACT_VECTOR_ELT:
251 case ISD::INSERT_VECTOR_ELT:
252 case ISD::INSERT_SUBVECTOR:
253 case ISD::EXTRACT_SUBVECTOR:
254 case ISD::SCALAR_TO_VECTOR:
256 case ISD::CONCAT_VECTORS:
257 setOperationAction(Op, VT, Custom);
260 setOperationAction(Op, VT, Expand);
266 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
268 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269 // is expanded to avoid having two separate loops in case the index is a VGPR.
271 // Most operations are naturally 32-bit vector operations. We only support
272 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
277 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
280 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
283 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
287 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
288 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
289 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
290 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
292 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
293 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
295 // Avoid stack access for these.
296 // TODO: Generalize to more vector types.
297 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
298 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
299 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
300 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
303 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
304 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
306 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
308 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
309 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
310 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
313 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
314 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
315 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
317 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
318 // and output demarshalling
319 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
322 // We can't return success/failure, only the old value,
323 // let LLVM add the comparison
324 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
325 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
327 if (Subtarget->hasFlatAddressSpace()) {
328 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
329 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
332 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
333 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
335 // On SI this is s_memtime and s_memrealtime on VI.
336 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
337 setOperationAction(ISD::TRAP, MVT::Other, Custom);
338 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
340 if (Subtarget->has16BitInsts()) {
341 setOperationAction(ISD::FLOG, MVT::f16, Custom);
342 setOperationAction(ISD::FLOG10, MVT::f16, Custom);
345 // v_mad_f32 does not support denormals according to some sources.
346 if (!Subtarget->hasFP32Denormals())
347 setOperationAction(ISD::FMAD, MVT::f32, Legal);
349 if (!Subtarget->hasBFI()) {
350 // fcopysign can be done in a single instruction with BFI.
351 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
352 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
355 if (!Subtarget->hasBCNT(32))
356 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
358 if (!Subtarget->hasBCNT(64))
359 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
361 if (Subtarget->hasFFBH())
362 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
364 if (Subtarget->hasFFBL())
365 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
367 // We only really have 32-bit BFE instructions (and 16-bit on VI).
369 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
370 // effort to match them now. We want this to be false for i64 cases when the
371 // extraction isn't restricted to the upper or lower half. Ideally we would
372 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
373 // span the midpoint are probably relatively rare, so don't worry about them
375 if (Subtarget->hasBFE())
376 setHasExtractBitsInsn(true);
378 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
379 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
381 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
382 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
383 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
384 setOperationAction(ISD::FRINT, MVT::f64, Legal);
386 setOperationAction(ISD::FCEIL, MVT::f64, Custom);
387 setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
388 setOperationAction(ISD::FRINT, MVT::f64, Custom);
389 setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
392 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
394 setOperationAction(ISD::FSIN, MVT::f32, Custom);
395 setOperationAction(ISD::FCOS, MVT::f32, Custom);
396 setOperationAction(ISD::FDIV, MVT::f32, Custom);
397 setOperationAction(ISD::FDIV, MVT::f64, Custom);
399 if (Subtarget->has16BitInsts()) {
400 setOperationAction(ISD::Constant, MVT::i16, Legal);
402 setOperationAction(ISD::SMIN, MVT::i16, Legal);
403 setOperationAction(ISD::SMAX, MVT::i16, Legal);
405 setOperationAction(ISD::UMIN, MVT::i16, Legal);
406 setOperationAction(ISD::UMAX, MVT::i16, Legal);
408 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
409 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
411 setOperationAction(ISD::ROTR, MVT::i16, Promote);
412 setOperationAction(ISD::ROTL, MVT::i16, Promote);
414 setOperationAction(ISD::SDIV, MVT::i16, Promote);
415 setOperationAction(ISD::UDIV, MVT::i16, Promote);
416 setOperationAction(ISD::SREM, MVT::i16, Promote);
417 setOperationAction(ISD::UREM, MVT::i16, Promote);
419 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
420 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
422 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
423 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
424 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
425 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
426 setOperationAction(ISD::CTPOP, MVT::i16, Promote);
428 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
430 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
432 setOperationAction(ISD::LOAD, MVT::i16, Custom);
434 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
436 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
437 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
438 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
439 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
441 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
442 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
443 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
444 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
446 // F16 - Constant Actions.
447 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
449 // F16 - Load/Store Actions.
450 setOperationAction(ISD::LOAD, MVT::f16, Promote);
451 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
452 setOperationAction(ISD::STORE, MVT::f16, Promote);
453 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
455 // F16 - VOP1 Actions.
456 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
457 setOperationAction(ISD::FCOS, MVT::f16, Promote);
458 setOperationAction(ISD::FSIN, MVT::f16, Promote);
459 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
460 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
461 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
462 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
463 setOperationAction(ISD::FROUND, MVT::f16, Custom);
465 // F16 - VOP2 Actions.
466 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
467 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
468 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
469 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
470 setOperationAction(ISD::FDIV, MVT::f16, Custom);
472 // F16 - VOP3 Actions.
473 setOperationAction(ISD::FMA, MVT::f16, Legal);
474 if (!Subtarget->hasFP16Denormals())
475 setOperationAction(ISD::FMAD, MVT::f16, Legal);
477 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
478 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
482 case ISD::BUILD_VECTOR:
484 case ISD::EXTRACT_VECTOR_ELT:
485 case ISD::INSERT_VECTOR_ELT:
486 case ISD::INSERT_SUBVECTOR:
487 case ISD::EXTRACT_SUBVECTOR:
488 case ISD::SCALAR_TO_VECTOR:
490 case ISD::CONCAT_VECTORS:
491 setOperationAction(Op, VT, Custom);
494 setOperationAction(Op, VT, Expand);
500 // XXX - Do these do anything? Vector constants turn into build_vector.
501 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
502 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
504 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
505 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
507 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
508 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
509 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
510 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
512 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
513 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
514 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
515 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
517 setOperationAction(ISD::AND, MVT::v2i16, Promote);
518 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
519 setOperationAction(ISD::OR, MVT::v2i16, Promote);
520 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
521 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
522 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
524 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
525 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
526 setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
527 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
529 setOperationAction(ISD::STORE, MVT::v4i16, Promote);
530 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
531 setOperationAction(ISD::STORE, MVT::v4f16, Promote);
532 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
534 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
535 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
536 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
537 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
539 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
540 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
541 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
543 if (!Subtarget->hasVOP3PInsts()) {
544 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
545 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
548 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
549 // This isn't really legal, but this avoids the legalizer unrolling it (and
550 // allows matching fneg (fabs x) patterns)
551 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
554 if (Subtarget->hasVOP3PInsts()) {
555 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
556 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
557 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
558 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
559 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
560 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
561 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
562 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
563 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
564 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
566 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
567 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
568 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
569 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
570 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
571 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
573 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
574 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
576 setOperationAction(ISD::SHL, MVT::v4i16, Custom);
577 setOperationAction(ISD::SRA, MVT::v4i16, Custom);
578 setOperationAction(ISD::SRL, MVT::v4i16, Custom);
579 setOperationAction(ISD::ADD, MVT::v4i16, Custom);
580 setOperationAction(ISD::SUB, MVT::v4i16, Custom);
581 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
583 setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
584 setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
585 setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
586 setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
588 setOperationAction(ISD::FADD, MVT::v4f16, Custom);
589 setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
590 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
591 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
593 setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
594 setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
597 setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
598 setOperationAction(ISD::FABS, MVT::v4f16, Custom);
600 if (Subtarget->has16BitInsts()) {
601 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
602 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
603 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
604 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
606 // Legalization hack.
607 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
608 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
610 setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
611 setOperationAction(ISD::FABS, MVT::v2f16, Custom);
614 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
615 setOperationAction(ISD::SELECT, VT, Custom);
618 setTargetDAGCombine(ISD::ADD);
619 setTargetDAGCombine(ISD::ADDCARRY);
620 setTargetDAGCombine(ISD::SUB);
621 setTargetDAGCombine(ISD::SUBCARRY);
622 setTargetDAGCombine(ISD::FADD);
623 setTargetDAGCombine(ISD::FSUB);
624 setTargetDAGCombine(ISD::FMINNUM);
625 setTargetDAGCombine(ISD::FMAXNUM);
626 setTargetDAGCombine(ISD::FMA);
627 setTargetDAGCombine(ISD::SMIN);
628 setTargetDAGCombine(ISD::SMAX);
629 setTargetDAGCombine(ISD::UMIN);
630 setTargetDAGCombine(ISD::UMAX);
631 setTargetDAGCombine(ISD::SETCC);
632 setTargetDAGCombine(ISD::AND);
633 setTargetDAGCombine(ISD::OR);
634 setTargetDAGCombine(ISD::XOR);
635 setTargetDAGCombine(ISD::SINT_TO_FP);
636 setTargetDAGCombine(ISD::UINT_TO_FP);
637 setTargetDAGCombine(ISD::FCANONICALIZE);
638 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
639 setTargetDAGCombine(ISD::ZERO_EXTEND);
640 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
641 setTargetDAGCombine(ISD::BUILD_VECTOR);
643 // All memory operations. Some folding on the pointer operand is done to help
644 // matching the constant offsets in the addressing modes.
645 setTargetDAGCombine(ISD::LOAD);
646 setTargetDAGCombine(ISD::STORE);
647 setTargetDAGCombine(ISD::ATOMIC_LOAD);
648 setTargetDAGCombine(ISD::ATOMIC_STORE);
649 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
650 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
651 setTargetDAGCombine(ISD::ATOMIC_SWAP);
652 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
653 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
654 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
655 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
656 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
657 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
658 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
659 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
660 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
661 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
663 setSchedulingPreference(Sched::RegPressure);
665 // SI at least has hardware support for floating point exceptions, but no way
666 // of using or handling them is implemented. They are also optional in OpenCL
668 setHasFloatingPointExceptions(Subtarget->hasFPExceptions());
671 const GCNSubtarget *SITargetLowering::getSubtarget() const {
675 //===----------------------------------------------------------------------===//
676 // TargetLowering queries
677 //===----------------------------------------------------------------------===//
679 // v_mad_mix* support a conversion from f16 to f32.
681 // There is only one special case when denormals are enabled we don't currently,
682 // where this is OK to use.
683 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
684 EVT DestVT, EVT SrcVT) const {
685 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
686 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
687 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
688 SrcVT.getScalarType() == MVT::f16;
691 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
692 // SI has some legal vector types, but no legal vector operations. Say no
693 // shuffles are legal in order to prefer scalarizing some vector operations.
697 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
700 unsigned IntrID) const {
701 if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
702 AMDGPU::lookupRsrcIntrinsic(IntrID)) {
703 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
704 (Intrinsic::ID)IntrID);
705 if (Attr.hasFnAttribute(Attribute::ReadNone))
708 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
710 if (RsrcIntr->IsImage) {
711 Info.ptrVal = MFI->getImagePSV(
712 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
713 CI.getArgOperand(RsrcIntr->RsrcArg));
716 Info.ptrVal = MFI->getBufferPSV(
717 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
718 CI.getArgOperand(RsrcIntr->RsrcArg));
721 Info.flags = MachineMemOperand::MODereferenceable;
722 if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
723 Info.opc = ISD::INTRINSIC_W_CHAIN;
724 Info.memVT = MVT::getVT(CI.getType());
725 Info.flags |= MachineMemOperand::MOLoad;
726 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
727 Info.opc = ISD::INTRINSIC_VOID;
728 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
729 Info.flags |= MachineMemOperand::MOStore;
732 Info.opc = ISD::INTRINSIC_W_CHAIN;
733 Info.memVT = MVT::getVT(CI.getType());
734 Info.flags = MachineMemOperand::MOLoad |
735 MachineMemOperand::MOStore |
736 MachineMemOperand::MODereferenceable;
738 // XXX - Should this be volatile without known ordering?
739 Info.flags |= MachineMemOperand::MOVolatile;
745 case Intrinsic::amdgcn_atomic_inc:
746 case Intrinsic::amdgcn_atomic_dec:
747 case Intrinsic::amdgcn_ds_fadd:
748 case Intrinsic::amdgcn_ds_fmin:
749 case Intrinsic::amdgcn_ds_fmax: {
750 Info.opc = ISD::INTRINSIC_W_CHAIN;
751 Info.memVT = MVT::getVT(CI.getType());
752 Info.ptrVal = CI.getOperand(0);
754 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
756 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
757 if (!Vol || !Vol->isZero())
758 Info.flags |= MachineMemOperand::MOVolatile;
768 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
769 SmallVectorImpl<Value*> &Ops,
770 Type *&AccessTy) const {
771 switch (II->getIntrinsicID()) {
772 case Intrinsic::amdgcn_atomic_inc:
773 case Intrinsic::amdgcn_atomic_dec:
774 case Intrinsic::amdgcn_ds_fadd:
775 case Intrinsic::amdgcn_ds_fmin:
776 case Intrinsic::amdgcn_ds_fmax: {
777 Value *Ptr = II->getArgOperand(0);
778 AccessTy = II->getType();
787 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
788 if (!Subtarget->hasFlatInstOffsets()) {
789 // Flat instructions do not have offsets, and only have the register
791 return AM.BaseOffs == 0 && AM.Scale == 0;
794 // GFX9 added a 13-bit signed offset. When using regular flat instructions,
795 // the sign bit is ignored and is treated as a 12-bit unsigned offset.
798 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
801 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
802 if (Subtarget->hasFlatGlobalInsts())
803 return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
805 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
806 // Assume the we will use FLAT for all global memory accesses
808 // FIXME: This assumption is currently wrong. On VI we still use
809 // MUBUF instructions for the r + i addressing mode. As currently
810 // implemented, the MUBUF instructions only work on buffer < 4GB.
811 // It may be possible to support > 4GB buffers with MUBUF instructions,
812 // by setting the stride value in the resource descriptor which would
813 // increase the size limit to (stride * 4GB). However, this is risky,
814 // because it has never been validated.
815 return isLegalFlatAddressingMode(AM);
818 return isLegalMUBUFAddressingMode(AM);
821 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
822 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
823 // additionally can do r + r + i with addr64. 32-bit has more addressing
824 // mode options. Depending on the resource constant, it can also do
825 // (i64 r0) + (i32 r1) * (i14 i).
827 // Private arrays end up using a scratch buffer most of the time, so also
828 // assume those use MUBUF instructions. Scratch loads / stores are currently
829 // implemented as mubuf instructions with offen bit set, so slightly
830 // different than the normal addr64.
831 if (!isUInt<12>(AM.BaseOffs))
834 // FIXME: Since we can split immediate into soffset and immediate offset,
835 // would it make sense to allow any immediate?
838 case 0: // r + i or just i, depending on HasBaseReg.
841 return true; // We have r + r or r + i.
848 // Allow 2 * r as r + r
849 // Or 2 * r + i is allowed as r + r + i.
851 default: // Don't allow n * r
856 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
857 const AddrMode &AM, Type *Ty,
858 unsigned AS, Instruction *I) const {
859 // No global is ever allowed as a base.
863 if (AS == AMDGPUASI.GLOBAL_ADDRESS)
864 return isLegalGlobalAddressingMode(AM);
866 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
867 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
868 // If the offset isn't a multiple of 4, it probably isn't going to be
869 // correctly aligned.
870 // FIXME: Can we get the real alignment here?
871 if (AM.BaseOffs % 4 != 0)
872 return isLegalMUBUFAddressingMode(AM);
874 // There are no SMRD extloads, so if we have to do a small type access we
875 // will use a MUBUF load.
876 // FIXME?: We also need to do this if unaligned, but we don't know the
878 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
879 return isLegalGlobalAddressingMode(AM);
881 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
882 // SMRD instructions have an 8-bit, dword offset on SI.
883 if (!isUInt<8>(AM.BaseOffs / 4))
885 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
886 // On CI+, this can also be a 32-bit literal constant offset. If it fits
887 // in 8-bits, it can use a smaller encoding.
888 if (!isUInt<32>(AM.BaseOffs / 4))
890 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
891 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
892 if (!isUInt<20>(AM.BaseOffs))
895 llvm_unreachable("unhandled generation");
897 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
900 if (AM.Scale == 1 && AM.HasBaseReg)
905 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
906 return isLegalMUBUFAddressingMode(AM);
907 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
908 AS == AMDGPUASI.REGION_ADDRESS) {
909 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
911 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
912 // an 8-bit dword offset but we don't know the alignment here.
913 if (!isUInt<16>(AM.BaseOffs))
916 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
919 if (AM.Scale == 1 && AM.HasBaseReg)
923 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
924 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
925 // For an unknown address space, this usually means that this is for some
926 // reason being used for pure arithmetic, and not based on some addressing
927 // computation. We don't have instructions that compute pointers with any
928 // addressing modes, so treat them as having no offset like flat
930 return isLegalFlatAddressingMode(AM);
932 llvm_unreachable("unhandled address space");
936 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
937 const SelectionDAG &DAG) const {
938 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
939 return (MemVT.getSizeInBits() <= 4 * 32);
940 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
941 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
942 return (MemVT.getSizeInBits() <= MaxPrivateBits);
943 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
944 return (MemVT.getSizeInBits() <= 2 * 32);
949 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
952 bool *IsFast) const {
956 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
957 // which isn't a simple VT.
958 // Until MVT is extended to handle this, simply check for the size and
959 // rely on the condition below: allow accesses if the size is a multiple of 4.
960 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
961 VT.getStoreSize() > 16)) {
965 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
966 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
967 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
968 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
969 // with adjacent offsets.
970 bool AlignedBy4 = (Align % 4 == 0);
972 *IsFast = AlignedBy4;
977 // FIXME: We have to be conservative here and assume that flat operations
978 // will access scratch. If we had access to the IR function, then we
979 // could determine if any private memory was used in the function.
980 if (!Subtarget->hasUnalignedScratchAccess() &&
981 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
982 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
986 if (Subtarget->hasUnalignedBufferAccess()) {
987 // If we have an uniform constant load, it still requires using a slow
988 // buffer instruction if unaligned.
990 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
991 AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
992 (Align % 4 == 0) : true;
998 // Smaller than dword value must be aligned.
999 if (VT.bitsLT(MVT::i32))
1002 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1003 // byte-address are ignored, thus forcing Dword alignment.
1004 // This applies to private, global, and constant memory.
1008 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1011 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1012 unsigned SrcAlign, bool IsMemset,
1015 MachineFunction &MF) const {
1016 // FIXME: Should account for address space here.
1018 // The default fallback uses the private pointer size as a guess for a type to
1019 // use. Make sure we switch these to 64-bit accesses.
1021 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1024 if (Size >= 8 && DstAlign >= 4)
1031 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1032 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1033 AS == AMDGPUASI.FLAT_ADDRESS ||
1034 AS == AMDGPUASI.CONSTANT_ADDRESS ||
1035 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
1038 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1039 unsigned DestAS) const {
1040 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1041 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1044 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1045 const MemSDNode *MemNode = cast<MemSDNode>(N);
1046 const Value *Ptr = MemNode->getMemOperand()->getValue();
1047 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1048 return I && I->getMetadata("amdgpu.noclobber");
1051 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1052 unsigned DestAS) const {
1053 // Flat -> private/local is a simple truncate.
1054 // Flat -> global is no-op
1055 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1058 return isNoopAddrSpaceCast(SrcAS, DestAS);
1061 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1062 const MemSDNode *MemNode = cast<MemSDNode>(N);
1064 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1067 TargetLoweringBase::LegalizeTypeAction
1068 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1069 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1070 return TypeSplitVector;
1072 return TargetLoweringBase::getPreferredVectorAction(VT);
1075 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1077 // FIXME: Could be smarter if called for vector constants.
1081 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1082 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1087 // These operations are done with 32-bit instructions anyway.
1092 // TODO: Extensions?
1099 // SimplifySetCC uses this function to determine whether or not it should
1100 // create setcc with i1 operands. We don't have instructions for i1 setcc.
1101 if (VT == MVT::i1 && Op == ISD::SETCC)
1104 return TargetLowering::isTypeDesirableForOp(Op, VT);
1107 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1110 uint64_t Offset) const {
1111 const DataLayout &DL = DAG.getDataLayout();
1112 MachineFunction &MF = DAG.getMachineFunction();
1113 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1115 const ArgDescriptor *InputPtrReg;
1116 const TargetRegisterClass *RC;
1118 std::tie(InputPtrReg, RC)
1119 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1121 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1122 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1123 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1124 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1126 return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1129 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1130 const SDLoc &SL) const {
1131 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1133 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1136 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1137 const SDLoc &SL, SDValue Val,
1139 const ISD::InputArg *Arg) const {
1140 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1142 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1143 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1146 if (MemVT.isFloatingPoint())
1147 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1149 Val = DAG.getSExtOrTrunc(Val, SL, VT);
1151 Val = DAG.getZExtOrTrunc(Val, SL, VT);
1156 SDValue SITargetLowering::lowerKernargMemParameter(
1157 SelectionDAG &DAG, EVT VT, EVT MemVT,
1158 const SDLoc &SL, SDValue Chain,
1159 uint64_t Offset, unsigned Align, bool Signed,
1160 const ISD::InputArg *Arg) const {
1161 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1162 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1163 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1165 // Try to avoid using an extload by loading earlier than the argument address,
1166 // and extracting the relevant bits. The load should hopefully be merged with
1167 // the previous argument.
1168 if (MemVT.getStoreSize() < 4 && Align < 4) {
1169 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1170 int64_t AlignDownOffset = alignDown(Offset, 4);
1171 int64_t OffsetDiff = Offset - AlignDownOffset;
1173 EVT IntVT = MemVT.changeTypeToInteger();
1175 // TODO: If we passed in the base kernel offset we could have a better
1176 // alignment than 4, but we don't really need it.
1177 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1178 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1179 MachineMemOperand::MODereferenceable |
1180 MachineMemOperand::MOInvariant);
1182 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1183 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1185 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1186 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1187 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1190 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1193 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1194 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1195 MachineMemOperand::MODereferenceable |
1196 MachineMemOperand::MOInvariant);
1198 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1199 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1202 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1203 const SDLoc &SL, SDValue Chain,
1204 const ISD::InputArg &Arg) const {
1205 MachineFunction &MF = DAG.getMachineFunction();
1206 MachineFrameInfo &MFI = MF.getFrameInfo();
1208 if (Arg.Flags.isByVal()) {
1209 unsigned Size = Arg.Flags.getByValSize();
1210 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1211 return DAG.getFrameIndex(FrameIdx, MVT::i32);
1214 unsigned ArgOffset = VA.getLocMemOffset();
1215 unsigned ArgSize = VA.getValVT().getStoreSize();
1217 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1219 // Create load nodes to retrieve arguments from the stack.
1220 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1223 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1224 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1225 MVT MemVT = VA.getValVT();
1227 switch (VA.getLocInfo()) {
1230 case CCValAssign::BCvt:
1231 MemVT = VA.getLocVT();
1233 case CCValAssign::SExt:
1234 ExtType = ISD::SEXTLOAD;
1236 case CCValAssign::ZExt:
1237 ExtType = ISD::ZEXTLOAD;
1239 case CCValAssign::AExt:
1240 ExtType = ISD::EXTLOAD;
1244 ArgValue = DAG.getExtLoad(
1245 ExtType, SL, VA.getLocVT(), Chain, FIN,
1246 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1251 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1252 const SIMachineFunctionInfo &MFI,
1254 AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1255 const ArgDescriptor *Reg;
1256 const TargetRegisterClass *RC;
1258 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1259 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1262 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1263 CallingConv::ID CallConv,
1264 ArrayRef<ISD::InputArg> Ins,
1266 FunctionType *FType,
1267 SIMachineFunctionInfo *Info) {
1268 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1269 const ISD::InputArg *Arg = &Ins[I];
1271 // First check if it's a PS input addr.
1272 if (CallConv == CallingConv::AMDGPU_PS &&
1273 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1275 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1277 // Inconveniently only the first part of the split is marked as isSplit,
1278 // so skip to the end. We only want to increment PSInputNum once for the
1279 // entire split argument.
1280 if (Arg->Flags.isSplit()) {
1281 while (!Arg->Flags.isSplitEnd()) {
1282 assert(!Arg->VT.isVector() &&
1283 "unexpected vector split in ps argument type");
1285 Splits.push_back(*Arg);
1291 // We can safely skip PS inputs.
1292 Skipped.set(Arg->getOrigArgIndex());
1297 Info->markPSInputAllocated(PSInputNum);
1299 Info->markPSInputEnabled(PSInputNum);
1304 // Second split vertices into their elements.
1305 if (Arg->VT.isVector()) {
1306 ISD::InputArg NewArg = *Arg;
1307 NewArg.Flags.setSplit();
1308 NewArg.VT = Arg->VT.getVectorElementType();
1310 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1311 // three or five element vertex only needs three or five registers,
1312 // NOT four or eight.
1313 Type *ParamType = FType->getParamType(Arg->getOrigArgIndex());
1314 unsigned NumElements = ParamType->getVectorNumElements();
1316 for (unsigned J = 0; J != NumElements; ++J) {
1317 Splits.push_back(NewArg);
1318 NewArg.PartOffset += NewArg.VT.getStoreSize();
1321 Splits.push_back(*Arg);
1326 // Allocate special inputs passed in VGPRs.
1327 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1328 MachineFunction &MF,
1329 const SIRegisterInfo &TRI,
1330 SIMachineFunctionInfo &Info) {
1331 if (Info.hasWorkItemIDX()) {
1332 unsigned Reg = AMDGPU::VGPR0;
1333 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1335 CCInfo.AllocateReg(Reg);
1336 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1339 if (Info.hasWorkItemIDY()) {
1340 unsigned Reg = AMDGPU::VGPR1;
1341 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1343 CCInfo.AllocateReg(Reg);
1344 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1347 if (Info.hasWorkItemIDZ()) {
1348 unsigned Reg = AMDGPU::VGPR2;
1349 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1351 CCInfo.AllocateReg(Reg);
1352 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1356 // Try to allocate a VGPR at the end of the argument list, or if no argument
1357 // VGPRs are left allocating a stack slot.
1358 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1359 ArrayRef<MCPhysReg> ArgVGPRs
1360 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1361 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1362 if (RegIdx == ArgVGPRs.size()) {
1363 // Spill to stack required.
1364 int64_t Offset = CCInfo.AllocateStack(4, 4);
1366 return ArgDescriptor::createStack(Offset);
1369 unsigned Reg = ArgVGPRs[RegIdx];
1370 Reg = CCInfo.AllocateReg(Reg);
1371 assert(Reg != AMDGPU::NoRegister);
1373 MachineFunction &MF = CCInfo.getMachineFunction();
1374 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1375 return ArgDescriptor::createRegister(Reg);
1378 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1379 const TargetRegisterClass *RC,
1380 unsigned NumArgRegs) {
1381 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1382 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1383 if (RegIdx == ArgSGPRs.size())
1384 report_fatal_error("ran out of SGPRs for arguments");
1386 unsigned Reg = ArgSGPRs[RegIdx];
1387 Reg = CCInfo.AllocateReg(Reg);
1388 assert(Reg != AMDGPU::NoRegister);
1390 MachineFunction &MF = CCInfo.getMachineFunction();
1391 MF.addLiveIn(Reg, RC);
1392 return ArgDescriptor::createRegister(Reg);
1395 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1396 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1399 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1400 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1403 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1404 MachineFunction &MF,
1405 const SIRegisterInfo &TRI,
1406 SIMachineFunctionInfo &Info) {
1407 if (Info.hasWorkItemIDX())
1408 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1410 if (Info.hasWorkItemIDY())
1411 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1413 if (Info.hasWorkItemIDZ())
1414 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1417 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1418 MachineFunction &MF,
1419 const SIRegisterInfo &TRI,
1420 SIMachineFunctionInfo &Info) {
1421 auto &ArgInfo = Info.getArgInfo();
1423 // TODO: Unify handling with private memory pointers.
1425 if (Info.hasDispatchPtr())
1426 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1428 if (Info.hasQueuePtr())
1429 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1431 if (Info.hasKernargSegmentPtr())
1432 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1434 if (Info.hasDispatchID())
1435 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1437 // flat_scratch_init is not applicable for non-kernel functions.
1439 if (Info.hasWorkGroupIDX())
1440 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1442 if (Info.hasWorkGroupIDY())
1443 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1445 if (Info.hasWorkGroupIDZ())
1446 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1448 if (Info.hasImplicitArgPtr())
1449 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1452 // Allocate special inputs passed in user SGPRs.
1453 static void allocateHSAUserSGPRs(CCState &CCInfo,
1454 MachineFunction &MF,
1455 const SIRegisterInfo &TRI,
1456 SIMachineFunctionInfo &Info) {
1457 if (Info.hasImplicitBufferPtr()) {
1458 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1459 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1460 CCInfo.AllocateReg(ImplicitBufferPtrReg);
1463 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1464 if (Info.hasPrivateSegmentBuffer()) {
1465 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1466 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1467 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1470 if (Info.hasDispatchPtr()) {
1471 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1472 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1473 CCInfo.AllocateReg(DispatchPtrReg);
1476 if (Info.hasQueuePtr()) {
1477 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1478 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1479 CCInfo.AllocateReg(QueuePtrReg);
1482 if (Info.hasKernargSegmentPtr()) {
1483 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1484 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1485 CCInfo.AllocateReg(InputPtrReg);
1488 if (Info.hasDispatchID()) {
1489 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1490 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1491 CCInfo.AllocateReg(DispatchIDReg);
1494 if (Info.hasFlatScratchInit()) {
1495 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1496 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1497 CCInfo.AllocateReg(FlatScratchInitReg);
1500 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1501 // these from the dispatch pointer.
1504 // Allocate special input registers that are initialized per-wave.
1505 static void allocateSystemSGPRs(CCState &CCInfo,
1506 MachineFunction &MF,
1507 SIMachineFunctionInfo &Info,
1508 CallingConv::ID CallConv,
1510 if (Info.hasWorkGroupIDX()) {
1511 unsigned Reg = Info.addWorkGroupIDX();
1512 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1513 CCInfo.AllocateReg(Reg);
1516 if (Info.hasWorkGroupIDY()) {
1517 unsigned Reg = Info.addWorkGroupIDY();
1518 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1519 CCInfo.AllocateReg(Reg);
1522 if (Info.hasWorkGroupIDZ()) {
1523 unsigned Reg = Info.addWorkGroupIDZ();
1524 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1525 CCInfo.AllocateReg(Reg);
1528 if (Info.hasWorkGroupInfo()) {
1529 unsigned Reg = Info.addWorkGroupInfo();
1530 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1531 CCInfo.AllocateReg(Reg);
1534 if (Info.hasPrivateSegmentWaveByteOffset()) {
1535 // Scratch wave offset passed in system SGPR.
1536 unsigned PrivateSegmentWaveByteOffsetReg;
1539 PrivateSegmentWaveByteOffsetReg =
1540 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1542 // This is true if the scratch wave byte offset doesn't have a fixed
1544 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1545 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1546 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1549 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1551 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1552 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1556 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1557 MachineFunction &MF,
1558 const SIRegisterInfo &TRI,
1559 SIMachineFunctionInfo &Info) {
1560 // Now that we've figured out where the scratch register inputs are, see if
1561 // should reserve the arguments and use them directly.
1562 MachineFrameInfo &MFI = MF.getFrameInfo();
1563 bool HasStackObjects = MFI.hasStackObjects();
1565 // Record that we know we have non-spill stack objects so we don't need to
1566 // check all stack objects later.
1567 if (HasStackObjects)
1568 Info.setHasNonSpillStackObjects(true);
1570 // Everything live out of a block is spilled with fast regalloc, so it's
1571 // almost certain that spilling will be required.
1572 if (TM.getOptLevel() == CodeGenOpt::None)
1573 HasStackObjects = true;
1575 // For now assume stack access is needed in any callee functions, so we need
1576 // the scratch registers to pass in.
1577 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1579 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1580 if (ST.isAmdCodeObjectV2(MF.getFunction())) {
1581 if (RequiresStackAccess) {
1582 // If we have stack objects, we unquestionably need the private buffer
1583 // resource. For the Code Object V2 ABI, this will be the first 4 user
1584 // SGPR inputs. We can reserve those and use them directly.
1586 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1587 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1588 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1590 if (MFI.hasCalls()) {
1591 // If we have calls, we need to keep the frame register in a register
1592 // that won't be clobbered by a call, so ensure it is copied somewhere.
1594 // This is not a problem for the scratch wave offset, because the same
1595 // registers are reserved in all functions.
1597 // FIXME: Nothing is really ensuring this is a call preserved register,
1598 // it's just selected from the end so it happens to be.
1599 unsigned ReservedOffsetReg
1600 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1601 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1603 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1604 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1605 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1608 unsigned ReservedBufferReg
1609 = TRI.reservedPrivateSegmentBufferReg(MF);
1610 unsigned ReservedOffsetReg
1611 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1613 // We tentatively reserve the last registers (skipping the last two
1614 // which may contain VCC). After register allocation, we'll replace
1615 // these with the ones immediately after those which were really
1616 // allocated. In the prologue copies will be inserted from the argument
1617 // to these reserved registers.
1618 Info.setScratchRSrcReg(ReservedBufferReg);
1619 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1622 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1624 // Without HSA, relocations are used for the scratch pointer and the
1625 // buffer resource setup is always inserted in the prologue. Scratch wave
1626 // offset is still in an input SGPR.
1627 Info.setScratchRSrcReg(ReservedBufferReg);
1629 if (HasStackObjects && !MFI.hasCalls()) {
1630 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1631 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1632 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1634 unsigned ReservedOffsetReg
1635 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1636 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1641 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1642 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1643 return !Info->isEntryFunction();
1646 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1650 void SITargetLowering::insertCopiesSplitCSR(
1651 MachineBasicBlock *Entry,
1652 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1653 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1655 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1659 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1660 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1661 MachineBasicBlock::iterator MBBI = Entry->begin();
1662 for (const MCPhysReg *I = IStart; *I; ++I) {
1663 const TargetRegisterClass *RC = nullptr;
1664 if (AMDGPU::SReg_64RegClass.contains(*I))
1665 RC = &AMDGPU::SGPR_64RegClass;
1666 else if (AMDGPU::SReg_32RegClass.contains(*I))
1667 RC = &AMDGPU::SGPR_32RegClass;
1669 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1671 unsigned NewVR = MRI->createVirtualRegister(RC);
1672 // Create copy from CSR to a virtual register.
1673 Entry->addLiveIn(*I);
1674 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1677 // Insert the copy-back instructions right before the terminator.
1678 for (auto *Exit : Exits)
1679 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1680 TII->get(TargetOpcode::COPY), *I)
1685 SDValue SITargetLowering::LowerFormalArguments(
1686 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1687 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1688 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1689 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1691 MachineFunction &MF = DAG.getMachineFunction();
1692 const Function &Fn = MF.getFunction();
1693 FunctionType *FType = MF.getFunction().getFunctionType();
1694 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1695 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1697 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1698 DiagnosticInfoUnsupported NoGraphicsHSA(
1699 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1700 DAG.getContext()->diagnose(NoGraphicsHSA);
1701 return DAG.getEntryNode();
1704 // Create stack objects that are used for emitting debugger prologue if
1705 // "amdgpu-debugger-emit-prologue" attribute was specified.
1706 if (ST.debuggerEmitPrologue())
1707 createDebuggerPrologueStackObjects(MF);
1709 SmallVector<ISD::InputArg, 16> Splits;
1710 SmallVector<CCValAssign, 16> ArgLocs;
1711 BitVector Skipped(Ins.size());
1712 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1715 bool IsShader = AMDGPU::isShader(CallConv);
1716 bool IsKernel = AMDGPU::isKernel(CallConv);
1717 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1720 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1721 // this when allocating argument fixed offsets.
1722 CCInfo.AllocateStack(4, 4);
1726 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1728 // At least one interpolation mode must be enabled or else the GPU will
1731 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1732 // set PSInputAddr, the user wants to enable some bits after the compilation
1733 // based on run-time states. Since we can't know what the final PSInputEna
1734 // will look like, so we shouldn't do anything here and the user should take
1735 // responsibility for the correct programming.
1737 // Otherwise, the following restrictions apply:
1738 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1739 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1741 if (CallConv == CallingConv::AMDGPU_PS) {
1742 if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1743 ((Info->getPSInputAddr() & 0xF) == 0 &&
1744 Info->isPSInputAllocated(11))) {
1745 CCInfo.AllocateReg(AMDGPU::VGPR0);
1746 CCInfo.AllocateReg(AMDGPU::VGPR1);
1747 Info->markPSInputAllocated(0);
1748 Info->markPSInputEnabled(0);
1750 if (Subtarget->isAmdPalOS()) {
1751 // For isAmdPalOS, the user does not enable some bits after compilation
1752 // based on run-time states; the register values being generated here are
1753 // the final ones set in hardware. Therefore we need to apply the
1754 // workaround to PSInputAddr and PSInputEnable together. (The case where
1755 // a bit is set in PSInputAddr but not PSInputEnable is where the
1756 // frontend set up an input arg for a particular interpolation mode, but
1757 // nothing uses that input arg. Really we should have an earlier pass
1758 // that removes such an arg.)
1759 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1760 if ((PsInputBits & 0x7F) == 0 ||
1761 ((PsInputBits & 0xF) == 0 &&
1762 (PsInputBits >> 11 & 1)))
1763 Info->markPSInputEnabled(
1764 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1768 assert(!Info->hasDispatchPtr() &&
1769 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1770 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1771 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1772 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1773 !Info->hasWorkItemIDZ());
1774 } else if (IsKernel) {
1775 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1777 Splits.append(Ins.begin(), Ins.end());
1781 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1782 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1786 analyzeFormalArgumentsCompute(CCInfo, Ins);
1788 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1789 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1792 SmallVector<SDValue, 16> Chains;
1794 // FIXME: This is the minimum kernel argument alignment. We should improve
1795 // this to the maximum alignment of the arguments.
1797 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1799 const unsigned KernelArgBaseAlign = 16;
1801 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1802 const ISD::InputArg &Arg = Ins[i];
1803 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
1804 InVals.push_back(DAG.getUNDEF(Arg.VT));
1808 CCValAssign &VA = ArgLocs[ArgIdx++];
1809 MVT VT = VA.getLocVT();
1811 if (IsEntryFunc && VA.isMemLoc()) {
1813 EVT MemVT = VA.getLocVT();
1815 const uint64_t Offset = VA.getLocMemOffset();
1816 unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1818 SDValue Arg = lowerKernargMemParameter(
1819 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1820 Chains.push_back(Arg.getValue(1));
1823 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1824 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1825 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1826 // On SI local pointers are just offsets into LDS, so they are always
1827 // less than 16-bits. On CI and newer they could potentially be
1828 // real pointers, so we can't guarantee their size.
1829 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1830 DAG.getValueType(MVT::i16));
1833 InVals.push_back(Arg);
1835 } else if (!IsEntryFunc && VA.isMemLoc()) {
1836 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1837 InVals.push_back(Val);
1838 if (!Arg.Flags.isByVal())
1839 Chains.push_back(Val.getValue(1));
1843 assert(VA.isRegLoc() && "Parameter must be in a register!");
1845 unsigned Reg = VA.getLocReg();
1846 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1847 EVT ValVT = VA.getValVT();
1849 Reg = MF.addLiveIn(Reg, RC);
1850 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1852 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1853 // The return object should be reasonably addressable.
1855 // FIXME: This helps when the return is a real sret. If it is a
1856 // automatically inserted sret (i.e. CanLowerReturn returns false), an
1857 // extra copy is inserted in SelectionDAGBuilder which obscures this.
1858 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1859 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1860 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1863 // If this is an 8 or 16-bit value, it is really passed promoted
1864 // to 32 bits. Insert an assert[sz]ext to capture this, then
1865 // truncate to the right size.
1866 switch (VA.getLocInfo()) {
1867 case CCValAssign::Full:
1869 case CCValAssign::BCvt:
1870 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1872 case CCValAssign::SExt:
1873 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1874 DAG.getValueType(ValVT));
1875 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1877 case CCValAssign::ZExt:
1878 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1879 DAG.getValueType(ValVT));
1880 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1882 case CCValAssign::AExt:
1883 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1886 llvm_unreachable("Unknown loc info!");
1889 if (IsShader && Arg.VT.isVector()) {
1890 // Build a vector from the registers
1891 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1892 unsigned NumElements = ParamType->getVectorNumElements();
1894 SmallVector<SDValue, 4> Regs;
1895 Regs.push_back(Val);
1896 for (unsigned j = 1; j != NumElements; ++j) {
1897 Reg = ArgLocs[ArgIdx++].getLocReg();
1898 Reg = MF.addLiveIn(Reg, RC);
1900 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1901 Regs.push_back(Copy);
1904 // Fill up the missing vector elements
1905 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1906 Regs.append(NumElements, DAG.getUNDEF(VT));
1908 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1912 InVals.push_back(Val);
1916 // Special inputs come after user arguments.
1917 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1920 // Start adding system SGPRs.
1922 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1924 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1925 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1926 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1927 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1930 auto &ArgUsageInfo =
1931 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1932 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
1934 unsigned StackArgSize = CCInfo.getNextStackOffset();
1935 Info->setBytesInStackArgArea(StackArgSize);
1937 return Chains.empty() ? Chain :
1938 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1941 // TODO: If return values can't fit in registers, we should return as many as
1942 // possible in registers before passing on stack.
1943 bool SITargetLowering::CanLowerReturn(
1944 CallingConv::ID CallConv,
1945 MachineFunction &MF, bool IsVarArg,
1946 const SmallVectorImpl<ISD::OutputArg> &Outs,
1947 LLVMContext &Context) const {
1948 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1949 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1950 // for shaders. Vector types should be explicitly handled by CC.
1951 if (AMDGPU::isEntryFunctionCC(CallConv))
1954 SmallVector<CCValAssign, 16> RVLocs;
1955 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1956 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1960 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1962 const SmallVectorImpl<ISD::OutputArg> &Outs,
1963 const SmallVectorImpl<SDValue> &OutVals,
1964 const SDLoc &DL, SelectionDAG &DAG) const {
1965 MachineFunction &MF = DAG.getMachineFunction();
1966 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1968 if (AMDGPU::isKernel(CallConv)) {
1969 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1973 bool IsShader = AMDGPU::isShader(CallConv);
1975 Info->setIfReturnsVoid(Outs.size() == 0);
1976 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1978 SmallVector<ISD::OutputArg, 48> Splits;
1979 SmallVector<SDValue, 48> SplitVals;
1981 // Split vectors into their elements.
1982 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1983 const ISD::OutputArg &Out = Outs[i];
1985 if (IsShader && Out.VT.isVector()) {
1986 MVT VT = Out.VT.getVectorElementType();
1987 ISD::OutputArg NewOut = Out;
1988 NewOut.Flags.setSplit();
1991 // We want the original number of vector elements here, e.g.
1992 // three or five, not four or eight.
1993 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1995 for (unsigned j = 0; j != NumElements; ++j) {
1996 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1997 DAG.getConstant(j, DL, MVT::i32));
1998 SplitVals.push_back(Elem);
1999 Splits.push_back(NewOut);
2000 NewOut.PartOffset += NewOut.VT.getStoreSize();
2003 SplitVals.push_back(OutVals[i]);
2004 Splits.push_back(Out);
2008 // CCValAssign - represent the assignment of the return value to a location.
2009 SmallVector<CCValAssign, 48> RVLocs;
2011 // CCState - Info about the registers and stack slots.
2012 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2015 // Analyze outgoing return values.
2016 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2019 SmallVector<SDValue, 48> RetOps;
2020 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2022 // Add return address for callable functions.
2023 if (!Info->isEntryFunction()) {
2024 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2025 SDValue ReturnAddrReg = CreateLiveInRegister(
2026 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2028 // FIXME: Should be able to use a vreg here, but need a way to prevent it
2029 // from being allcoated to a CSR.
2031 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2034 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2035 Flag = Chain.getValue(1);
2037 RetOps.push_back(PhysReturnAddrReg);
2040 // Copy the result values into the output registers.
2041 for (unsigned i = 0, realRVLocIdx = 0;
2043 ++i, ++realRVLocIdx) {
2044 CCValAssign &VA = RVLocs[i];
2045 assert(VA.isRegLoc() && "Can only return in registers!");
2046 // TODO: Partially return in registers if return values don't fit.
2048 SDValue Arg = SplitVals[realRVLocIdx];
2050 // Copied from other backends.
2051 switch (VA.getLocInfo()) {
2052 case CCValAssign::Full:
2054 case CCValAssign::BCvt:
2055 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2057 case CCValAssign::SExt:
2058 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2060 case CCValAssign::ZExt:
2061 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2063 case CCValAssign::AExt:
2064 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2067 llvm_unreachable("Unknown loc info!");
2070 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2071 Flag = Chain.getValue(1);
2072 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2075 // FIXME: Does sret work properly?
2076 if (!Info->isEntryFunction()) {
2077 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2078 const MCPhysReg *I =
2079 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2082 if (AMDGPU::SReg_64RegClass.contains(*I))
2083 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2084 else if (AMDGPU::SReg_32RegClass.contains(*I))
2085 RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2087 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2092 // Update chain and glue.
2095 RetOps.push_back(Flag);
2097 unsigned Opc = AMDGPUISD::ENDPGM;
2099 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2100 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2103 SDValue SITargetLowering::LowerCallResult(
2104 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2105 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2106 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2107 SDValue ThisVal) const {
2108 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2110 // Assign locations to each value returned by this call.
2111 SmallVector<CCValAssign, 16> RVLocs;
2112 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2114 CCInfo.AnalyzeCallResult(Ins, RetCC);
2116 // Copy all of the result registers out of their specified physreg.
2117 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2118 CCValAssign VA = RVLocs[i];
2121 if (VA.isRegLoc()) {
2122 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2123 Chain = Val.getValue(1);
2124 InFlag = Val.getValue(2);
2125 } else if (VA.isMemLoc()) {
2126 report_fatal_error("TODO: return values in memory");
2128 llvm_unreachable("unknown argument location type");
2130 switch (VA.getLocInfo()) {
2131 case CCValAssign::Full:
2133 case CCValAssign::BCvt:
2134 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2136 case CCValAssign::ZExt:
2137 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2138 DAG.getValueType(VA.getValVT()));
2139 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2141 case CCValAssign::SExt:
2142 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2143 DAG.getValueType(VA.getValVT()));
2144 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2146 case CCValAssign::AExt:
2147 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2150 llvm_unreachable("Unknown loc info!");
2153 InVals.push_back(Val);
2159 // Add code to pass special inputs required depending on used features separate
2160 // from the explicit user arguments present in the IR.
2161 void SITargetLowering::passSpecialInputs(
2162 CallLoweringInfo &CLI,
2163 const SIMachineFunctionInfo &Info,
2164 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2165 SmallVectorImpl<SDValue> &MemOpChains,
2167 SDValue StackPtr) const {
2168 // If we don't have a call site, this was a call inserted by
2169 // legalization. These can never use special inputs.
2173 const Function *CalleeFunc = CLI.CS.getCalledFunction();
2176 SelectionDAG &DAG = CLI.DAG;
2177 const SDLoc &DL = CLI.DL;
2179 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2181 auto &ArgUsageInfo =
2182 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2183 const AMDGPUFunctionArgInfo &CalleeArgInfo
2184 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2186 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2188 // TODO: Unify with private memory register handling. This is complicated by
2189 // the fact that at least in kernels, the input argument is not necessarily
2190 // in the same location as the input.
2191 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2192 AMDGPUFunctionArgInfo::DISPATCH_PTR,
2193 AMDGPUFunctionArgInfo::QUEUE_PTR,
2194 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2195 AMDGPUFunctionArgInfo::DISPATCH_ID,
2196 AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2197 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2198 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2199 AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2200 AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2201 AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2202 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2205 for (auto InputID : InputRegs) {
2206 const ArgDescriptor *OutgoingArg;
2207 const TargetRegisterClass *ArgRC;
2209 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2213 const ArgDescriptor *IncomingArg;
2214 const TargetRegisterClass *IncomingArgRC;
2215 std::tie(IncomingArg, IncomingArgRC)
2216 = CallerArgInfo.getPreloadedValue(InputID);
2217 assert(IncomingArgRC == ArgRC);
2219 // All special arguments are ints for now.
2220 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2224 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2226 // The implicit arg ptr is special because it doesn't have a corresponding
2227 // input for kernels, and is computed from the kernarg segment pointer.
2228 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2229 InputReg = getImplicitArgPtr(DAG, DL);
2232 if (OutgoingArg->isRegister()) {
2233 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2235 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2237 OutgoingArg->getStackOffset());
2238 MemOpChains.push_back(ArgStore);
2243 static bool canGuaranteeTCO(CallingConv::ID CC) {
2244 return CC == CallingConv::Fast;
2247 /// Return true if we might ever do TCO for calls with this calling convention.
2248 static bool mayTailCallThisCC(CallingConv::ID CC) {
2250 case CallingConv::C:
2253 return canGuaranteeTCO(CC);
2257 bool SITargetLowering::isEligibleForTailCallOptimization(
2258 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2259 const SmallVectorImpl<ISD::OutputArg> &Outs,
2260 const SmallVectorImpl<SDValue> &OutVals,
2261 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2262 if (!mayTailCallThisCC(CalleeCC))
2265 MachineFunction &MF = DAG.getMachineFunction();
2266 const Function &CallerF = MF.getFunction();
2267 CallingConv::ID CallerCC = CallerF.getCallingConv();
2268 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2269 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2271 // Kernels aren't callable, and don't have a live in return address so it
2272 // doesn't make sense to do a tail call with entry functions.
2273 if (!CallerPreserved)
2276 bool CCMatch = CallerCC == CalleeCC;
2278 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2279 if (canGuaranteeTCO(CalleeCC) && CCMatch)
2284 // TODO: Can we handle var args?
2288 for (const Argument &Arg : CallerF.args()) {
2289 if (Arg.hasByValAttr())
2293 LLVMContext &Ctx = *DAG.getContext();
2295 // Check that the call results are passed in the same way.
2296 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2297 CCAssignFnForCall(CalleeCC, IsVarArg),
2298 CCAssignFnForCall(CallerCC, IsVarArg)))
2301 // The callee has to preserve all registers the caller needs to preserve.
2303 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2304 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2308 // Nothing more to check if the callee is taking no arguments.
2312 SmallVector<CCValAssign, 16> ArgLocs;
2313 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2315 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2317 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2318 // If the stack arguments for this call do not fit into our own save area then
2319 // the call cannot be made tail.
2320 // TODO: Is this really necessary?
2321 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2324 const MachineRegisterInfo &MRI = MF.getRegInfo();
2325 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2328 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2329 if (!CI->isTailCall())
2332 const Function *ParentFn = CI->getParent()->getParent();
2333 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2336 auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2337 return (Attr.getValueAsString() != "true");
2340 // The wave scratch offset register is used as the global base pointer.
2341 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2342 SmallVectorImpl<SDValue> &InVals) const {
2343 SelectionDAG &DAG = CLI.DAG;
2344 const SDLoc &DL = CLI.DL;
2345 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2346 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2347 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2348 SDValue Chain = CLI.Chain;
2349 SDValue Callee = CLI.Callee;
2350 bool &IsTailCall = CLI.IsTailCall;
2351 CallingConv::ID CallConv = CLI.CallConv;
2352 bool IsVarArg = CLI.IsVarArg;
2353 bool IsSibCall = false;
2354 bool IsThisReturn = false;
2355 MachineFunction &MF = DAG.getMachineFunction();
2358 return lowerUnhandledCall(CLI, InVals,
2359 "unsupported call to variadic function ");
2362 if (!CLI.CS.getCalledFunction()) {
2363 return lowerUnhandledCall(CLI, InVals,
2364 "unsupported indirect call to function ");
2367 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2368 return lowerUnhandledCall(CLI, InVals,
2369 "unsupported required tail call to function ");
2372 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2373 // Note the issue is with the CC of the calling function, not of the call
2375 return lowerUnhandledCall(CLI, InVals,
2376 "unsupported call from graphics shader of function ");
2379 // The first 4 bytes are reserved for the callee's emergency stack slot.
2380 const unsigned CalleeUsableStackOffset = 4;
2383 IsTailCall = isEligibleForTailCallOptimization(
2384 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2385 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2386 report_fatal_error("failed to perform tail call elimination on a call "
2387 "site marked musttail");
2390 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2392 // A sibling call is one where we're under the usual C ABI and not planning
2393 // to change that but can still do a tail call:
2394 if (!TailCallOpt && IsTailCall)
2401 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2402 // FIXME: Remove this hack for function pointer types after removing
2403 // support of old address space mapping. In the new address space
2404 // mapping the pointer in default address space is 64 bit, therefore
2405 // does not need this hack.
2406 if (Callee.getValueType() == MVT::i32) {
2407 const GlobalValue *GV = GA->getGlobal();
2408 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2409 GA->getTargetFlags());
2412 assert(Callee.getValueType() == MVT::i64);
2414 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2416 // Analyze operands of the call, assigning locations to each operand.
2417 SmallVector<CCValAssign, 16> ArgLocs;
2418 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2419 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2420 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2422 // Get a count of how many bytes are to be pushed on the stack.
2423 unsigned NumBytes = CCInfo.getNextStackOffset();
2426 // Since we're not changing the ABI to make this a tail call, the memory
2427 // operands are already available in the caller's incoming argument space.
2431 // FPDiff is the byte offset of the call's argument area from the callee's.
2432 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2433 // by this amount for a tail call. In a sibling call it must be 0 because the
2434 // caller will deallocate the entire stack and the callee still expects its
2435 // arguments to begin at SP+0. Completely unused for non-tail calls.
2437 MachineFrameInfo &MFI = MF.getFrameInfo();
2438 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2440 SDValue CallerSavedFP;
2442 // Adjust the stack pointer for the new arguments...
2443 // These operations are automatically eliminated by the prolog/epilog pass
2445 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2447 unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2449 // In the HSA case, this should be an identity copy.
2450 SDValue ScratchRSrcReg
2451 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2452 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2454 // TODO: Don't hardcode these registers and get from the callee function.
2455 SDValue ScratchWaveOffsetReg
2456 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2457 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2459 if (!Info->isEntryFunction()) {
2460 // Avoid clobbering this function's FP value. In the current convention
2461 // callee will overwrite this, so do save/restore around the call site.
2462 CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2463 Info->getFrameOffsetReg(), MVT::i32);
2467 // Stack pointer relative accesses are done by changing the offset SGPR. This
2468 // is just the VGPR offset component.
2469 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2471 SmallVector<SDValue, 8> MemOpChains;
2472 MVT PtrVT = MVT::i32;
2474 // Walk the register/memloc assignments, inserting copies/loads.
2475 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2476 ++i, ++realArgIdx) {
2477 CCValAssign &VA = ArgLocs[i];
2478 SDValue Arg = OutVals[realArgIdx];
2480 // Promote the value if needed.
2481 switch (VA.getLocInfo()) {
2482 case CCValAssign::Full:
2484 case CCValAssign::BCvt:
2485 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2487 case CCValAssign::ZExt:
2488 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2490 case CCValAssign::SExt:
2491 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2493 case CCValAssign::AExt:
2494 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2496 case CCValAssign::FPExt:
2497 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2500 llvm_unreachable("Unknown loc info!");
2503 if (VA.isRegLoc()) {
2504 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2506 assert(VA.isMemLoc());
2509 MachinePointerInfo DstInfo;
2511 unsigned LocMemOffset = VA.getLocMemOffset();
2512 int32_t Offset = LocMemOffset;
2514 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2517 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2518 unsigned OpSize = Flags.isByVal() ?
2519 Flags.getByValSize() : VA.getValVT().getStoreSize();
2521 Offset = Offset + FPDiff;
2522 int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2524 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2526 DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2528 // Make sure any stack arguments overlapping with where we're storing
2529 // are loaded before this eventual operation. Otherwise they'll be
2532 // FIXME: Why is this really necessary? This seems to just result in a
2533 // lot of code to copy the stack and write them back to the same
2534 // locations, which are supposed to be immutable?
2535 Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2538 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2541 if (Outs[i].Flags.isByVal()) {
2543 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2544 SDValue Cpy = DAG.getMemcpy(
2545 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2546 /*isVol = */ false, /*AlwaysInline = */ true,
2547 /*isTailCall = */ false, DstInfo,
2548 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2549 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2551 MemOpChains.push_back(Cpy);
2553 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2554 MemOpChains.push_back(Store);
2559 // Copy special input registers after user input arguments.
2560 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2562 if (!MemOpChains.empty())
2563 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2565 // Build a sequence of copy-to-reg nodes chained together with token chain
2566 // and flag operands which copy the outgoing args into the appropriate regs.
2568 for (auto &RegToPass : RegsToPass) {
2569 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2570 RegToPass.second, InFlag);
2571 InFlag = Chain.getValue(1);
2575 SDValue PhysReturnAddrReg;
2577 // Since the return is being combined with the call, we need to pass on the
2580 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2581 SDValue ReturnAddrReg = CreateLiveInRegister(
2582 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2584 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2586 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2587 InFlag = Chain.getValue(1);
2590 // We don't usually want to end the call-sequence here because we would tidy
2591 // the frame up *after* the call, however in the ABI-changing tail-call case
2592 // we've carefully laid out the parameters so that when sp is reset they'll be
2593 // in the correct location.
2594 if (IsTailCall && !IsSibCall) {
2595 Chain = DAG.getCALLSEQ_END(Chain,
2596 DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2597 DAG.getTargetConstant(0, DL, MVT::i32),
2599 InFlag = Chain.getValue(1);
2602 std::vector<SDValue> Ops;
2603 Ops.push_back(Chain);
2604 Ops.push_back(Callee);
2607 // Each tail call may have to adjust the stack by a different amount, so
2608 // this information must travel along with the operation for eventual
2609 // consumption by emitEpilogue.
2610 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2612 Ops.push_back(PhysReturnAddrReg);
2615 // Add argument registers to the end of the list so that they are known live
2617 for (auto &RegToPass : RegsToPass) {
2618 Ops.push_back(DAG.getRegister(RegToPass.first,
2619 RegToPass.second.getValueType()));
2622 // Add a register mask operand representing the call-preserved registers.
2624 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2625 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2626 assert(Mask && "Missing call preserved mask for calling convention");
2627 Ops.push_back(DAG.getRegisterMask(Mask));
2629 if (InFlag.getNode())
2630 Ops.push_back(InFlag);
2632 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2634 // If we're doing a tall call, use a TC_RETURN here rather than an
2635 // actual call instruction.
2637 MFI.setHasTailCall();
2638 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2641 // Returns a chain and a flag for retval copy to use.
2642 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2643 Chain = Call.getValue(0);
2644 InFlag = Call.getValue(1);
2646 if (CallerSavedFP) {
2647 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2648 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2649 InFlag = Chain.getValue(1);
2652 uint64_t CalleePopBytes = NumBytes;
2653 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2654 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2657 InFlag = Chain.getValue(1);
2659 // Handle result values, copying them out of physregs into vregs that we
2661 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2662 InVals, IsThisReturn,
2663 IsThisReturn ? OutVals[0] : SDValue());
2666 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2667 SelectionDAG &DAG) const {
2668 unsigned Reg = StringSwitch<unsigned>(RegName)
2669 .Case("m0", AMDGPU::M0)
2670 .Case("exec", AMDGPU::EXEC)
2671 .Case("exec_lo", AMDGPU::EXEC_LO)
2672 .Case("exec_hi", AMDGPU::EXEC_HI)
2673 .Case("flat_scratch", AMDGPU::FLAT_SCR)
2674 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2675 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2676 .Default(AMDGPU::NoRegister);
2678 if (Reg == AMDGPU::NoRegister) {
2679 report_fatal_error(Twine("invalid register name \""
2680 + StringRef(RegName) + "\"."));
2684 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2685 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2686 report_fatal_error(Twine("invalid register \""
2687 + StringRef(RegName) + "\" for subtarget."));
2692 case AMDGPU::EXEC_LO:
2693 case AMDGPU::EXEC_HI:
2694 case AMDGPU::FLAT_SCR_LO:
2695 case AMDGPU::FLAT_SCR_HI:
2696 if (VT.getSizeInBits() == 32)
2700 case AMDGPU::FLAT_SCR:
2701 if (VT.getSizeInBits() == 64)
2705 llvm_unreachable("missing register type checking");
2708 report_fatal_error(Twine("invalid type for register \""
2709 + StringRef(RegName) + "\"."));
2712 // If kill is not the last instruction, split the block so kill is always a
2713 // proper terminator.
2714 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2715 MachineBasicBlock *BB) const {
2716 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2718 MachineBasicBlock::iterator SplitPoint(&MI);
2721 if (SplitPoint == BB->end()) {
2722 // Don't bother with a new block.
2723 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2727 MachineFunction *MF = BB->getParent();
2728 MachineBasicBlock *SplitBB
2729 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2731 MF->insert(++MachineFunction::iterator(BB), SplitBB);
2732 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2734 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2735 BB->addSuccessor(SplitBB);
2737 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2741 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2742 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2743 // will only do one iteration. In the worst case, this will loop 64 times.
2745 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2746 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2747 const SIInstrInfo *TII,
2748 MachineRegisterInfo &MRI,
2749 MachineBasicBlock &OrigBB,
2750 MachineBasicBlock &LoopBB,
2752 const MachineOperand &IdxReg,
2756 unsigned InitSaveExecReg,
2759 bool IsIndirectSrc) {
2760 MachineBasicBlock::iterator I = LoopBB.begin();
2762 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2763 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2764 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2765 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2767 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2773 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2774 .addReg(InitSaveExecReg)
2779 // Read the next variant <- also loop target.
2780 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2781 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2783 // Compare the just read M0 value to all possible Idx values.
2784 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2785 .addReg(CurrentIdxReg)
2786 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2788 // Update EXEC, save the original EXEC value to VCC.
2789 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2790 .addReg(CondReg, RegState::Kill);
2792 MRI.setSimpleHint(NewExec, CondReg);
2794 if (UseGPRIdxMode) {
2797 IdxReg = CurrentIdxReg;
2799 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2800 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2801 .addReg(CurrentIdxReg, RegState::Kill)
2804 unsigned IdxMode = IsIndirectSrc ?
2805 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2806 MachineInstr *SetOn =
2807 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2808 .addReg(IdxReg, RegState::Kill)
2810 SetOn->getOperand(3).setIsUndef();
2812 // Move index from VCC into M0
2814 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2815 .addReg(CurrentIdxReg, RegState::Kill);
2817 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2818 .addReg(CurrentIdxReg, RegState::Kill)
2823 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2824 MachineInstr *InsertPt =
2825 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2826 .addReg(AMDGPU::EXEC)
2829 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2832 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2833 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2836 return InsertPt->getIterator();
2839 // This has slightly sub-optimal regalloc when the source vector is killed by
2840 // the read. The register allocator does not understand that the kill is
2841 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2842 // subregister from it, using 1 more VGPR than necessary. This was saved when
2843 // this was expanded after register allocation.
2844 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2845 MachineBasicBlock &MBB,
2847 unsigned InitResultReg,
2851 bool IsIndirectSrc) {
2852 MachineFunction *MF = MBB.getParent();
2853 MachineRegisterInfo &MRI = MF->getRegInfo();
2854 const DebugLoc &DL = MI.getDebugLoc();
2855 MachineBasicBlock::iterator I(&MI);
2857 unsigned DstReg = MI.getOperand(0).getReg();
2858 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2859 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2861 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2863 // Save the EXEC mask
2864 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2865 .addReg(AMDGPU::EXEC);
2867 // To insert the loop we need to split the block. Move everything after this
2868 // point to a new block, and insert a new empty block between the two.
2869 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2870 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2871 MachineFunction::iterator MBBI(MBB);
2874 MF->insert(MBBI, LoopBB);
2875 MF->insert(MBBI, RemainderBB);
2877 LoopBB->addSuccessor(LoopBB);
2878 LoopBB->addSuccessor(RemainderBB);
2880 // Move the rest of the block into a new block.
2881 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2882 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2884 MBB.addSuccessor(LoopBB);
2886 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2888 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2889 InitResultReg, DstReg, PhiReg, TmpExec,
2890 Offset, UseGPRIdxMode, IsIndirectSrc);
2892 MachineBasicBlock::iterator First = RemainderBB->begin();
2893 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2899 // Returns subreg index, offset
2900 static std::pair<unsigned, int>
2901 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2902 const TargetRegisterClass *SuperRC,
2905 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2907 // Skip out of bounds offsets, or else we would end up using an undefined
2909 if (Offset >= NumElts || Offset < 0)
2910 return std::make_pair(AMDGPU::sub0, Offset);
2912 return std::make_pair(AMDGPU::sub0 + Offset, 0);
2915 // Return true if the index is an SGPR and was set.
2916 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2917 MachineRegisterInfo &MRI,
2921 bool IsIndirectSrc) {
2922 MachineBasicBlock *MBB = MI.getParent();
2923 const DebugLoc &DL = MI.getDebugLoc();
2924 MachineBasicBlock::iterator I(&MI);
2926 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2927 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2929 assert(Idx->getReg() != AMDGPU::NoRegister);
2931 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2934 if (UseGPRIdxMode) {
2935 unsigned IdxMode = IsIndirectSrc ?
2936 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2938 MachineInstr *SetOn =
2939 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2943 SetOn->getOperand(3).setIsUndef();
2945 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2946 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2949 MachineInstr *SetOn =
2950 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2951 .addReg(Tmp, RegState::Kill)
2954 SetOn->getOperand(3).setIsUndef();
2961 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2964 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2972 // Control flow needs to be inserted if indexing with a VGPR.
2973 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2974 MachineBasicBlock &MBB,
2975 const GCNSubtarget &ST) {
2976 const SIInstrInfo *TII = ST.getInstrInfo();
2977 const SIRegisterInfo &TRI = TII->getRegisterInfo();
2978 MachineFunction *MF = MBB.getParent();
2979 MachineRegisterInfo &MRI = MF->getRegInfo();
2981 unsigned Dst = MI.getOperand(0).getReg();
2982 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2983 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2985 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2988 std::tie(SubReg, Offset)
2989 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2991 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2993 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2994 MachineBasicBlock::iterator I(&MI);
2995 const DebugLoc &DL = MI.getDebugLoc();
2997 if (UseGPRIdxMode) {
2998 // TODO: Look at the uses to avoid the copy. This may require rescheduling
2999 // to avoid interfering with other uses, so probably requires a new
3000 // optimization pass.
3001 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3002 .addReg(SrcReg, RegState::Undef, SubReg)
3003 .addReg(SrcReg, RegState::Implicit)
3004 .addReg(AMDGPU::M0, RegState::Implicit);
3005 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3007 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3008 .addReg(SrcReg, RegState::Undef, SubReg)
3009 .addReg(SrcReg, RegState::Implicit);
3012 MI.eraseFromParent();
3017 const DebugLoc &DL = MI.getDebugLoc();
3018 MachineBasicBlock::iterator I(&MI);
3020 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3021 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3023 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3025 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3026 Offset, UseGPRIdxMode, true);
3027 MachineBasicBlock *LoopBB = InsPt->getParent();
3029 if (UseGPRIdxMode) {
3030 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3031 .addReg(SrcReg, RegState::Undef, SubReg)
3032 .addReg(SrcReg, RegState::Implicit)
3033 .addReg(AMDGPU::M0, RegState::Implicit);
3034 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3036 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3037 .addReg(SrcReg, RegState::Undef, SubReg)
3038 .addReg(SrcReg, RegState::Implicit);
3041 MI.eraseFromParent();
3046 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3047 const TargetRegisterClass *VecRC) {
3048 switch (TRI.getRegSizeInBits(*VecRC)) {
3050 return AMDGPU::V_MOVRELD_B32_V1;
3052 return AMDGPU::V_MOVRELD_B32_V2;
3053 case 128: // 16 bytes
3054 return AMDGPU::V_MOVRELD_B32_V4;
3055 case 256: // 32 bytes
3056 return AMDGPU::V_MOVRELD_B32_V8;
3057 case 512: // 64 bytes
3058 return AMDGPU::V_MOVRELD_B32_V16;
3060 llvm_unreachable("unsupported size for MOVRELD pseudos");
3064 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3065 MachineBasicBlock &MBB,
3066 const GCNSubtarget &ST) {
3067 const SIInstrInfo *TII = ST.getInstrInfo();
3068 const SIRegisterInfo &TRI = TII->getRegisterInfo();
3069 MachineFunction *MF = MBB.getParent();
3070 MachineRegisterInfo &MRI = MF->getRegInfo();
3072 unsigned Dst = MI.getOperand(0).getReg();
3073 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3074 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3075 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3076 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3077 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3079 // This can be an immediate, but will be folded later.
3080 assert(Val->getReg());
3083 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3086 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3088 if (Idx->getReg() == AMDGPU::NoRegister) {
3089 MachineBasicBlock::iterator I(&MI);
3090 const DebugLoc &DL = MI.getDebugLoc();
3092 assert(Offset == 0);
3094 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3099 MI.eraseFromParent();
3103 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3104 MachineBasicBlock::iterator I(&MI);
3105 const DebugLoc &DL = MI.getDebugLoc();
3107 if (UseGPRIdxMode) {
3108 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3109 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3111 .addReg(Dst, RegState::ImplicitDefine)
3112 .addReg(SrcVec->getReg(), RegState::Implicit)
3113 .addReg(AMDGPU::M0, RegState::Implicit);
3115 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3117 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3119 BuildMI(MBB, I, DL, MovRelDesc)
3120 .addReg(Dst, RegState::Define)
3121 .addReg(SrcVec->getReg())
3123 .addImm(SubReg - AMDGPU::sub0);
3126 MI.eraseFromParent();
3131 MRI.clearKillFlags(Val->getReg());
3133 const DebugLoc &DL = MI.getDebugLoc();
3135 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3137 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3138 Offset, UseGPRIdxMode, false);
3139 MachineBasicBlock *LoopBB = InsPt->getParent();
3141 if (UseGPRIdxMode) {
3142 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3143 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3145 .addReg(Dst, RegState::ImplicitDefine)
3146 .addReg(PhiReg, RegState::Implicit)
3147 .addReg(AMDGPU::M0, RegState::Implicit);
3148 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3150 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3152 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3153 .addReg(Dst, RegState::Define)
3156 .addImm(SubReg - AMDGPU::sub0);
3159 MI.eraseFromParent();
3164 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3165 MachineInstr &MI, MachineBasicBlock *BB) const {
3167 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3168 MachineFunction *MF = BB->getParent();
3169 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3171 if (TII->isMIMG(MI)) {
3172 if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3173 report_fatal_error("missing mem operand from MIMG instruction");
3175 // Add a memoperand for mimg instructions so that they aren't assumed to
3176 // be ordered memory instuctions.
3181 switch (MI.getOpcode()) {
3182 case AMDGPU::S_ADD_U64_PSEUDO:
3183 case AMDGPU::S_SUB_U64_PSEUDO: {
3184 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3185 const DebugLoc &DL = MI.getDebugLoc();
3187 MachineOperand &Dest = MI.getOperand(0);
3188 MachineOperand &Src0 = MI.getOperand(1);
3189 MachineOperand &Src1 = MI.getOperand(2);
3191 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3192 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3194 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3195 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3196 &AMDGPU::SReg_32_XM0RegClass);
3197 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3198 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3199 &AMDGPU::SReg_32_XM0RegClass);
3201 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3202 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3203 &AMDGPU::SReg_32_XM0RegClass);
3204 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3205 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3206 &AMDGPU::SReg_32_XM0RegClass);
3208 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3210 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3211 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3212 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3215 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3218 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3220 .addImm(AMDGPU::sub0)
3222 .addImm(AMDGPU::sub1);
3223 MI.eraseFromParent();
3226 case AMDGPU::SI_INIT_M0: {
3227 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3228 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3229 .add(MI.getOperand(0));
3230 MI.eraseFromParent();
3233 case AMDGPU::SI_INIT_EXEC:
3234 // This should be before all vector instructions.
3235 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3237 .addImm(MI.getOperand(0).getImm());
3238 MI.eraseFromParent();
3241 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3242 // Extract the thread count from an SGPR input and set EXEC accordingly.
3243 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3245 // S_BFE_U32 count, input, {shift, 7}
3246 // S_BFM_B64 exec, count, 0
3247 // S_CMP_EQ_U32 count, 64
3248 // S_CMOV_B64 exec, -1
3249 MachineInstr *FirstMI = &*BB->begin();
3250 MachineRegisterInfo &MRI = MF->getRegInfo();
3251 unsigned InputReg = MI.getOperand(0).getReg();
3252 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3255 // Move the COPY of the input reg to the beginning, so that we can use it.
3256 for (auto I = BB->begin(); I != &MI; I++) {
3257 if (I->getOpcode() != TargetOpcode::COPY ||
3258 I->getOperand(0).getReg() != InputReg)
3262 FirstMI = &*++BB->begin();
3264 I->removeFromParent();
3265 BB->insert(FirstMI, &*I);
3273 // This should be before all vector instructions.
3274 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3276 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3277 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3281 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3282 .addReg(CountReg, RegState::Kill)
3284 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3287 MI.eraseFromParent();
3291 case AMDGPU::GET_GROUPSTATICSIZE: {
3292 DebugLoc DL = MI.getDebugLoc();
3293 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3294 .add(MI.getOperand(0))
3295 .addImm(MFI->getLDSSize());
3296 MI.eraseFromParent();
3299 case AMDGPU::SI_INDIRECT_SRC_V1:
3300 case AMDGPU::SI_INDIRECT_SRC_V2:
3301 case AMDGPU::SI_INDIRECT_SRC_V4:
3302 case AMDGPU::SI_INDIRECT_SRC_V8:
3303 case AMDGPU::SI_INDIRECT_SRC_V16:
3304 return emitIndirectSrc(MI, *BB, *getSubtarget());
3305 case AMDGPU::SI_INDIRECT_DST_V1:
3306 case AMDGPU::SI_INDIRECT_DST_V2:
3307 case AMDGPU::SI_INDIRECT_DST_V4:
3308 case AMDGPU::SI_INDIRECT_DST_V8:
3309 case AMDGPU::SI_INDIRECT_DST_V16:
3310 return emitIndirectDst(MI, *BB, *getSubtarget());
3311 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3312 case AMDGPU::SI_KILL_I1_PSEUDO:
3313 return splitKillBlock(MI, BB);
3314 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3315 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3317 unsigned Dst = MI.getOperand(0).getReg();
3318 unsigned Src0 = MI.getOperand(1).getReg();
3319 unsigned Src1 = MI.getOperand(2).getReg();
3320 const DebugLoc &DL = MI.getDebugLoc();
3321 unsigned SrcCond = MI.getOperand(3).getReg();
3323 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3324 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3325 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3327 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3329 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3330 .addReg(Src0, 0, AMDGPU::sub0)
3331 .addReg(Src1, 0, AMDGPU::sub0)
3332 .addReg(SrcCondCopy);
3333 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3334 .addReg(Src0, 0, AMDGPU::sub1)
3335 .addReg(Src1, 0, AMDGPU::sub1)
3336 .addReg(SrcCondCopy);
3338 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3340 .addImm(AMDGPU::sub0)
3342 .addImm(AMDGPU::sub1);
3343 MI.eraseFromParent();
3346 case AMDGPU::SI_BR_UNDEF: {
3347 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3348 const DebugLoc &DL = MI.getDebugLoc();
3349 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3350 .add(MI.getOperand(0));
3351 Br->getOperand(1).setIsUndef(true); // read undef SCC
3352 MI.eraseFromParent();
3355 case AMDGPU::ADJCALLSTACKUP:
3356 case AMDGPU::ADJCALLSTACKDOWN: {
3357 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3358 MachineInstrBuilder MIB(*MF, &MI);
3360 // Add an implicit use of the frame offset reg to prevent the restore copy
3361 // inserted after the call from being reorderd after stack operations in the
3362 // the caller's frame.
3363 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3364 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3365 .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3368 case AMDGPU::SI_CALL_ISEL:
3369 case AMDGPU::SI_TCRETURN_ISEL: {
3370 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3371 const DebugLoc &DL = MI.getDebugLoc();
3372 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3374 MachineRegisterInfo &MRI = MF->getRegInfo();
3375 unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3376 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3377 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3379 const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3381 MachineInstrBuilder MIB;
3382 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3383 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3384 .add(MI.getOperand(0))
3385 .addGlobalAddress(G);
3387 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3388 .add(MI.getOperand(0))
3389 .addGlobalAddress(G);
3391 // There is an additional imm operand for tcreturn, but it should be in the
3392 // right place already.
3395 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3396 MIB.add(MI.getOperand(I));
3398 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3399 MI.eraseFromParent();
3403 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3407 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3408 return isTypeLegal(VT.getScalarType());
3411 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3412 // This currently forces unfolding various combinations of fsub into fma with
3413 // free fneg'd operands. As long as we have fast FMA (controlled by
3414 // isFMAFasterThanFMulAndFAdd), we should perform these.
3416 // When fma is quarter rate, for f64 where add / sub are at best half rate,
3417 // most of these combines appear to be cycle neutral but save on instruction
3418 // count / code size.
3422 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3424 if (!VT.isVector()) {
3427 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3430 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3431 // TODO: Should i16 be used always if legal? For now it would force VALU
3433 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3436 // Answering this is somewhat tricky and depends on the specific device which
3437 // have different rates for fma or all f64 operations.
3439 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3440 // regardless of which device (although the number of cycles differs between
3441 // devices), so it is always profitable for f64.
3443 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3444 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3445 // which we can always do even without fused FP ops since it returns the same
3446 // result as the separate operations and since it is always full
3447 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3448 // however does not support denormals, so we do report fma as faster if we have
3449 // a fast fma device and require denormals.
3451 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3452 VT = VT.getScalarType();
3454 switch (VT.getSimpleVT().SimpleTy) {
3456 // This is as fast on some subtargets. However, we always have full rate f32
3457 // mad available which returns the same result as the separate operations
3458 // which we should prefer over fma. We can't use this if we want to support
3459 // denormals, so only report this in these cases.
3460 if (Subtarget->hasFP32Denormals())
3461 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3463 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3464 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3469 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3477 //===----------------------------------------------------------------------===//
3478 // Custom DAG Lowering Operations
3479 //===----------------------------------------------------------------------===//
3481 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3482 // wider vector type is legal.
3483 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3484 SelectionDAG &DAG) const {
3485 unsigned Opc = Op.getOpcode();
3486 EVT VT = Op.getValueType();
3487 assert(VT == MVT::v4f16);
3490 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3493 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3495 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3498 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3501 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3502 // wider vector type is legal.
3503 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3504 SelectionDAG &DAG) const {
3505 unsigned Opc = Op.getOpcode();
3506 EVT VT = Op.getValueType();
3507 assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3510 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3512 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3516 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3518 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3521 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3524 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3525 switch (Op.getOpcode()) {
3526 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3527 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3529 SDValue Result = LowerLOAD(Op, DAG);
3530 assert((!Result.getNode() ||
3531 Result.getNode()->getNumValues() == 2) &&
3532 "Load should return a value and a chain");
3538 return LowerTrig(Op, DAG);
3539 case ISD::SELECT: return LowerSELECT(Op, DAG);
3540 case ISD::FDIV: return LowerFDIV(Op, DAG);
3541 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3542 case ISD::STORE: return LowerSTORE(Op, DAG);
3543 case ISD::GlobalAddress: {
3544 MachineFunction &MF = DAG.getMachineFunction();
3545 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3546 return LowerGlobalAddress(MFI, Op, DAG);
3548 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3549 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3550 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3551 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3552 case ISD::INSERT_VECTOR_ELT:
3553 return lowerINSERT_VECTOR_ELT(Op, DAG);
3554 case ISD::EXTRACT_VECTOR_ELT:
3555 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3556 case ISD::BUILD_VECTOR:
3557 return lowerBUILD_VECTOR(Op, DAG);
3559 return lowerFP_ROUND(Op, DAG);
3561 return lowerTRAP(Op, DAG);
3562 case ISD::DEBUGTRAP:
3563 return lowerDEBUGTRAP(Op, DAG);
3566 return splitUnaryVectorOp(Op, DAG);
3581 return splitBinaryVectorOp(Op, DAG);
3586 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3588 SelectionDAG &DAG, bool Unpacked) {
3589 if (!LoadVT.isVector())
3592 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3593 // Truncate to v2i16/v4i16.
3594 EVT IntLoadVT = LoadVT.changeTypeToInteger();
3596 // Workaround legalizer not scalarizing truncate after vector op
3597 // legalization byt not creating intermediate vector trunc.
3598 SmallVector<SDValue, 4> Elts;
3599 DAG.ExtractVectorElements(Result, Elts);
3600 for (SDValue &Elt : Elts)
3601 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3603 Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3605 // Bitcast to original type (v2f16/v4f16).
3606 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3609 // Cast back to the original packed type.
3610 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3613 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3616 bool IsIntrinsic) const {
3618 SmallVector<SDValue, 10> Ops;
3619 Ops.reserve(M->getNumOperands());
3621 Ops.push_back(M->getOperand(0));
3623 Ops.push_back(DAG.getConstant(Opcode, DL, MVT::i32));
3625 // Skip 1, as it is the intrinsic ID.
3626 for (unsigned I = 2, E = M->getNumOperands(); I != E; ++I)
3627 Ops.push_back(M->getOperand(I));
3629 bool Unpacked = Subtarget->hasUnpackedD16VMem();
3630 EVT LoadVT = M->getValueType(0);
3632 EVT EquivLoadVT = LoadVT;
3633 if (Unpacked && LoadVT.isVector()) {
3634 EquivLoadVT = LoadVT.isVector() ?
3635 EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3636 LoadVT.getVectorNumElements()) : LoadVT;
3639 // Change from v4f16/v2f16 to EquivLoadVT.
3640 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3643 = DAG.getMemIntrinsicNode(
3644 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3645 VTList, Ops, M->getMemoryVT(),
3646 M->getMemOperand());
3647 if (!Unpacked) // Just adjusted the opcode.
3650 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3652 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3655 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3656 SmallVectorImpl<SDValue> &Results,
3657 SelectionDAG &DAG) const {
3658 switch (N->getOpcode()) {
3659 case ISD::INSERT_VECTOR_ELT: {
3660 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3661 Results.push_back(Res);
3664 case ISD::EXTRACT_VECTOR_ELT: {
3665 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3666 Results.push_back(Res);
3669 case ISD::INTRINSIC_WO_CHAIN: {
3670 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3672 case Intrinsic::amdgcn_cvt_pkrtz: {
3673 SDValue Src0 = N->getOperand(1);
3674 SDValue Src1 = N->getOperand(2);
3676 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3678 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3681 case Intrinsic::amdgcn_cvt_pknorm_i16:
3682 case Intrinsic::amdgcn_cvt_pknorm_u16:
3683 case Intrinsic::amdgcn_cvt_pk_i16:
3684 case Intrinsic::amdgcn_cvt_pk_u16: {
3685 SDValue Src0 = N->getOperand(1);
3686 SDValue Src1 = N->getOperand(2);
3690 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3691 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3692 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3693 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3694 else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3695 Opcode = AMDGPUISD::CVT_PK_I16_I32;
3697 Opcode = AMDGPUISD::CVT_PK_U16_U32;
3699 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3700 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3706 case ISD::INTRINSIC_W_CHAIN: {
3707 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3708 Results.push_back(Res);
3709 Results.push_back(Res.getValue(1));
3717 EVT VT = N->getValueType(0);
3718 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3719 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3720 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3722 EVT SelectVT = NewVT;
3723 if (NewVT.bitsLT(MVT::i32)) {
3724 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3725 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3726 SelectVT = MVT::i32;
3729 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3730 N->getOperand(0), LHS, RHS);
3732 if (NewVT != SelectVT)
3733 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3734 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3738 if (N->getValueType(0) != MVT::v2f16)
3742 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3744 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3746 DAG.getConstant(0x80008000, SL, MVT::i32));
3747 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3751 if (N->getValueType(0) != MVT::v2f16)
3755 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3757 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3759 DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3760 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3768 /// Helper function for LowerBRCOND
3769 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3771 SDNode *Parent = Value.getNode();
3772 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3775 if (I.getUse().get() != Value)
3778 if (I->getOpcode() == Opcode)
3784 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3785 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3786 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3787 case Intrinsic::amdgcn_if:
3788 return AMDGPUISD::IF;
3789 case Intrinsic::amdgcn_else:
3790 return AMDGPUISD::ELSE;
3791 case Intrinsic::amdgcn_loop:
3792 return AMDGPUISD::LOOP;
3793 case Intrinsic::amdgcn_end_cf:
3794 llvm_unreachable("should not occur");
3800 // break, if_break, else_break are all only used as inputs to loop, not
3801 // directly as branch conditions.
3805 void SITargetLowering::createDebuggerPrologueStackObjects(
3806 MachineFunction &MF) const {
3807 // Create stack objects that are used for emitting debugger prologue.
3809 // Debugger prologue writes work group IDs and work item IDs to scratch memory
3810 // at fixed location in the following format:
3811 // offset 0: work group ID x
3812 // offset 4: work group ID y
3813 // offset 8: work group ID z
3814 // offset 16: work item ID x
3815 // offset 20: work item ID y
3816 // offset 24: work item ID z
3817 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3820 // For each dimension:
3821 for (unsigned i = 0; i < 3; ++i) {
3822 // Create fixed stack object for work group ID.
3823 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3824 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3825 // Create fixed stack object for work item ID.
3826 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3827 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3831 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3832 const Triple &TT = getTargetMachine().getTargetTriple();
3833 return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3834 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3835 AMDGPU::shouldEmitConstantsToTextSection(TT);
3838 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3839 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3840 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3841 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3842 !shouldEmitFixup(GV) &&
3843 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3846 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3847 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3850 /// This transforms the control flow intrinsics to get the branch destination as
3851 /// last parameter, also switches branch target with BR if the need arise
3852 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3853 SelectionDAG &DAG) const {
3856 SDNode *Intr = BRCOND.getOperand(1).getNode();
3857 SDValue Target = BRCOND.getOperand(2);
3858 SDNode *BR = nullptr;
3859 SDNode *SetCC = nullptr;
3861 if (Intr->getOpcode() == ISD::SETCC) {
3862 // As long as we negate the condition everything is fine
3864 Intr = SetCC->getOperand(0).getNode();
3867 // Get the target from BR if we don't negate the condition
3868 BR = findUser(BRCOND, ISD::BR);
3869 Target = BR->getOperand(1);
3872 // FIXME: This changes the types of the intrinsics instead of introducing new
3873 // nodes with the correct types.
3874 // e.g. llvm.amdgcn.loop
3876 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3877 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3879 unsigned CFNode = isCFIntrinsic(Intr);
3881 // This is a uniform branch so we don't need to legalize.
3885 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3886 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3889 (SetCC->getConstantOperandVal(1) == 1 &&
3890 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3893 // operands of the new intrinsic call
3894 SmallVector<SDValue, 4> Ops;
3896 Ops.push_back(BRCOND.getOperand(0));
3898 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
3899 Ops.push_back(Target);
3901 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3903 // build the new intrinsic call
3904 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3909 BRCOND.getOperand(0)
3912 Result = DAG.getMergeValues(Ops, DL).getNode();
3916 // Give the branch instruction our target
3919 BRCOND.getOperand(2)
3921 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3922 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3923 BR = NewBR.getNode();
3926 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3928 // Copy the intrinsic results to registers
3929 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3930 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3934 Chain = DAG.getCopyToReg(
3936 CopyToReg->getOperand(1),
3937 SDValue(Result, i - 1),
3940 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3943 // Remove the old intrinsic from the chain
3944 DAG.ReplaceAllUsesOfValueWith(
3945 SDValue(Intr, Intr->getNumValues() - 1),
3946 Intr->getOperand(0));
3951 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3955 return Op.getValueType().bitsLE(VT) ?
3956 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3957 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3960 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3961 assert(Op.getValueType() == MVT::f16 &&
3962 "Do not know how to custom lower FP_ROUND for non-f16 type");
3964 SDValue Src = Op.getOperand(0);
3965 EVT SrcVT = Src.getValueType();
3966 if (SrcVT != MVT::f64)
3971 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3972 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3973 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3976 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3978 SDValue Chain = Op.getOperand(0);
3980 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
3981 !Subtarget->isTrapHandlerEnabled())
3982 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3984 MachineFunction &MF = DAG.getMachineFunction();
3985 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3986 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3987 assert(UserSGPR != AMDGPU::NoRegister);
3988 SDValue QueuePtr = CreateLiveInRegister(
3989 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3990 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3991 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3992 QueuePtr, SDValue());
3995 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
3999 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4002 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4004 SDValue Chain = Op.getOperand(0);
4005 MachineFunction &MF = DAG.getMachineFunction();
4007 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4008 !Subtarget->isTrapHandlerEnabled()) {
4009 DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4010 "debugtrap handler not supported",
4013 LLVMContext &Ctx = MF.getFunction().getContext();
4014 Ctx.diagnose(NoTrap);
4020 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4022 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4025 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4026 SelectionDAG &DAG) const {
4027 // FIXME: Use inline constants (src_{shared, private}_base) instead.
4028 if (Subtarget->hasApertureRegs()) {
4029 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
4030 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4031 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4032 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
4033 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4034 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4036 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4037 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4038 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4040 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4041 SDValue ApertureReg = SDValue(
4042 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4043 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4044 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4047 MachineFunction &MF = DAG.getMachineFunction();
4048 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4049 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4050 assert(UserSGPR != AMDGPU::NoRegister);
4052 SDValue QueuePtr = CreateLiveInRegister(
4053 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4055 // Offset into amd_queue_t for group_segment_aperture_base_hi /
4056 // private_segment_aperture_base_hi.
4057 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
4059 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4061 // TODO: Use custom target PseudoSourceValue.
4062 // TODO: We should use the value from the IR intrinsic call, but it might not
4063 // be available and how do we get it?
4064 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4065 AMDGPUASI.CONSTANT_ADDRESS));
4067 MachinePointerInfo PtrInfo(V, StructOffset);
4068 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4069 MinAlign(64, StructOffset),
4070 MachineMemOperand::MODereferenceable |
4071 MachineMemOperand::MOInvariant);
4074 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4075 SelectionDAG &DAG) const {
4077 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4079 SDValue Src = ASC->getOperand(0);
4080 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4082 const AMDGPUTargetMachine &TM =
4083 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4085 // flat -> local/private
4086 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4087 unsigned DestAS = ASC->getDestAddressSpace();
4089 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4090 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4091 unsigned NullVal = TM.getNullPointerValue(DestAS);
4092 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4093 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4094 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4096 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4097 NonNull, Ptr, SegmentNullPtr);
4101 // local/private -> flat
4102 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4103 unsigned SrcAS = ASC->getSrcAddressSpace();
4105 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4106 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4107 unsigned NullVal = TM.getNullPointerValue(SrcAS);
4108 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4111 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4113 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4115 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4117 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4118 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4123 // global <-> flat are no-ops and never emitted.
4125 const MachineFunction &MF = DAG.getMachineFunction();
4126 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4127 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4128 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4130 return DAG.getUNDEF(ASC->getValueType(0));
4133 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4134 SelectionDAG &DAG) const {
4135 SDValue Vec = Op.getOperand(0);
4136 SDValue InsVal = Op.getOperand(1);
4137 SDValue Idx = Op.getOperand(2);
4138 EVT VecVT = Vec.getValueType();
4139 EVT EltVT = VecVT.getVectorElementType();
4140 unsigned VecSize = VecVT.getSizeInBits();
4141 unsigned EltSize = EltVT.getSizeInBits();
4144 assert(VecSize <= 64);
4146 unsigned NumElts = VecVT.getVectorNumElements();
4148 auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4150 if (NumElts == 4 && EltSize == 16 && KIdx) {
4151 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4153 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4154 DAG.getConstant(0, SL, MVT::i32));
4155 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4156 DAG.getConstant(1, SL, MVT::i32));
4158 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4159 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4161 unsigned Idx = KIdx->getZExtValue();
4162 bool InsertLo = Idx < 2;
4163 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4164 InsertLo ? LoVec : HiVec,
4165 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4166 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4168 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4170 SDValue Concat = InsertLo ?
4171 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4172 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4174 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4177 if (isa<ConstantSDNode>(Idx))
4180 MVT IntVT = MVT::getIntegerVT(VecSize);
4182 // Avoid stack access for dynamic indexing.
4183 SDValue Val = InsVal;
4184 if (InsVal.getValueType() == MVT::f16)
4185 Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4187 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4188 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4190 assert(isPowerOf2_32(EltSize));
4191 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4193 // Convert vector index to bit-index.
4194 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4196 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4197 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4198 DAG.getConstant(0xffff, SL, IntVT),
4201 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4202 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4203 DAG.getNOT(SL, BFM, IntVT), BCVec);
4205 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4206 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4209 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4210 SelectionDAG &DAG) const {
4213 EVT ResultVT = Op.getValueType();
4214 SDValue Vec = Op.getOperand(0);
4215 SDValue Idx = Op.getOperand(1);
4216 EVT VecVT = Vec.getValueType();
4217 unsigned VecSize = VecVT.getSizeInBits();
4218 EVT EltVT = VecVT.getVectorElementType();
4219 assert(VecSize <= 64);
4221 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4223 // Make sure we do any optimizations that will make it easier to fold
4224 // source modifiers before obscuring it with bit operations.
4226 // XXX - Why doesn't this get called when vector_shuffle is expanded?
4227 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4230 unsigned EltSize = EltVT.getSizeInBits();
4231 assert(isPowerOf2_32(EltSize));
4233 MVT IntVT = MVT::getIntegerVT(VecSize);
4234 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4236 // Convert vector index to bit-index (* EltSize)
4237 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4239 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4240 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4242 if (ResultVT == MVT::f16) {
4243 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4244 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4247 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4250 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4251 SelectionDAG &DAG) const {
4253 EVT VT = Op.getValueType();
4255 if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4256 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4258 // Turn into pair of packed build_vectors.
4259 // TODO: Special case for constants that can be materialized with s_mov_b64.
4260 SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4261 { Op.getOperand(0), Op.getOperand(1) });
4262 SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4263 { Op.getOperand(2), Op.getOperand(3) });
4265 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4266 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4268 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4269 return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4272 assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4274 SDValue Lo = Op.getOperand(0);
4275 SDValue Hi = Op.getOperand(1);
4277 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4278 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4280 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4281 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4283 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4284 DAG.getConstant(16, SL, MVT::i32));
4286 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4288 return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4292 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4293 // We can fold offsets for anything that doesn't require a GOT relocation.
4294 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4295 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4296 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4297 !shouldEmitGOTReloc(GA->getGlobal());
4301 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4302 const SDLoc &DL, unsigned Offset, EVT PtrVT,
4303 unsigned GAFlags = SIInstrInfo::MO_NONE) {
4304 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4305 // lowered to the following code sequence:
4307 // For constant address space:
4308 // s_getpc_b64 s[0:1]
4309 // s_add_u32 s0, s0, $symbol
4310 // s_addc_u32 s1, s1, 0
4312 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4313 // a fixup or relocation is emitted to replace $symbol with a literal
4314 // constant, which is a pc-relative offset from the encoding of the $symbol
4315 // operand to the global variable.
4317 // For global address space:
4318 // s_getpc_b64 s[0:1]
4319 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4320 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4322 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
4323 // fixups or relocations are emitted to replace $symbol@*@lo and
4324 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4325 // which is a 64-bit pc-relative offset from the encoding of the $symbol
4326 // operand to the global variable.
4328 // What we want here is an offset from the value returned by s_getpc
4329 // (which is the address of the s_add_u32 instruction) to the global
4330 // variable, but since the encoding of $symbol starts 4 bytes after the start
4331 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4332 // small. This requires us to add 4 to the global variable offset in order to
4333 // compute the correct address.
4334 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4336 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4337 GAFlags == SIInstrInfo::MO_NONE ?
4338 GAFlags : GAFlags + 1);
4339 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4342 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4344 SelectionDAG &DAG) const {
4345 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4346 const GlobalValue *GV = GSD->getGlobal();
4348 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4349 GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4350 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4351 // FIXME: It isn't correct to rely on the type of the pointer. This should
4352 // be removed when address space 0 is 64-bit.
4353 !GV->getType()->getElementType()->isFunctionTy())
4354 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4357 EVT PtrVT = Op.getValueType();
4359 if (shouldEmitFixup(GV))
4360 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4361 else if (shouldEmitPCReloc(GV))
4362 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4363 SIInstrInfo::MO_REL32);
4365 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4366 SIInstrInfo::MO_GOTPCREL32);
4368 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4369 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4370 const DataLayout &DataLayout = DAG.getDataLayout();
4371 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4372 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4373 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4375 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4376 MachineMemOperand::MODereferenceable |
4377 MachineMemOperand::MOInvariant);
4380 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4381 const SDLoc &DL, SDValue V) const {
4382 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4383 // the destination register.
4385 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4386 // so we will end up with redundant moves to m0.
4388 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4390 // A Null SDValue creates a glue result.
4391 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4393 return SDValue(M0, 0);
4396 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4399 unsigned Offset) const {
4401 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4402 DAG.getEntryNode(), Offset, 4, false);
4403 // The local size values will have the hi 16-bits as zero.
4404 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4405 DAG.getValueType(VT));
4408 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4410 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4411 "non-hsa intrinsic with hsa target",
4413 DAG.getContext()->diagnose(BadIntrin);
4414 return DAG.getUNDEF(VT);
4417 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4419 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4420 "intrinsic not supported on subtarget",
4422 DAG.getContext()->diagnose(BadIntrin);
4423 return DAG.getUNDEF(VT);
4426 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4427 ArrayRef<SDValue> Elts) {
4428 assert(!Elts.empty());
4432 if (Elts.size() == 1) {
4435 } else if (Elts.size() == 2) {
4438 } else if (Elts.size() <= 4) {
4441 } else if (Elts.size() <= 8) {
4445 assert(Elts.size() <= 16);
4450 SmallVector<SDValue, 16> VecElts(NumElts);
4451 for (unsigned i = 0; i < Elts.size(); ++i) {
4452 SDValue Elt = Elts[i];
4453 if (Elt.getValueType() != MVT::f32)
4454 Elt = DAG.getBitcast(MVT::f32, Elt);
4457 for (unsigned i = Elts.size(); i < NumElts; ++i)
4458 VecElts[i] = DAG.getUNDEF(MVT::f32);
4462 return DAG.getBuildVector(Type, DL, VecElts);
4465 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4466 SDValue *GLC, SDValue *SLC) {
4467 auto CachePolicyConst = dyn_cast<ConstantSDNode>(CachePolicy.getNode());
4468 if (!CachePolicyConst)
4471 uint64_t Value = CachePolicyConst->getZExtValue();
4472 SDLoc DL(CachePolicy);
4474 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4475 Value &= ~(uint64_t)0x1;
4478 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4479 Value &= ~(uint64_t)0x2;
4485 SDValue SITargetLowering::lowerImage(SDValue Op,
4486 const AMDGPU::ImageDimIntrinsicInfo *Intr,
4487 SelectionDAG &DAG) const {
4489 MachineFunction &MF = DAG.getMachineFunction();
4490 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4491 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4492 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4494 SmallVector<EVT, 2> ResultTypes(Op->value_begin(), Op->value_end());
4498 unsigned AddrIdx; // Index of first address argument
4501 if (BaseOpcode->Atomic) {
4502 VData = Op.getOperand(2);
4504 bool Is64Bit = VData.getValueType() == MVT::i64;
4505 if (BaseOpcode->AtomicX2) {
4506 SDValue VData2 = Op.getOperand(3);
4507 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4510 VData = DAG.getBitcast(MVT::v4i32, VData);
4512 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4513 DMask = Is64Bit ? 0xf : 0x3;
4514 NumVDataDwords = Is64Bit ? 4 : 2;
4517 DMask = Is64Bit ? 0x3 : 0x1;
4518 NumVDataDwords = Is64Bit ? 2 : 1;
4524 if (BaseOpcode->Store) {
4525 VData = Op.getOperand(2);
4527 MVT StoreVT = VData.getSimpleValueType();
4528 if (StoreVT.getScalarType() == MVT::f16) {
4529 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4530 !BaseOpcode->HasD16)
4531 return Op; // D16 is unsupported for this instruction
4534 VData = handleD16VData(VData, DAG);
4537 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4540 MVT LoadVT = Op.getSimpleValueType();
4541 if (LoadVT.getScalarType() == MVT::f16) {
4542 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4543 !BaseOpcode->HasD16)
4544 return Op; // D16 is unsupported for this instruction
4547 if (LoadVT.isVector() && Subtarget->hasUnpackedD16VMem())
4548 ResultTypes[0] = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
4551 NumVDataDwords = (ResultTypes[0].getSizeInBits() + 31) / 32;
4552 DMaskIdx = isa<MemSDNode>(Op) ? 2 : 1;
4555 auto DMaskConst = dyn_cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4559 AddrIdx = DMaskIdx + 1;
4560 DMask = DMaskConst->getZExtValue();
4561 if (!DMask && !BaseOpcode->Store) {
4562 // Eliminate no-op loads. Stores with dmask == 0 are *not* no-op: they
4563 // store the channels' default values.
4564 SDValue Undef = DAG.getUNDEF(Op.getValueType());
4565 if (isa<MemSDNode>(Op))
4566 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
4571 unsigned NumVAddrs = BaseOpcode->NumExtraArgs +
4572 (BaseOpcode->Gradients ? DimInfo->NumGradients : 0) +
4573 (BaseOpcode->Coordinates ? DimInfo->NumCoords : 0) +
4574 (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4575 SmallVector<SDValue, 4> VAddrs;
4576 for (unsigned i = 0; i < NumVAddrs; ++i)
4577 VAddrs.push_back(Op.getOperand(AddrIdx + i));
4578 SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4580 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4581 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4582 unsigned CtrlIdx; // Index of texfailctrl argument
4584 if (!BaseOpcode->Sampler) {
4586 CtrlIdx = AddrIdx + NumVAddrs + 1;
4589 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
4593 Unorm = UnormConst->getZExtValue() ? True : False;
4594 CtrlIdx = AddrIdx + NumVAddrs + 3;
4597 SDValue TexFail = Op.getOperand(CtrlIdx);
4598 auto TexFailConst = dyn_cast<ConstantSDNode>(TexFail.getNode());
4599 if (!TexFailConst || TexFailConst->getZExtValue() != 0)
4604 if (BaseOpcode->Atomic) {
4605 GLC = True; // TODO no-return optimization
4606 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC))
4609 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC))
4613 SmallVector<SDValue, 14> Ops;
4614 if (BaseOpcode->Store || BaseOpcode->Atomic)
4615 Ops.push_back(VData); // vdata
4616 Ops.push_back(VAddr);
4617 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
4618 if (BaseOpcode->Sampler)
4619 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
4620 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
4621 Ops.push_back(Unorm);
4624 Ops.push_back(False); // r128
4625 Ops.push_back(False); // tfe
4626 Ops.push_back(False); // lwe
4627 Ops.push_back(DimInfo->DA ? True : False);
4628 if (BaseOpcode->HasD16)
4629 Ops.push_back(IsD16 ? True : False);
4630 if (isa<MemSDNode>(Op))
4631 Ops.push_back(Op.getOperand(0)); // chain
4633 int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32;
4636 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4637 Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx8,
4638 NumVDataDwords, NumVAddrDwords);
4640 Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx6,
4641 NumVDataDwords, NumVAddrDwords);
4642 assert(Opcode != -1);
4644 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
4645 if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
4646 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4647 *MemRefs = MemOp->getMemOperand();
4648 NewNode->setMemRefs(MemRefs, MemRefs + 1);
4651 if (BaseOpcode->AtomicX2) {
4652 SmallVector<SDValue, 1> Elt;
4653 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
4654 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
4655 } else if (IsD16 && !BaseOpcode->Store) {
4656 MVT LoadVT = Op.getSimpleValueType();
4657 SDValue Adjusted = adjustLoadValueTypeImpl(
4658 SDValue(NewNode, 0), LoadVT, DL, DAG, Subtarget->hasUnpackedD16VMem());
4659 return DAG.getMergeValues({Adjusted, SDValue(NewNode, 1)}, DL);
4662 return SDValue(NewNode, 0);
4665 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4666 SelectionDAG &DAG) const {
4667 MachineFunction &MF = DAG.getMachineFunction();
4668 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4670 EVT VT = Op.getValueType();
4672 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4674 // TODO: Should this propagate fast-math-flags?
4676 switch (IntrinsicID) {
4677 case Intrinsic::amdgcn_implicit_buffer_ptr: {
4678 if (getSubtarget()->isAmdCodeObjectV2(MF.getFunction()))
4679 return emitNonHSAIntrinsicError(DAG, DL, VT);
4680 return getPreloadedValue(DAG, *MFI, VT,
4681 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4683 case Intrinsic::amdgcn_dispatch_ptr:
4684 case Intrinsic::amdgcn_queue_ptr: {
4685 if (!Subtarget->isAmdCodeObjectV2(MF.getFunction())) {
4686 DiagnosticInfoUnsupported BadIntrin(
4687 MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4689 DAG.getContext()->diagnose(BadIntrin);
4690 return DAG.getUNDEF(VT);
4693 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4694 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4695 return getPreloadedValue(DAG, *MFI, VT, RegID);
4697 case Intrinsic::amdgcn_implicitarg_ptr: {
4698 if (MFI->isEntryFunction())
4699 return getImplicitArgPtr(DAG, DL);
4700 return getPreloadedValue(DAG, *MFI, VT,
4701 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4703 case Intrinsic::amdgcn_kernarg_segment_ptr: {
4704 return getPreloadedValue(DAG, *MFI, VT,
4705 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4707 case Intrinsic::amdgcn_dispatch_id: {
4708 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4710 case Intrinsic::amdgcn_rcp:
4711 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4712 case Intrinsic::amdgcn_rsq:
4713 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4714 case Intrinsic::amdgcn_rsq_legacy:
4715 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4716 return emitRemovedIntrinsicError(DAG, DL, VT);
4718 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4719 case Intrinsic::amdgcn_rcp_legacy:
4720 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
4721 return emitRemovedIntrinsicError(DAG, DL, VT);
4722 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4723 case Intrinsic::amdgcn_rsq_clamp: {
4724 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4725 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4727 Type *Type = VT.getTypeForEVT(*DAG.getContext());
4728 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4729 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4731 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4732 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4733 DAG.getConstantFP(Max, DL, VT));
4734 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4735 DAG.getConstantFP(Min, DL, VT));
4737 case Intrinsic::r600_read_ngroups_x:
4738 if (Subtarget->isAmdHsaOS())
4739 return emitNonHSAIntrinsicError(DAG, DL, VT);
4741 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4742 SI::KernelInputOffsets::NGROUPS_X, 4, false);
4743 case Intrinsic::r600_read_ngroups_y:
4744 if (Subtarget->isAmdHsaOS())
4745 return emitNonHSAIntrinsicError(DAG, DL, VT);
4747 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4748 SI::KernelInputOffsets::NGROUPS_Y, 4, false);
4749 case Intrinsic::r600_read_ngroups_z:
4750 if (Subtarget->isAmdHsaOS())
4751 return emitNonHSAIntrinsicError(DAG, DL, VT);
4753 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4754 SI::KernelInputOffsets::NGROUPS_Z, 4, false);
4755 case Intrinsic::r600_read_global_size_x:
4756 if (Subtarget->isAmdHsaOS())
4757 return emitNonHSAIntrinsicError(DAG, DL, VT);
4759 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4760 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
4761 case Intrinsic::r600_read_global_size_y:
4762 if (Subtarget->isAmdHsaOS())
4763 return emitNonHSAIntrinsicError(DAG, DL, VT);
4765 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4766 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
4767 case Intrinsic::r600_read_global_size_z:
4768 if (Subtarget->isAmdHsaOS())
4769 return emitNonHSAIntrinsicError(DAG, DL, VT);
4771 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4772 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
4773 case Intrinsic::r600_read_local_size_x:
4774 if (Subtarget->isAmdHsaOS())
4775 return emitNonHSAIntrinsicError(DAG, DL, VT);
4777 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4778 SI::KernelInputOffsets::LOCAL_SIZE_X);
4779 case Intrinsic::r600_read_local_size_y:
4780 if (Subtarget->isAmdHsaOS())
4781 return emitNonHSAIntrinsicError(DAG, DL, VT);
4783 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4784 SI::KernelInputOffsets::LOCAL_SIZE_Y);
4785 case Intrinsic::r600_read_local_size_z:
4786 if (Subtarget->isAmdHsaOS())
4787 return emitNonHSAIntrinsicError(DAG, DL, VT);
4789 return lowerImplicitZextParam(DAG, Op, MVT::i16,
4790 SI::KernelInputOffsets::LOCAL_SIZE_Z);
4791 case Intrinsic::amdgcn_workgroup_id_x:
4792 case Intrinsic::r600_read_tgid_x:
4793 return getPreloadedValue(DAG, *MFI, VT,
4794 AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4795 case Intrinsic::amdgcn_workgroup_id_y:
4796 case Intrinsic::r600_read_tgid_y:
4797 return getPreloadedValue(DAG, *MFI, VT,
4798 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4799 case Intrinsic::amdgcn_workgroup_id_z:
4800 case Intrinsic::r600_read_tgid_z:
4801 return getPreloadedValue(DAG, *MFI, VT,
4802 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4803 case Intrinsic::amdgcn_workitem_id_x: {
4804 case Intrinsic::r600_read_tidig_x:
4805 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4806 SDLoc(DAG.getEntryNode()),
4807 MFI->getArgInfo().WorkItemIDX);
4809 case Intrinsic::amdgcn_workitem_id_y:
4810 case Intrinsic::r600_read_tidig_y:
4811 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4812 SDLoc(DAG.getEntryNode()),
4813 MFI->getArgInfo().WorkItemIDY);
4814 case Intrinsic::amdgcn_workitem_id_z:
4815 case Intrinsic::r600_read_tidig_z:
4816 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4817 SDLoc(DAG.getEntryNode()),
4818 MFI->getArgInfo().WorkItemIDZ);
4819 case AMDGPUIntrinsic::SI_load_const: {
4825 MachineMemOperand *MMO = MF.getMachineMemOperand(
4826 MachinePointerInfo(),
4827 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4828 MachineMemOperand::MOInvariant,
4829 VT.getStoreSize(), 4);
4830 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4831 Op->getVTList(), Ops, VT, MMO);
4833 case Intrinsic::amdgcn_fdiv_fast:
4834 return lowerFDIV_FAST(Op, DAG);
4835 case Intrinsic::amdgcn_interp_mov: {
4836 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4837 SDValue Glue = M0.getValue(1);
4838 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4839 Op.getOperand(2), Op.getOperand(3), Glue);
4841 case Intrinsic::amdgcn_interp_p1: {
4842 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4843 SDValue Glue = M0.getValue(1);
4844 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4845 Op.getOperand(2), Op.getOperand(3), Glue);
4847 case Intrinsic::amdgcn_interp_p2: {
4848 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4849 SDValue Glue = SDValue(M0.getNode(), 1);
4850 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4851 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4854 case Intrinsic::amdgcn_sin:
4855 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4857 case Intrinsic::amdgcn_cos:
4858 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4860 case Intrinsic::amdgcn_log_clamp: {
4861 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
4864 DiagnosticInfoUnsupported BadIntrin(
4865 MF.getFunction(), "intrinsic not supported on subtarget",
4867 DAG.getContext()->diagnose(BadIntrin);
4868 return DAG.getUNDEF(VT);
4870 case Intrinsic::amdgcn_ldexp:
4871 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4872 Op.getOperand(1), Op.getOperand(2));
4874 case Intrinsic::amdgcn_fract:
4875 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4877 case Intrinsic::amdgcn_class:
4878 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4879 Op.getOperand(1), Op.getOperand(2));
4880 case Intrinsic::amdgcn_div_fmas:
4881 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4882 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4885 case Intrinsic::amdgcn_div_fixup:
4886 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4887 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4889 case Intrinsic::amdgcn_trig_preop:
4890 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4891 Op.getOperand(1), Op.getOperand(2));
4892 case Intrinsic::amdgcn_div_scale: {
4893 // 3rd parameter required to be a constant.
4894 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4896 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4898 // Translate to the operands expected by the machine instruction. The
4899 // first parameter must be the same as the first instruction.
4900 SDValue Numerator = Op.getOperand(1);
4901 SDValue Denominator = Op.getOperand(2);
4903 // Note this order is opposite of the machine instruction's operations,
4904 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4905 // intrinsic has the numerator as the first operand to match a normal
4906 // division operation.
4908 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4910 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4911 Denominator, Numerator);
4913 case Intrinsic::amdgcn_icmp: {
4914 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4916 return DAG.getUNDEF(VT);
4918 int CondCode = CD->getSExtValue();
4919 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4920 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4921 return DAG.getUNDEF(VT);
4923 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4924 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4925 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4926 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4928 case Intrinsic::amdgcn_fcmp: {
4929 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4931 return DAG.getUNDEF(VT);
4933 int CondCode = CD->getSExtValue();
4934 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4935 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4936 return DAG.getUNDEF(VT);
4938 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4939 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4940 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4941 Op.getOperand(2), DAG.getCondCode(CCOpcode));
4943 case Intrinsic::amdgcn_fmed3:
4944 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4945 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4946 case Intrinsic::amdgcn_fdot2:
4947 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
4948 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4949 case Intrinsic::amdgcn_fmul_legacy:
4950 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4951 Op.getOperand(1), Op.getOperand(2));
4952 case Intrinsic::amdgcn_sffbh:
4953 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4954 case Intrinsic::amdgcn_sbfe:
4955 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4956 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4957 case Intrinsic::amdgcn_ubfe:
4958 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4959 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4960 case Intrinsic::amdgcn_cvt_pkrtz:
4961 case Intrinsic::amdgcn_cvt_pknorm_i16:
4962 case Intrinsic::amdgcn_cvt_pknorm_u16:
4963 case Intrinsic::amdgcn_cvt_pk_i16:
4964 case Intrinsic::amdgcn_cvt_pk_u16: {
4965 // FIXME: Stop adding cast if v2f16/v2i16 are legal.
4966 EVT VT = Op.getValueType();
4969 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
4970 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
4971 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
4972 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4973 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
4974 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4975 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
4976 Opcode = AMDGPUISD::CVT_PK_I16_I32;
4978 Opcode = AMDGPUISD::CVT_PK_U16_U32;
4980 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
4981 Op.getOperand(1), Op.getOperand(2));
4982 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4984 case Intrinsic::amdgcn_wqm: {
4985 SDValue Src = Op.getOperand(1);
4986 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4989 case Intrinsic::amdgcn_wwm: {
4990 SDValue Src = Op.getOperand(1);
4991 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4994 case Intrinsic::amdgcn_fmad_ftz:
4995 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
4996 Op.getOperand(2), Op.getOperand(3));
4998 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
4999 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5000 return lowerImage(Op, ImageDimIntr, DAG);
5006 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5007 SelectionDAG &DAG) const {
5008 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5012 case Intrinsic::amdgcn_atomic_inc:
5013 case Intrinsic::amdgcn_atomic_dec:
5014 case Intrinsic::amdgcn_ds_fadd:
5015 case Intrinsic::amdgcn_ds_fmin:
5016 case Intrinsic::amdgcn_ds_fmax: {
5017 MemSDNode *M = cast<MemSDNode>(Op);
5020 case Intrinsic::amdgcn_atomic_inc:
5021 Opc = AMDGPUISD::ATOMIC_INC;
5023 case Intrinsic::amdgcn_atomic_dec:
5024 Opc = AMDGPUISD::ATOMIC_DEC;
5026 case Intrinsic::amdgcn_ds_fadd:
5027 Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
5029 case Intrinsic::amdgcn_ds_fmin:
5030 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5032 case Intrinsic::amdgcn_ds_fmax:
5033 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5036 llvm_unreachable("Unknown intrinsic!");
5039 M->getOperand(0), // Chain
5040 M->getOperand(2), // Ptr
5041 M->getOperand(3) // Value
5044 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5045 M->getMemoryVT(), M->getMemOperand());
5047 case Intrinsic::amdgcn_buffer_load:
5048 case Intrinsic::amdgcn_buffer_load_format: {
5050 Op.getOperand(0), // Chain
5051 Op.getOperand(2), // rsrc
5052 Op.getOperand(3), // vindex
5053 Op.getOperand(4), // offset
5054 Op.getOperand(5), // glc
5055 Op.getOperand(6) // slc
5058 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5059 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5060 EVT VT = Op.getValueType();
5061 EVT IntVT = VT.changeTypeToInteger();
5062 auto *M = cast<MemSDNode>(Op);
5063 EVT LoadVT = Op.getValueType();
5064 bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5066 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG);
5068 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5069 M->getMemOperand());
5071 case Intrinsic::amdgcn_tbuffer_load: {
5072 MemSDNode *M = cast<MemSDNode>(Op);
5073 EVT LoadVT = Op.getValueType();
5074 bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5076 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG);
5080 Op.getOperand(0), // Chain
5081 Op.getOperand(2), // rsrc
5082 Op.getOperand(3), // vindex
5083 Op.getOperand(4), // voffset
5084 Op.getOperand(5), // soffset
5085 Op.getOperand(6), // offset
5086 Op.getOperand(7), // dfmt
5087 Op.getOperand(8), // nfmt
5088 Op.getOperand(9), // glc
5089 Op.getOperand(10) // slc
5092 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5093 Op->getVTList(), Ops, LoadVT,
5094 M->getMemOperand());
5096 case Intrinsic::amdgcn_buffer_atomic_swap:
5097 case Intrinsic::amdgcn_buffer_atomic_add:
5098 case Intrinsic::amdgcn_buffer_atomic_sub:
5099 case Intrinsic::amdgcn_buffer_atomic_smin:
5100 case Intrinsic::amdgcn_buffer_atomic_umin:
5101 case Intrinsic::amdgcn_buffer_atomic_smax:
5102 case Intrinsic::amdgcn_buffer_atomic_umax:
5103 case Intrinsic::amdgcn_buffer_atomic_and:
5104 case Intrinsic::amdgcn_buffer_atomic_or:
5105 case Intrinsic::amdgcn_buffer_atomic_xor: {
5107 Op.getOperand(0), // Chain
5108 Op.getOperand(2), // vdata
5109 Op.getOperand(3), // rsrc
5110 Op.getOperand(4), // vindex
5111 Op.getOperand(5), // offset
5112 Op.getOperand(6) // slc
5114 EVT VT = Op.getValueType();
5116 auto *M = cast<MemSDNode>(Op);
5117 unsigned Opcode = 0;
5120 case Intrinsic::amdgcn_buffer_atomic_swap:
5121 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5123 case Intrinsic::amdgcn_buffer_atomic_add:
5124 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5126 case Intrinsic::amdgcn_buffer_atomic_sub:
5127 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5129 case Intrinsic::amdgcn_buffer_atomic_smin:
5130 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5132 case Intrinsic::amdgcn_buffer_atomic_umin:
5133 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5135 case Intrinsic::amdgcn_buffer_atomic_smax:
5136 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5138 case Intrinsic::amdgcn_buffer_atomic_umax:
5139 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5141 case Intrinsic::amdgcn_buffer_atomic_and:
5142 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5144 case Intrinsic::amdgcn_buffer_atomic_or:
5145 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5147 case Intrinsic::amdgcn_buffer_atomic_xor:
5148 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5151 llvm_unreachable("unhandled atomic opcode");
5154 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5155 M->getMemOperand());
5158 case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5160 Op.getOperand(0), // Chain
5161 Op.getOperand(2), // src
5162 Op.getOperand(3), // cmp
5163 Op.getOperand(4), // rsrc
5164 Op.getOperand(5), // vindex
5165 Op.getOperand(6), // offset
5166 Op.getOperand(7) // slc
5168 EVT VT = Op.getValueType();
5169 auto *M = cast<MemSDNode>(Op);
5171 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5172 Op->getVTList(), Ops, VT, M->getMemOperand());
5176 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5177 AMDGPU::getImageDimIntrinsicInfo(IntrID))
5178 return lowerImage(Op, ImageDimIntr, DAG);
5184 SDValue SITargetLowering::handleD16VData(SDValue VData,
5185 SelectionDAG &DAG) const {
5186 EVT StoreVT = VData.getValueType();
5188 // No change for f16 and legal vector D16 types.
5189 if (!StoreVT.isVector())
5193 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5195 if (Subtarget->hasUnpackedD16VMem()) {
5196 // We need to unpack the packed data to store.
5197 EVT IntStoreVT = StoreVT.changeTypeToInteger();
5198 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5200 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5201 StoreVT.getVectorNumElements());
5202 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5203 return DAG.UnrollVectorOp(ZExt.getNode());
5206 assert(isTypeLegal(StoreVT));
5210 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5211 SelectionDAG &DAG) const {
5213 SDValue Chain = Op.getOperand(0);
5214 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5215 MachineFunction &MF = DAG.getMachineFunction();
5217 switch (IntrinsicID) {
5218 case Intrinsic::amdgcn_exp: {
5219 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5220 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5221 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5222 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5224 const SDValue Ops[] = {
5226 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5227 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5228 Op.getOperand(4), // src0
5229 Op.getOperand(5), // src1
5230 Op.getOperand(6), // src2
5231 Op.getOperand(7), // src3
5232 DAG.getTargetConstant(0, DL, MVT::i1), // compr
5233 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5236 unsigned Opc = Done->isNullValue() ?
5237 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5238 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5240 case Intrinsic::amdgcn_exp_compr: {
5241 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5242 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5243 SDValue Src0 = Op.getOperand(4);
5244 SDValue Src1 = Op.getOperand(5);
5245 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5246 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5248 SDValue Undef = DAG.getUNDEF(MVT::f32);
5249 const SDValue Ops[] = {
5251 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5252 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
5253 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5254 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5257 DAG.getTargetConstant(1, DL, MVT::i1), // compr
5258 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5261 unsigned Opc = Done->isNullValue() ?
5262 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5263 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5265 case Intrinsic::amdgcn_s_sendmsg:
5266 case Intrinsic::amdgcn_s_sendmsghalt: {
5267 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5268 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5269 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5270 SDValue Glue = Chain.getValue(1);
5271 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5272 Op.getOperand(2), Glue);
5274 case Intrinsic::amdgcn_init_exec: {
5275 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5278 case Intrinsic::amdgcn_init_exec_from_input: {
5279 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5280 Op.getOperand(2), Op.getOperand(3));
5282 case AMDGPUIntrinsic::AMDGPU_kill: {
5283 SDValue Src = Op.getOperand(2);
5284 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5285 if (!K->isNegative())
5288 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5289 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5292 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5293 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5295 case Intrinsic::amdgcn_s_barrier: {
5296 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5297 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5298 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5299 if (WGSize <= ST.getWavefrontSize())
5300 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5301 Op.getOperand(0)), 0);
5305 case AMDGPUIntrinsic::SI_tbuffer_store: {
5307 // Extract vindex and voffset from vaddr as appropriate
5308 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5309 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5310 SDValue VAddr = Op.getOperand(5);
5312 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5314 assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5315 "Legacy intrinsic doesn't support both offset and index - use new version");
5317 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5318 SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5320 // Deal with the vec-3 case
5321 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5322 auto Opcode = NumChannels->getZExtValue() == 3 ?
5323 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5327 Op.getOperand(3), // vdata
5328 Op.getOperand(2), // rsrc
5331 Op.getOperand(6), // soffset
5332 Op.getOperand(7), // inst_offset
5333 Op.getOperand(8), // dfmt
5334 Op.getOperand(9), // nfmt
5335 Op.getOperand(12), // glc
5336 Op.getOperand(13), // slc
5339 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5340 "Value of tfe other than zero is unsupported");
5342 EVT VT = Op.getOperand(3).getValueType();
5343 MachineMemOperand *MMO = MF.getMachineMemOperand(
5344 MachinePointerInfo(),
5345 MachineMemOperand::MOStore,
5346 VT.getStoreSize(), 4);
5347 return DAG.getMemIntrinsicNode(Opcode, DL,
5348 Op->getVTList(), Ops, VT, MMO);
5351 case Intrinsic::amdgcn_tbuffer_store: {
5352 SDValue VData = Op.getOperand(2);
5353 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5355 VData = handleD16VData(VData, DAG);
5359 Op.getOperand(3), // rsrc
5360 Op.getOperand(4), // vindex
5361 Op.getOperand(5), // voffset
5362 Op.getOperand(6), // soffset
5363 Op.getOperand(7), // offset
5364 Op.getOperand(8), // dfmt
5365 Op.getOperand(9), // nfmt
5366 Op.getOperand(10), // glc
5367 Op.getOperand(11) // slc
5369 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5370 AMDGPUISD::TBUFFER_STORE_FORMAT;
5371 MemSDNode *M = cast<MemSDNode>(Op);
5372 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5373 M->getMemoryVT(), M->getMemOperand());
5376 case Intrinsic::amdgcn_buffer_store:
5377 case Intrinsic::amdgcn_buffer_store_format: {
5378 SDValue VData = Op.getOperand(2);
5379 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5381 VData = handleD16VData(VData, DAG);
5385 Op.getOperand(3), // rsrc
5386 Op.getOperand(4), // vindex
5387 Op.getOperand(5), // offset
5388 Op.getOperand(6), // glc
5389 Op.getOperand(7) // slc
5391 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5392 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5393 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5394 MemSDNode *M = cast<MemSDNode>(Op);
5395 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5396 M->getMemoryVT(), M->getMemOperand());
5399 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5400 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5401 return lowerImage(Op, ImageDimIntr, DAG);
5408 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
5409 ISD::LoadExtType ExtType, SDValue Op,
5410 const SDLoc &SL, EVT VT) {
5411 if (VT.bitsLT(Op.getValueType()))
5412 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
5416 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
5418 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
5420 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
5421 case ISD::NON_EXTLOAD:
5425 llvm_unreachable("invalid ext type");
5428 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
5429 SelectionDAG &DAG = DCI.DAG;
5430 if (Ld->getAlignment() < 4 || Ld->isDivergent())
5433 // FIXME: Constant loads should all be marked invariant.
5434 unsigned AS = Ld->getAddressSpace();
5435 if (AS != AMDGPUASI.CONSTANT_ADDRESS &&
5436 AS != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
5437 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
5440 // Don't do this early, since it may interfere with adjacent load merging for
5441 // illegal types. We can avoid losing alignment information for exotic types
5443 EVT MemVT = Ld->getMemoryVT();
5444 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
5445 MemVT.getSizeInBits() >= 32)
5450 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
5451 "unexpected vector extload");
5453 // TODO: Drop only high part of range.
5454 SDValue Ptr = Ld->getBasePtr();
5455 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
5456 MVT::i32, SL, Ld->getChain(), Ptr,
5458 Ld->getPointerInfo(), MVT::i32,
5460 Ld->getMemOperand()->getFlags(),
5462 nullptr); // Drop ranges
5464 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
5465 if (MemVT.isFloatingPoint()) {
5466 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
5467 "unexpected fp extload");
5468 TruncVT = MemVT.changeTypeToInteger();
5471 SDValue Cvt = NewLoad;
5472 if (Ld->getExtensionType() == ISD::SEXTLOAD) {
5473 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
5474 DAG.getValueType(TruncVT));
5475 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
5476 Ld->getExtensionType() == ISD::NON_EXTLOAD) {
5477 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
5479 assert(Ld->getExtensionType() == ISD::EXTLOAD);
5482 EVT VT = Ld->getValueType(0);
5483 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5485 DCI.AddToWorklist(Cvt.getNode());
5487 // We may need to handle exotic cases, such as i16->i64 extloads, so insert
5488 // the appropriate extension from the 32-bit load.
5489 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
5490 DCI.AddToWorklist(Cvt.getNode());
5492 // Handle conversion back to floating point if necessary.
5493 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
5495 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
5498 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5500 LoadSDNode *Load = cast<LoadSDNode>(Op);
5501 ISD::LoadExtType ExtType = Load->getExtensionType();
5502 EVT MemVT = Load->getMemoryVT();
5504 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5505 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5508 // FIXME: Copied from PPC
5509 // First, load into 32 bits, then truncate to 1 bit.
5511 SDValue Chain = Load->getChain();
5512 SDValue BasePtr = Load->getBasePtr();
5513 MachineMemOperand *MMO = Load->getMemOperand();
5515 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5517 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5518 BasePtr, RealMemVT, MMO);
5521 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5525 return DAG.getMergeValues(Ops, DL);
5528 if (!MemVT.isVector())
5531 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5532 "Custom lowering for non-i32 vectors hasn't been implemented.");
5534 unsigned Alignment = Load->getAlignment();
5535 unsigned AS = Load->getAddressSpace();
5536 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5539 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5540 return DAG.getMergeValues(Ops, DL);
5543 MachineFunction &MF = DAG.getMachineFunction();
5544 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5545 // If there is a possibilty that flat instruction access scratch memory
5546 // then we need to use the same legalization rules we use for private.
5547 if (AS == AMDGPUASI.FLAT_ADDRESS)
5548 AS = MFI->hasFlatScratchInit() ?
5549 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5551 unsigned NumElements = MemVT.getVectorNumElements();
5553 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5554 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5555 if (!Op->isDivergent() && Alignment >= 4)
5557 // Non-uniform loads will be selected to MUBUF instructions, so they
5558 // have the same legalization requirements as global and private
5563 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5564 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5565 AS == AMDGPUASI.GLOBAL_ADDRESS) {
5566 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
5567 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
5570 // Non-uniform loads will be selected to MUBUF instructions, so they
5571 // have the same legalization requirements as global and private
5575 if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5576 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5577 AS == AMDGPUASI.GLOBAL_ADDRESS ||
5578 AS == AMDGPUASI.FLAT_ADDRESS) {
5579 if (NumElements > 4)
5580 return SplitVectorLoad(Op, DAG);
5581 // v4 loads are supported for private and global memory.
5584 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5585 // Depending on the setting of the private_element_size field in the
5586 // resource descriptor, we can only make private accesses up to a certain
5588 switch (Subtarget->getMaxPrivateElementSize()) {
5590 return scalarizeVectorLoad(Load, DAG);
5592 if (NumElements > 2)
5593 return SplitVectorLoad(Op, DAG);
5596 // Same as global/flat
5597 if (NumElements > 4)
5598 return SplitVectorLoad(Op, DAG);
5601 llvm_unreachable("unsupported private_element_size");
5603 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5604 // Use ds_read_b128 if possible.
5605 if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
5606 MemVT.getStoreSize() == 16)
5609 if (NumElements > 2)
5610 return SplitVectorLoad(Op, DAG);
5615 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5616 EVT VT = Op.getValueType();
5617 assert(VT.getSizeInBits() == 64);
5620 SDValue Cond = Op.getOperand(0);
5622 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5623 SDValue One = DAG.getConstant(1, DL, MVT::i32);
5625 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5626 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5628 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5629 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5631 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5633 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5634 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5636 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5638 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5639 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5642 // Catch division cases where we can use shortcuts with rcp and rsq
5644 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5645 SelectionDAG &DAG) const {
5647 SDValue LHS = Op.getOperand(0);
5648 SDValue RHS = Op.getOperand(1);
5649 EVT VT = Op.getValueType();
5650 const SDNodeFlags Flags = Op->getFlags();
5651 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
5653 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5656 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5657 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5658 if (CLHS->isExactlyValue(1.0)) {
5659 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5660 // the CI documentation has a worst case error of 1 ulp.
5661 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5662 // use it as long as we aren't trying to use denormals.
5664 // v_rcp_f16 and v_rsq_f16 DO support denormals.
5666 // 1.0 / sqrt(x) -> rsq(x)
5668 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5669 // error seems really high at 2^29 ULP.
5670 if (RHS.getOpcode() == ISD::FSQRT)
5671 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5673 // 1.0 / x -> rcp(x)
5674 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5677 // Same as for 1.0, but expand the sign out of the constant.
5678 if (CLHS->isExactlyValue(-1.0)) {
5679 // -1.0 / x -> rcp (fneg x)
5680 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5681 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5687 // Turn into multiply by the reciprocal.
5688 // x / y -> x * (1.0 / y)
5689 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5690 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5696 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5697 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5698 if (GlueChain->getNumValues() <= 1) {
5699 return DAG.getNode(Opcode, SL, VT, A, B);
5702 assert(GlueChain->getNumValues() == 3);
5704 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5706 default: llvm_unreachable("no chain equivalent for opcode");
5708 Opcode = AMDGPUISD::FMUL_W_CHAIN;
5712 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5713 GlueChain.getValue(2));
5716 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5717 EVT VT, SDValue A, SDValue B, SDValue C,
5718 SDValue GlueChain) {
5719 if (GlueChain->getNumValues() <= 1) {
5720 return DAG.getNode(Opcode, SL, VT, A, B, C);
5723 assert(GlueChain->getNumValues() == 3);
5725 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5727 default: llvm_unreachable("no chain equivalent for opcode");
5729 Opcode = AMDGPUISD::FMA_W_CHAIN;
5733 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5734 GlueChain.getValue(2));
5737 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5738 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5742 SDValue Src0 = Op.getOperand(0);
5743 SDValue Src1 = Op.getOperand(1);
5745 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5746 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5748 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5749 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5751 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5752 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5754 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5757 // Faster 2.5 ULP division that does not support denormals.
5758 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5760 SDValue LHS = Op.getOperand(1);
5761 SDValue RHS = Op.getOperand(2);
5763 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5765 const APFloat K0Val(BitsToFloat(0x6f800000));
5766 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5768 const APFloat K1Val(BitsToFloat(0x2f800000));
5769 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5771 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5774 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5776 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5778 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5780 // TODO: Should this propagate fast-math-flags?
5781 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5783 // rcp does not support denormals.
5784 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5786 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5788 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5791 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5792 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5796 SDValue LHS = Op.getOperand(0);
5797 SDValue RHS = Op.getOperand(1);
5799 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5801 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5803 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5805 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5808 // Denominator is scaled to not be denormal, so using rcp is ok.
5809 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5811 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5814 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5815 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5816 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5818 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5820 if (!Subtarget->hasFP32Denormals()) {
5821 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5822 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5824 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5826 EnableDenormValue, BitField);
5829 EnableDenorm.getValue(0),
5830 EnableDenorm.getValue(1)
5833 NegDivScale0 = DAG.getMergeValues(Ops, SL);
5836 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5837 ApproxRcp, One, NegDivScale0);
5839 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5842 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5845 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5846 NumeratorScaled, Mul);
5848 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5850 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5851 NumeratorScaled, Fma3);
5853 if (!Subtarget->hasFP32Denormals()) {
5854 const SDValue DisableDenormValue =
5855 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5856 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5862 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5863 DisableDenorm, DAG.getRoot());
5864 DAG.setRoot(OutputChain);
5867 SDValue Scale = NumeratorScaled.getValue(1);
5868 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5869 Fma4, Fma1, Fma3, Scale);
5871 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5874 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5875 if (DAG.getTarget().Options.UnsafeFPMath)
5876 return lowerFastUnsafeFDIV(Op, DAG);
5879 SDValue X = Op.getOperand(0);
5880 SDValue Y = Op.getOperand(1);
5882 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5884 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5886 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5888 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5890 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5892 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5894 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5896 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5898 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5900 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5901 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5903 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5904 NegDivScale0, Mul, DivScale1);
5908 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
5909 // Workaround a hardware bug on SI where the condition output from div_scale
5912 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5914 // Figure out if the scale to use for div_fmas.
5915 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5916 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5917 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5918 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5920 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5921 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5924 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5926 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5928 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5929 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5930 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5932 Scale = DivScale1.getValue(1);
5935 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5936 Fma4, Fma3, Mul, Scale);
5938 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5941 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5942 EVT VT = Op.getValueType();
5945 return LowerFDIV32(Op, DAG);
5948 return LowerFDIV64(Op, DAG);
5951 return LowerFDIV16(Op, DAG);
5953 llvm_unreachable("Unexpected type for fdiv");
5956 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5958 StoreSDNode *Store = cast<StoreSDNode>(Op);
5959 EVT VT = Store->getMemoryVT();
5961 if (VT == MVT::i1) {
5962 return DAG.getTruncStore(Store->getChain(), DL,
5963 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5964 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5967 assert(VT.isVector() &&
5968 Store->getValue().getValueType().getScalarType() == MVT::i32);
5970 unsigned AS = Store->getAddressSpace();
5971 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5972 AS, Store->getAlignment())) {
5973 return expandUnalignedStore(Store, DAG);
5976 MachineFunction &MF = DAG.getMachineFunction();
5977 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5978 // If there is a possibilty that flat instruction access scratch memory
5979 // then we need to use the same legalization rules we use for private.
5980 if (AS == AMDGPUASI.FLAT_ADDRESS)
5981 AS = MFI->hasFlatScratchInit() ?
5982 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5984 unsigned NumElements = VT.getVectorNumElements();
5985 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5986 AS == AMDGPUASI.FLAT_ADDRESS) {
5987 if (NumElements > 4)
5988 return SplitVectorStore(Op, DAG);
5990 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5991 switch (Subtarget->getMaxPrivateElementSize()) {
5993 return scalarizeVectorStore(Store, DAG);
5995 if (NumElements > 2)
5996 return SplitVectorStore(Op, DAG);
5999 if (NumElements > 4)
6000 return SplitVectorStore(Op, DAG);
6003 llvm_unreachable("unsupported private_element_size");
6005 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
6006 // Use ds_write_b128 if possible.
6007 if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
6008 VT.getStoreSize() == 16)
6011 if (NumElements > 2)
6012 return SplitVectorStore(Op, DAG);
6015 llvm_unreachable("unhandled address space");
6019 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
6021 EVT VT = Op.getValueType();
6022 SDValue Arg = Op.getOperand(0);
6023 // TODO: Should this propagate fast-math-flags?
6024 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
6025 DAG.getNode(ISD::FMUL, DL, VT, Arg,
6026 DAG.getConstantFP(0.5/M_PI, DL,
6029 switch (Op.getOpcode()) {
6031 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
6033 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
6035 llvm_unreachable("Wrong trig opcode");
6039 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
6040 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
6041 assert(AtomicNode->isCompareAndSwap());
6042 unsigned AS = AtomicNode->getAddressSpace();
6044 // No custom lowering required for local address space
6045 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
6048 // Non-local address space requires custom lowering for atomic compare
6049 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
6051 SDValue ChainIn = Op.getOperand(0);
6052 SDValue Addr = Op.getOperand(1);
6053 SDValue Old = Op.getOperand(2);
6054 SDValue New = Op.getOperand(3);
6055 EVT VT = Op.getValueType();
6056 MVT SimpleVT = VT.getSimpleVT();
6057 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
6059 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
6060 SDValue Ops[] = { ChainIn, Addr, NewOld };
6062 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
6063 Ops, VT, AtomicNode->getMemOperand());
6066 //===----------------------------------------------------------------------===//
6067 // Custom DAG optimizations
6068 //===----------------------------------------------------------------------===//
6070 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
6071 DAGCombinerInfo &DCI) const {
6072 EVT VT = N->getValueType(0);
6073 EVT ScalarVT = VT.getScalarType();
6074 if (ScalarVT != MVT::f32)
6077 SelectionDAG &DAG = DCI.DAG;
6080 SDValue Src = N->getOperand(0);
6081 EVT SrcVT = Src.getValueType();
6083 // TODO: We could try to match extracting the higher bytes, which would be
6084 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
6085 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
6086 // about in practice.
6087 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
6088 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
6089 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
6090 DCI.AddToWorklist(Cvt.getNode());
6098 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
6100 // This is a variant of
6101 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
6103 // The normal DAG combiner will do this, but only if the add has one use since
6104 // that would increase the number of instructions.
6106 // This prevents us from seeing a constant offset that can be folded into a
6107 // memory instruction's addressing mode. If we know the resulting add offset of
6108 // a pointer can be folded into an addressing offset, we can replace the pointer
6109 // operand with the add of new constant offset. This eliminates one of the uses,
6110 // and may allow the remaining use to also be simplified.
6112 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
6115 DAGCombinerInfo &DCI) const {
6116 SDValue N0 = N->getOperand(0);
6117 SDValue N1 = N->getOperand(1);
6119 // We only do this to handle cases where it's profitable when there are
6120 // multiple uses of the add, so defer to the standard combine.
6121 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
6125 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
6129 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6133 // If the resulting offset is too large, we can't fold it into the addressing
6135 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
6136 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
6139 AM.HasBaseReg = true;
6140 AM.BaseOffs = Offset.getSExtValue();
6141 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
6144 SelectionDAG &DAG = DCI.DAG;
6146 EVT VT = N->getValueType(0);
6148 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
6149 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
6152 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
6153 (N0.getOpcode() == ISD::OR ||
6154 N0->getFlags().hasNoUnsignedWrap()));
6156 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
6159 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
6160 DAGCombinerInfo &DCI) const {
6161 SDValue Ptr = N->getBasePtr();
6162 SelectionDAG &DAG = DCI.DAG;
6165 // TODO: We could also do this for multiplies.
6166 if (Ptr.getOpcode() == ISD::SHL) {
6167 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
6168 N->getMemoryVT(), DCI);
6170 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6172 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6173 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6180 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6181 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6182 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6183 (Opc == ISD::XOR && Val == 0);
6186 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6187 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6188 // integer combine opportunities since most 64-bit operations are decomposed
6189 // this way. TODO: We won't want this for SALU especially if it is an inline
6191 SDValue SITargetLowering::splitBinaryBitConstantOp(
6192 DAGCombinerInfo &DCI,
6194 unsigned Opc, SDValue LHS,
6195 const ConstantSDNode *CRHS) const {
6196 uint64_t Val = CRHS->getZExtValue();
6197 uint32_t ValLo = Lo_32(Val);
6198 uint32_t ValHi = Hi_32(Val);
6199 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6201 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6202 bitOpWithConstantIsReducible(Opc, ValHi)) ||
6203 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6204 // If we need to materialize a 64-bit immediate, it will be split up later
6205 // anyway. Avoid creating the harder to understand 64-bit immediate
6207 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6213 // Returns true if argument is a boolean value which is not serialized into
6214 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6215 static bool isBoolSGPR(SDValue V) {
6216 if (V.getValueType() != MVT::i1)
6218 switch (V.getOpcode()) {
6224 case AMDGPUISD::FP_CLASS:
6230 // If a constant has all zeroes or all ones within each byte return it.
6231 // Otherwise return 0.
6232 static uint32_t getConstantPermuteMask(uint32_t C) {
6233 // 0xff for any zero byte in the mask
6234 uint32_t ZeroByteMask = 0;
6235 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
6236 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
6237 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
6238 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
6239 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
6240 if ((NonZeroByteMask & C) != NonZeroByteMask)
6241 return 0; // Partial bytes selected.
6245 // Check if a node selects whole bytes from its operand 0 starting at a byte
6246 // boundary while masking the rest. Returns select mask as in the v_perm_b32
6247 // or -1 if not succeeded.
6248 // Note byte select encoding:
6249 // value 0-3 selects corresponding source byte;
6250 // value 0xc selects zero;
6251 // value 0xff selects 0xff.
6252 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
6253 assert(V.getValueSizeInBits() == 32);
6255 if (V.getNumOperands() != 2)
6258 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
6262 uint32_t C = N1->getZExtValue();
6264 switch (V.getOpcode()) {
6268 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6269 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
6274 if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6275 return (0x03020100 & ~ConstMask) | ConstMask;
6283 return uint32_t((0x030201000c0c0c0cull << C) >> 32);
6289 return uint32_t(0x0c0c0c0c03020100ull >> C);
6295 SDValue SITargetLowering::performAndCombine(SDNode *N,
6296 DAGCombinerInfo &DCI) const {
6297 if (DCI.isBeforeLegalize())
6300 SelectionDAG &DAG = DCI.DAG;
6301 EVT VT = N->getValueType(0);
6302 SDValue LHS = N->getOperand(0);
6303 SDValue RHS = N->getOperand(1);
6306 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6307 if (VT == MVT::i64 && CRHS) {
6309 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6313 if (CRHS && VT == MVT::i32) {
6314 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6315 // nb = number of trailing zeroes in mask
6316 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6317 // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6318 uint64_t Mask = CRHS->getZExtValue();
6319 unsigned Bits = countPopulation(Mask);
6320 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6321 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6322 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6323 unsigned Shift = CShift->getZExtValue();
6324 unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6325 unsigned Offset = NB + Shift;
6326 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6328 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6330 DAG.getConstant(Offset, SL, MVT::i32),
6331 DAG.getConstant(Bits, SL, MVT::i32));
6332 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6333 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6334 DAG.getValueType(NarrowVT));
6335 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6336 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6342 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6343 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
6344 isa<ConstantSDNode>(LHS.getOperand(2))) {
6345 uint32_t Sel = getConstantPermuteMask(Mask);
6349 // Select 0xc for all zero bytes
6350 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
6352 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6353 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6357 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6358 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6359 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6360 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6361 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6363 SDValue X = LHS.getOperand(0);
6364 SDValue Y = RHS.getOperand(0);
6365 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6368 if (LCC == ISD::SETO) {
6369 if (X != LHS.getOperand(1))
6372 if (RCC == ISD::SETUNE) {
6373 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6374 if (!C1 || !C1->isInfinity() || C1->isNegative())
6377 const uint32_t Mask = SIInstrFlags::N_NORMAL |
6378 SIInstrFlags::N_SUBNORMAL |
6379 SIInstrFlags::N_ZERO |
6380 SIInstrFlags::P_ZERO |
6381 SIInstrFlags::P_SUBNORMAL |
6382 SIInstrFlags::P_NORMAL;
6384 static_assert(((~(SIInstrFlags::S_NAN |
6385 SIInstrFlags::Q_NAN |
6386 SIInstrFlags::N_INFINITY |
6387 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6391 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6392 X, DAG.getConstant(Mask, DL, MVT::i32));
6397 if (VT == MVT::i32 &&
6398 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6399 // and x, (sext cc from i1) => select cc, x, 0
6400 if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6401 std::swap(LHS, RHS);
6402 if (isBoolSGPR(RHS.getOperand(0)))
6403 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6404 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6407 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6408 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6409 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6410 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6411 uint32_t LHSMask = getPermuteMask(DAG, LHS);
6412 uint32_t RHSMask = getPermuteMask(DAG, RHS);
6413 if (LHSMask != ~0u && RHSMask != ~0u) {
6414 // Canonicalize the expression in an attempt to have fewer unique masks
6415 // and therefore fewer registers used to hold the masks.
6416 if (LHSMask > RHSMask) {
6417 std::swap(LHSMask, RHSMask);
6418 std::swap(LHS, RHS);
6421 // Select 0xc for each lane used from source operand. Zero has 0xc mask
6422 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6423 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6424 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6426 // Check of we need to combine values from two sources within a byte.
6427 if (!(LHSUsedLanes & RHSUsedLanes) &&
6428 // If we select high and lower word keep it for SDWA.
6429 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6430 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6431 // Each byte in each mask is either selector mask 0-3, or has higher
6432 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
6433 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
6434 // mask which is not 0xff wins. By anding both masks we have a correct
6435 // result except that 0x0c shall be corrected to give 0x0c only.
6436 uint32_t Mask = LHSMask & RHSMask;
6437 for (unsigned I = 0; I < 32; I += 8) {
6438 uint32_t ByteSel = 0xff << I;
6439 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
6440 Mask &= (0x0c << I) & 0xffffffff;
6443 // Add 4 to each active LHS lane. It will not affect any existing 0xff
6445 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
6448 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6449 LHS.getOperand(0), RHS.getOperand(0),
6450 DAG.getConstant(Sel, DL, MVT::i32));
6458 SDValue SITargetLowering::performOrCombine(SDNode *N,
6459 DAGCombinerInfo &DCI) const {
6460 SelectionDAG &DAG = DCI.DAG;
6461 SDValue LHS = N->getOperand(0);
6462 SDValue RHS = N->getOperand(1);
6464 EVT VT = N->getValueType(0);
6465 if (VT == MVT::i1) {
6466 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6467 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6468 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6469 SDValue Src = LHS.getOperand(0);
6470 if (Src != RHS.getOperand(0))
6473 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6474 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6478 // Only 10 bits are used.
6479 static const uint32_t MaxMask = 0x3ff;
6481 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6483 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6484 Src, DAG.getConstant(NewMask, DL, MVT::i32));
6490 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6491 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
6492 LHS.getOpcode() == AMDGPUISD::PERM &&
6493 isa<ConstantSDNode>(LHS.getOperand(2))) {
6494 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
6498 Sel |= LHS.getConstantOperandVal(2);
6500 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6501 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6504 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6505 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6506 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6507 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6508 uint32_t LHSMask = getPermuteMask(DAG, LHS);
6509 uint32_t RHSMask = getPermuteMask(DAG, RHS);
6510 if (LHSMask != ~0u && RHSMask != ~0u) {
6511 // Canonicalize the expression in an attempt to have fewer unique masks
6512 // and therefore fewer registers used to hold the masks.
6513 if (LHSMask > RHSMask) {
6514 std::swap(LHSMask, RHSMask);
6515 std::swap(LHS, RHS);
6518 // Select 0xc for each lane used from source operand. Zero has 0xc mask
6519 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6520 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6521 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6523 // Check of we need to combine values from two sources within a byte.
6524 if (!(LHSUsedLanes & RHSUsedLanes) &&
6525 // If we select high and lower word keep it for SDWA.
6526 // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6527 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6528 // Kill zero bytes selected by other mask. Zero value is 0xc.
6529 LHSMask &= ~RHSUsedLanes;
6530 RHSMask &= ~LHSUsedLanes;
6531 // Add 4 to each active LHS lane
6532 LHSMask |= LHSUsedLanes & 0x04040404;
6534 uint32_t Sel = LHSMask | RHSMask;
6537 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6538 LHS.getOperand(0), RHS.getOperand(0),
6539 DAG.getConstant(Sel, DL, MVT::i32));
6547 // TODO: This could be a generic combine with a predicate for extracting the
6548 // high half of an integer being free.
6550 // (or i64:x, (zero_extend i32:y)) ->
6551 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6552 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6553 RHS.getOpcode() != ISD::ZERO_EXTEND)
6554 std::swap(LHS, RHS);
6556 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6557 SDValue ExtSrc = RHS.getOperand(0);
6558 EVT SrcVT = ExtSrc.getValueType();
6559 if (SrcVT == MVT::i32) {
6561 SDValue LowLHS, HiBits;
6562 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6563 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6565 DCI.AddToWorklist(LowOr.getNode());
6566 DCI.AddToWorklist(HiBits.getNode());
6568 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6570 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6574 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6577 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6584 SDValue SITargetLowering::performXorCombine(SDNode *N,
6585 DAGCombinerInfo &DCI) const {
6586 EVT VT = N->getValueType(0);
6590 SDValue LHS = N->getOperand(0);
6591 SDValue RHS = N->getOperand(1);
6593 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6596 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6603 // Instructions that will be lowered with a final instruction that zeros the
6604 // high result bits.
6605 // XXX - probably only need to list legal operations.
6606 static bool fp16SrcZerosHighBits(unsigned Opc) {
6615 case ISD::FCANONICALIZE:
6617 case ISD::UINT_TO_FP:
6618 case ISD::SINT_TO_FP:
6620 // Fabs is lowered to a bit operation, but it's an and which will clear the
6621 // high bits anyway.
6635 case ISD::FNEARBYINT:
6640 case AMDGPUISD::FRACT:
6641 case AMDGPUISD::CLAMP:
6642 case AMDGPUISD::COS_HW:
6643 case AMDGPUISD::SIN_HW:
6644 case AMDGPUISD::FMIN3:
6645 case AMDGPUISD::FMAX3:
6646 case AMDGPUISD::FMED3:
6647 case AMDGPUISD::FMAD_FTZ:
6648 case AMDGPUISD::RCP:
6649 case AMDGPUISD::RSQ:
6650 case AMDGPUISD::RCP_IFLAG:
6651 case AMDGPUISD::LDEXP:
6654 // fcopysign, select and others may be lowered to 32-bit bit operations
6655 // which don't zero the high bits.
6660 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6661 DAGCombinerInfo &DCI) const {
6662 if (!Subtarget->has16BitInsts() ||
6663 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6666 EVT VT = N->getValueType(0);
6670 SDValue Src = N->getOperand(0);
6671 if (Src.getValueType() != MVT::i16)
6674 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6675 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6676 if (Src.getOpcode() == ISD::BITCAST) {
6677 SDValue BCSrc = Src.getOperand(0);
6678 if (BCSrc.getValueType() == MVT::f16 &&
6679 fp16SrcZerosHighBits(BCSrc.getOpcode()))
6680 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6686 SDValue SITargetLowering::performClassCombine(SDNode *N,
6687 DAGCombinerInfo &DCI) const {
6688 SelectionDAG &DAG = DCI.DAG;
6689 SDValue Mask = N->getOperand(1);
6691 // fp_class x, 0 -> false
6692 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6693 if (CMask->isNullValue())
6694 return DAG.getConstant(0, SDLoc(N), MVT::i1);
6697 if (N->getOperand(0).isUndef())
6698 return DAG.getUNDEF(MVT::i1);
6703 SDValue SITargetLowering::performRcpCombine(SDNode *N,
6704 DAGCombinerInfo &DCI) const {
6705 EVT VT = N->getValueType(0);
6706 SDValue N0 = N->getOperand(0);
6711 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
6712 N0.getOpcode() == ISD::SINT_TO_FP)) {
6713 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
6717 return AMDGPUTargetLowering::performRcpCombine(N, DCI);
6720 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6721 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6724 return DAG.isKnownNeverNaN(Op);
6727 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6728 const GCNSubtarget *ST, unsigned MaxDepth=5) {
6729 // If source is a result of another standard FP operation it is already in
6732 switch (Op.getOpcode()) {
6736 // These will flush denorms if required.
6746 case ISD::FCANONICALIZE:
6750 return Op.getValueType().getScalarType() != MVT::f16 ||
6751 ST->hasFP16Denormals();
6753 case ISD::FP_EXTEND:
6754 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6755 ST->hasFP16Denormals();
6757 case ISD::FP16_TO_FP:
6758 case ISD::FP_TO_FP16:
6759 return ST->hasFP16Denormals();
6761 // It can/will be lowered or combined as a bit operation.
6762 // Need to check their input recursively to handle.
6765 return (MaxDepth > 0) &&
6766 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6771 return Op.getValueType().getScalarType() != MVT::f16;
6773 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6774 // For such targets need to check their input recursively.
6780 if (ST->supportsMinMaxDenormModes() &&
6781 DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6782 DAG.isKnownNeverNaN(Op.getOperand(1)))
6785 return (MaxDepth > 0) &&
6786 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6787 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6789 case ISD::ConstantFP: {
6790 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6791 return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6797 // Constant fold canonicalize.
6798 SDValue SITargetLowering::performFCanonicalizeCombine(
6800 DAGCombinerInfo &DCI) const {
6801 SelectionDAG &DAG = DCI.DAG;
6802 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
6805 SDValue N0 = N->getOperand(0);
6806 EVT VT = N0.getValueType().getScalarType();
6807 auto ST = getSubtarget();
6809 if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6810 (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6811 (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6812 DAG.isKnownNeverNaN(N0))
6815 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6817 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6818 isCanonicalized(DAG, N0, ST))
6824 const APFloat &C = CFP->getValueAPF();
6826 // Flush denormals to 0 if not enabled.
6827 if (C.isDenormal()) {
6828 EVT VT = N->getValueType(0);
6829 EVT SVT = VT.getScalarType();
6830 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6831 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6833 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6834 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6836 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6837 return DAG.getConstantFP(0.0, SDLoc(N), VT);
6841 EVT VT = N->getValueType(0);
6842 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6843 if (C.isSignaling()) {
6844 // Quiet a signaling NaN.
6845 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6848 // Make sure it is the canonical NaN bitpattern.
6850 // TODO: Can we use -1 as the canonical NaN value since it's an inline
6852 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6853 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6856 return N->getOperand(0);
6859 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6862 return AMDGPUISD::FMAX3;
6864 return AMDGPUISD::SMAX3;
6866 return AMDGPUISD::UMAX3;
6868 return AMDGPUISD::FMIN3;
6870 return AMDGPUISD::SMIN3;
6872 return AMDGPUISD::UMIN3;
6874 llvm_unreachable("Not a min/max opcode");
6878 SDValue SITargetLowering::performIntMed3ImmCombine(
6879 SelectionDAG &DAG, const SDLoc &SL,
6880 SDValue Op0, SDValue Op1, bool Signed) const {
6881 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6885 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6890 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6893 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6897 EVT VT = K0->getValueType(0);
6898 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6899 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6900 return DAG.getNode(Med3Opc, SL, VT,
6901 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6904 // If there isn't a 16-bit med3 operation, convert to 32-bit.
6906 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6908 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6909 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6910 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6912 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6913 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6916 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6917 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6920 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6921 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6928 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6931 SDValue Op1) const {
6932 ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6936 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6940 // Ordered >= (although NaN inputs should have folded away by now).
6941 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6942 if (Cmp == APFloat::cmpGreaterThan)
6945 // TODO: Check IEEE bit enabled?
6946 EVT VT = Op0.getValueType();
6947 if (Subtarget->enableDX10Clamp()) {
6948 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6949 // hardware fmed3 behavior converting to a min.
6950 // FIXME: Should this be allowing -0.0?
6951 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6952 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6955 // med3 for f16 is only available on gfx9+, and not available for v2f16.
6956 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6957 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6958 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6959 // then give the other result, which is different from med3 with a NaN
6961 SDValue Var = Op0.getOperand(0);
6962 if (!isKnownNeverSNan(DAG, Var))
6965 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6966 Var, SDValue(K0, 0), SDValue(K1, 0));
6972 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6973 DAGCombinerInfo &DCI) const {
6974 SelectionDAG &DAG = DCI.DAG;
6976 EVT VT = N->getValueType(0);
6977 unsigned Opc = N->getOpcode();
6978 SDValue Op0 = N->getOperand(0);
6979 SDValue Op1 = N->getOperand(1);
6981 // Only do this if the inner op has one use since this will just increases
6982 // register pressure for no benefit.
6985 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6986 !VT.isVector() && VT != MVT::f64 &&
6987 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6988 // max(max(a, b), c) -> max3(a, b, c)
6989 // min(min(a, b), c) -> min3(a, b, c)
6990 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6992 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
7001 // max(a, max(b, c)) -> max3(a, b, c)
7002 // min(a, min(b, c)) -> min3(a, b, c)
7003 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
7005 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
7014 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
7015 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
7016 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
7020 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
7021 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
7025 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
7026 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
7027 (Opc == AMDGPUISD::FMIN_LEGACY &&
7028 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
7029 (VT == MVT::f32 || VT == MVT::f64 ||
7030 (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
7031 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
7033 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
7040 static bool isClampZeroToOne(SDValue A, SDValue B) {
7041 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
7042 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
7043 // FIXME: Should this be allowing -0.0?
7044 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
7045 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
7052 // FIXME: Should only worry about snans for version with chain.
7053 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
7054 DAGCombinerInfo &DCI) const {
7055 EVT VT = N->getValueType(0);
7056 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
7057 // NaNs. With a NaN input, the order of the operands may change the result.
7059 SelectionDAG &DAG = DCI.DAG;
7062 SDValue Src0 = N->getOperand(0);
7063 SDValue Src1 = N->getOperand(1);
7064 SDValue Src2 = N->getOperand(2);
7066 if (isClampZeroToOne(Src0, Src1)) {
7067 // const_a, const_b, x -> clamp is safe in all cases including signaling
7069 // FIXME: Should this be allowing -0.0?
7070 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
7073 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
7074 // handling no dx10-clamp?
7075 if (Subtarget->enableDX10Clamp()) {
7076 // If NaNs is clamped to 0, we are free to reorder the inputs.
7078 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7079 std::swap(Src0, Src1);
7081 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
7082 std::swap(Src1, Src2);
7084 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7085 std::swap(Src0, Src1);
7087 if (isClampZeroToOne(Src1, Src2))
7088 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
7094 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
7095 DAGCombinerInfo &DCI) const {
7096 SDValue Src0 = N->getOperand(0);
7097 SDValue Src1 = N->getOperand(1);
7098 if (Src0.isUndef() && Src1.isUndef())
7099 return DCI.DAG.getUNDEF(N->getValueType(0));
7103 SDValue SITargetLowering::performExtractVectorEltCombine(
7104 SDNode *N, DAGCombinerInfo &DCI) const {
7105 SDValue Vec = N->getOperand(0);
7106 SelectionDAG &DAG = DCI.DAG;
7108 EVT VecVT = Vec.getValueType();
7109 EVT EltVT = VecVT.getVectorElementType();
7111 if ((Vec.getOpcode() == ISD::FNEG ||
7112 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
7114 EVT EltVT = N->getValueType(0);
7115 SDValue Idx = N->getOperand(1);
7116 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7117 Vec.getOperand(0), Idx);
7118 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
7121 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
7123 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
7124 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
7125 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
7126 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
7128 EVT EltVT = N->getValueType(0);
7129 SDValue Idx = N->getOperand(1);
7130 unsigned Opc = Vec.getOpcode();
7135 // TODO: Support other binary operations.
7144 return DAG.getNode(Opc, SL, EltVT,
7145 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7146 Vec.getOperand(0), Idx),
7147 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7148 Vec.getOperand(1), Idx));
7152 if (!DCI.isBeforeLegalize())
7155 unsigned VecSize = VecVT.getSizeInBits();
7156 unsigned EltSize = EltVT.getSizeInBits();
7158 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
7159 // elements. This exposes more load reduction opportunities by replacing
7160 // multiple small extract_vector_elements with a single 32-bit extract.
7161 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7162 if (EltSize <= 16 &&
7163 EltVT.isByteSized() &&
7165 VecSize % 32 == 0 &&
7167 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
7169 unsigned BitIndex = Idx->getZExtValue() * EltSize;
7170 unsigned EltIdx = BitIndex / 32;
7171 unsigned LeftoverBitIdx = BitIndex % 32;
7174 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
7175 DCI.AddToWorklist(Cast.getNode());
7177 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
7178 DAG.getConstant(EltIdx, SL, MVT::i32));
7179 DCI.AddToWorklist(Elt.getNode());
7180 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
7181 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
7182 DCI.AddToWorklist(Srl.getNode());
7184 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
7185 DCI.AddToWorklist(Trunc.getNode());
7186 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
7192 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
7193 SDValue &Lo, SDValue &Hi) {
7194 if (Hi.getOpcode() == ISD::BITCAST &&
7195 Hi.getOperand(0).getValueType() == MVT::f16 &&
7196 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
7197 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
7198 Hi = Hi.getOperand(0);
7205 SDValue SITargetLowering::performBuildVectorCombine(
7206 SDNode *N, DAGCombinerInfo &DCI) const {
7209 if (!isTypeLegal(MVT::v2i16))
7211 SelectionDAG &DAG = DCI.DAG;
7212 EVT VT = N->getValueType(0);
7214 if (VT == MVT::v2i16) {
7215 SDValue Lo = N->getOperand(0);
7216 SDValue Hi = N->getOperand(1);
7218 // v2i16 build_vector (const|undef), (bitcast f16:$x)
7219 // -> bitcast (v2f16 build_vector const|undef, $x
7220 if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
7221 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi });
7222 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7225 if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
7226 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo });
7227 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7234 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
7236 const SDNode *N1) const {
7237 EVT VT = N0->getValueType(0);
7239 // Only do this if we are not trying to support denormals. v_mad_f32 does not
7240 // support denormals ever.
7241 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
7242 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
7245 const TargetOptions &Options = DAG.getTarget().Options;
7246 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7247 (N0->getFlags().hasAllowContract() &&
7248 N1->getFlags().hasAllowContract())) &&
7249 isFMAFasterThanFMulAndFAdd(VT)) {
7256 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
7258 SDValue N0, SDValue N1, SDValue N2,
7260 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
7261 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
7262 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
7263 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
7266 SDValue SITargetLowering::performAddCombine(SDNode *N,
7267 DAGCombinerInfo &DCI) const {
7268 SelectionDAG &DAG = DCI.DAG;
7269 EVT VT = N->getValueType(0);
7271 SDValue LHS = N->getOperand(0);
7272 SDValue RHS = N->getOperand(1);
7274 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
7275 && Subtarget->hasMad64_32() &&
7276 !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
7277 VT.getScalarSizeInBits() <= 64) {
7278 if (LHS.getOpcode() != ISD::MUL)
7279 std::swap(LHS, RHS);
7281 SDValue MulLHS = LHS.getOperand(0);
7282 SDValue MulRHS = LHS.getOperand(1);
7283 SDValue AddRHS = RHS;
7285 // TODO: Maybe restrict if SGPR inputs.
7286 if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
7287 numBitsUnsigned(MulRHS, DAG) <= 32) {
7288 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
7289 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
7290 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
7291 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
7294 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
7295 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
7296 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
7297 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
7298 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
7304 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
7307 // add x, zext (setcc) => addcarry x, 0, setcc
7308 // add x, sext (setcc) => subcarry x, 0, setcc
7309 unsigned Opc = LHS.getOpcode();
7310 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
7311 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
7312 std::swap(RHS, LHS);
7314 Opc = RHS.getOpcode();
7317 case ISD::ZERO_EXTEND:
7318 case ISD::SIGN_EXTEND:
7319 case ISD::ANY_EXTEND: {
7320 auto Cond = RHS.getOperand(0);
7321 if (!isBoolSGPR(Cond))
7323 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
7324 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
7325 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
7326 return DAG.getNode(Opc, SL, VTList, Args);
7328 case ISD::ADDCARRY: {
7329 // add x, (addcarry y, 0, cc) => addcarry x, y, cc
7330 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7331 if (!C || C->getZExtValue() != 0) break;
7332 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
7333 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
7339 SDValue SITargetLowering::performSubCombine(SDNode *N,
7340 DAGCombinerInfo &DCI) const {
7341 SelectionDAG &DAG = DCI.DAG;
7342 EVT VT = N->getValueType(0);
7348 SDValue LHS = N->getOperand(0);
7349 SDValue RHS = N->getOperand(1);
7351 unsigned Opc = LHS.getOpcode();
7352 if (Opc != ISD::SUBCARRY)
7353 std::swap(RHS, LHS);
7355 if (LHS.getOpcode() == ISD::SUBCARRY) {
7356 // sub (subcarry x, 0, cc), y => subcarry x, y, cc
7357 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7358 if (!C || C->getZExtValue() != 0)
7360 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
7361 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
7366 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
7367 DAGCombinerInfo &DCI) const {
7369 if (N->getValueType(0) != MVT::i32)
7372 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7373 if (!C || C->getZExtValue() != 0)
7376 SelectionDAG &DAG = DCI.DAG;
7377 SDValue LHS = N->getOperand(0);
7379 // addcarry (add x, y), 0, cc => addcarry x, y, cc
7380 // subcarry (sub x, y), 0, cc => subcarry x, y, cc
7381 unsigned LHSOpc = LHS.getOpcode();
7382 unsigned Opc = N->getOpcode();
7383 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
7384 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
7385 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
7386 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
7391 SDValue SITargetLowering::performFAddCombine(SDNode *N,
7392 DAGCombinerInfo &DCI) const {
7393 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7396 SelectionDAG &DAG = DCI.DAG;
7397 EVT VT = N->getValueType(0);
7400 SDValue LHS = N->getOperand(0);
7401 SDValue RHS = N->getOperand(1);
7403 // These should really be instruction patterns, but writing patterns with
7404 // source modiifiers is a pain.
7406 // fadd (fadd (a, a), b) -> mad 2.0, a, b
7407 if (LHS.getOpcode() == ISD::FADD) {
7408 SDValue A = LHS.getOperand(0);
7409 if (A == LHS.getOperand(1)) {
7410 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7412 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7413 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
7418 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
7419 if (RHS.getOpcode() == ISD::FADD) {
7420 SDValue A = RHS.getOperand(0);
7421 if (A == RHS.getOperand(1)) {
7422 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7424 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7425 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
7433 SDValue SITargetLowering::performFSubCombine(SDNode *N,
7434 DAGCombinerInfo &DCI) const {
7435 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7438 SelectionDAG &DAG = DCI.DAG;
7440 EVT VT = N->getValueType(0);
7441 assert(!VT.isVector());
7443 // Try to get the fneg to fold into the source modifier. This undoes generic
7444 // DAG combines and folds them into the mad.
7446 // Only do this if we are not trying to support denormals. v_mad_f32 does
7447 // not support denormals ever.
7448 SDValue LHS = N->getOperand(0);
7449 SDValue RHS = N->getOperand(1);
7450 if (LHS.getOpcode() == ISD::FADD) {
7451 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7452 SDValue A = LHS.getOperand(0);
7453 if (A == LHS.getOperand(1)) {
7454 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7456 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7457 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7459 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7464 if (RHS.getOpcode() == ISD::FADD) {
7465 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7467 SDValue A = RHS.getOperand(0);
7468 if (A == RHS.getOperand(1)) {
7469 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7471 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7472 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7480 SDValue SITargetLowering::performFMACombine(SDNode *N,
7481 DAGCombinerInfo &DCI) const {
7482 SelectionDAG &DAG = DCI.DAG;
7483 EVT VT = N->getValueType(0);
7486 if (!Subtarget->hasDLInsts() || VT != MVT::f32)
7489 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
7490 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
7491 SDValue Op1 = N->getOperand(0);
7492 SDValue Op2 = N->getOperand(1);
7493 SDValue FMA = N->getOperand(2);
7495 if (FMA.getOpcode() != ISD::FMA ||
7496 Op1.getOpcode() != ISD::FP_EXTEND ||
7497 Op2.getOpcode() != ISD::FP_EXTEND)
7500 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
7501 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
7502 // is sufficient to allow generaing fdot2.
7503 const TargetOptions &Options = DAG.getTarget().Options;
7504 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7505 (N->getFlags().hasAllowContract() &&
7506 FMA->getFlags().hasAllowContract())) {
7507 Op1 = Op1.getOperand(0);
7508 Op2 = Op2.getOperand(0);
7509 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7510 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7513 SDValue Vec1 = Op1.getOperand(0);
7514 SDValue Idx1 = Op1.getOperand(1);
7515 SDValue Vec2 = Op2.getOperand(0);
7517 SDValue FMAOp1 = FMA.getOperand(0);
7518 SDValue FMAOp2 = FMA.getOperand(1);
7519 SDValue FMAAcc = FMA.getOperand(2);
7521 if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
7522 FMAOp2.getOpcode() != ISD::FP_EXTEND)
7525 FMAOp1 = FMAOp1.getOperand(0);
7526 FMAOp2 = FMAOp2.getOperand(0);
7527 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7528 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7531 SDValue Vec3 = FMAOp1.getOperand(0);
7532 SDValue Vec4 = FMAOp2.getOperand(0);
7533 SDValue Idx2 = FMAOp1.getOperand(1);
7535 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
7536 // Idx1 and Idx2 cannot be the same.
7540 if (Vec1 == Vec2 || Vec3 == Vec4)
7543 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
7546 if ((Vec1 == Vec3 && Vec2 == Vec4) ||
7547 (Vec1 == Vec4 && Vec2 == Vec3))
7548 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc);
7553 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7554 DAGCombinerInfo &DCI) const {
7555 SelectionDAG &DAG = DCI.DAG;
7558 SDValue LHS = N->getOperand(0);
7559 SDValue RHS = N->getOperand(1);
7560 EVT VT = LHS.getValueType();
7561 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7563 auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7565 CRHS = dyn_cast<ConstantSDNode>(LHS);
7567 std::swap(LHS, RHS);
7568 CC = getSetCCSwappedOperands(CC);
7573 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7574 isBoolSGPR(LHS.getOperand(0))) {
7575 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7576 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7577 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
7578 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
7579 if ((CRHS->isAllOnesValue() &&
7580 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7581 (CRHS->isNullValue() &&
7582 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7583 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7584 DAG.getConstant(-1, SL, MVT::i1));
7585 if ((CRHS->isAllOnesValue() &&
7586 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7587 (CRHS->isNullValue() &&
7588 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7589 return LHS.getOperand(0);
7592 uint64_t CRHSVal = CRHS->getZExtValue();
7593 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7594 LHS.getOpcode() == ISD::SELECT &&
7595 isa<ConstantSDNode>(LHS.getOperand(1)) &&
7596 isa<ConstantSDNode>(LHS.getOperand(2)) &&
7597 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
7598 isBoolSGPR(LHS.getOperand(0))) {
7600 // setcc (select cc, CT, CF), CF, eq => xor cc, -1
7601 // setcc (select cc, CT, CF), CF, ne => cc
7602 // setcc (select cc, CT, CF), CT, ne => xor cc, -1
7603 // setcc (select cc, CT, CF), CT, eq => cc
7604 uint64_t CT = LHS.getConstantOperandVal(1);
7605 uint64_t CF = LHS.getConstantOperandVal(2);
7607 if ((CF == CRHSVal && CC == ISD::SETEQ) ||
7608 (CT == CRHSVal && CC == ISD::SETNE))
7609 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7610 DAG.getConstant(-1, SL, MVT::i1));
7611 if ((CF == CRHSVal && CC == ISD::SETNE) ||
7612 (CT == CRHSVal && CC == ISD::SETEQ))
7613 return LHS.getOperand(0);
7617 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7621 // Match isinf pattern
7622 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7623 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7624 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7628 const APFloat &APF = CRHS->getValueAPF();
7629 if (APF.isInfinity() && !APF.isNegative()) {
7630 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7631 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7632 DAG.getConstant(Mask, SL, MVT::i32));
7639 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7640 DAGCombinerInfo &DCI) const {
7641 SelectionDAG &DAG = DCI.DAG;
7643 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7645 SDValue Src = N->getOperand(0);
7646 SDValue Srl = N->getOperand(0);
7647 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7648 Srl = Srl.getOperand(0);
7650 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7651 if (Srl.getOpcode() == ISD::SRL) {
7652 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7653 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7654 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7656 if (const ConstantSDNode *C =
7657 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7658 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7661 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7662 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7663 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7669 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7672 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7673 !DCI.isBeforeLegalizeOps());
7674 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7675 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7676 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7677 DCI.CommitTargetLoweringOpt(TLO);
7683 SDValue SITargetLowering::performClampCombine(SDNode *N,
7684 DAGCombinerInfo &DCI) const {
7685 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
7689 const APFloat &F = CSrc->getValueAPF();
7690 APFloat Zero = APFloat::getZero(F.getSemantics());
7691 APFloat::cmpResult Cmp0 = F.compare(Zero);
7692 if (Cmp0 == APFloat::cmpLessThan ||
7693 (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
7694 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
7697 APFloat One(F.getSemantics(), "1.0");
7698 APFloat::cmpResult Cmp1 = F.compare(One);
7699 if (Cmp1 == APFloat::cmpGreaterThan)
7700 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
7702 return SDValue(CSrc, 0);
7706 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7707 DAGCombinerInfo &DCI) const {
7708 switch (N->getOpcode()) {
7710 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7712 return performAddCombine(N, DCI);
7714 return performSubCombine(N, DCI);
7717 return performAddCarrySubCarryCombine(N, DCI);
7719 return performFAddCombine(N, DCI);
7721 return performFSubCombine(N, DCI);
7723 return performSetCCCombine(N, DCI);
7730 case AMDGPUISD::FMIN_LEGACY:
7731 case AMDGPUISD::FMAX_LEGACY: {
7732 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7733 getTargetMachine().getOptLevel() > CodeGenOpt::None)
7734 return performMinMaxCombine(N, DCI);
7738 return performFMACombine(N, DCI);
7740 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
7745 case ISD::ATOMIC_LOAD:
7746 case ISD::ATOMIC_STORE:
7747 case ISD::ATOMIC_CMP_SWAP:
7748 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7749 case ISD::ATOMIC_SWAP:
7750 case ISD::ATOMIC_LOAD_ADD:
7751 case ISD::ATOMIC_LOAD_SUB:
7752 case ISD::ATOMIC_LOAD_AND:
7753 case ISD::ATOMIC_LOAD_OR:
7754 case ISD::ATOMIC_LOAD_XOR:
7755 case ISD::ATOMIC_LOAD_NAND:
7756 case ISD::ATOMIC_LOAD_MIN:
7757 case ISD::ATOMIC_LOAD_MAX:
7758 case ISD::ATOMIC_LOAD_UMIN:
7759 case ISD::ATOMIC_LOAD_UMAX:
7760 case AMDGPUISD::ATOMIC_INC:
7761 case AMDGPUISD::ATOMIC_DEC:
7762 case AMDGPUISD::ATOMIC_LOAD_FADD:
7763 case AMDGPUISD::ATOMIC_LOAD_FMIN:
7764 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
7765 if (DCI.isBeforeLegalize())
7767 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7769 return performAndCombine(N, DCI);
7771 return performOrCombine(N, DCI);
7773 return performXorCombine(N, DCI);
7774 case ISD::ZERO_EXTEND:
7775 return performZeroExtendCombine(N, DCI);
7776 case AMDGPUISD::FP_CLASS:
7777 return performClassCombine(N, DCI);
7778 case ISD::FCANONICALIZE:
7779 return performFCanonicalizeCombine(N, DCI);
7780 case AMDGPUISD::RCP:
7781 return performRcpCombine(N, DCI);
7782 case AMDGPUISD::FRACT:
7783 case AMDGPUISD::RSQ:
7784 case AMDGPUISD::RCP_LEGACY:
7785 case AMDGPUISD::RSQ_LEGACY:
7786 case AMDGPUISD::RCP_IFLAG:
7787 case AMDGPUISD::RSQ_CLAMP:
7788 case AMDGPUISD::LDEXP: {
7789 SDValue Src = N->getOperand(0);
7794 case ISD::SINT_TO_FP:
7795 case ISD::UINT_TO_FP:
7796 return performUCharToFloatCombine(N, DCI);
7797 case AMDGPUISD::CVT_F32_UBYTE0:
7798 case AMDGPUISD::CVT_F32_UBYTE1:
7799 case AMDGPUISD::CVT_F32_UBYTE2:
7800 case AMDGPUISD::CVT_F32_UBYTE3:
7801 return performCvtF32UByteNCombine(N, DCI);
7802 case AMDGPUISD::FMED3:
7803 return performFMed3Combine(N, DCI);
7804 case AMDGPUISD::CVT_PKRTZ_F16_F32:
7805 return performCvtPkRTZCombine(N, DCI);
7806 case AMDGPUISD::CLAMP:
7807 return performClampCombine(N, DCI);
7808 case ISD::SCALAR_TO_VECTOR: {
7809 SelectionDAG &DAG = DCI.DAG;
7810 EVT VT = N->getValueType(0);
7812 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7813 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7815 SDValue Src = N->getOperand(0);
7816 EVT EltVT = Src.getValueType();
7817 if (EltVT == MVT::f16)
7818 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7820 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7821 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7826 case ISD::EXTRACT_VECTOR_ELT:
7827 return performExtractVectorEltCombine(N, DCI);
7828 case ISD::BUILD_VECTOR:
7829 return performBuildVectorCombine(N, DCI);
7831 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7834 /// Helper function for adjustWritemask
7835 static unsigned SubIdx2Lane(unsigned Idx) {
7838 case AMDGPU::sub0: return 0;
7839 case AMDGPU::sub1: return 1;
7840 case AMDGPU::sub2: return 2;
7841 case AMDGPU::sub3: return 3;
7845 /// Adjust the writemask of MIMG instructions
7846 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7847 SelectionDAG &DAG) const {
7848 unsigned Opcode = Node->getMachineOpcode();
7850 // Subtract 1 because the vdata output is not a MachineSDNode operand.
7851 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
7852 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
7853 return Node; // not implemented for D16
7855 SDNode *Users[4] = { nullptr };
7857 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
7858 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7859 unsigned NewDmask = 0;
7860 bool HasChain = Node->getNumValues() > 1;
7862 if (OldDmask == 0) {
7863 // These are folded out, but on the chance it happens don't assert.
7867 // Try to figure out the used register components
7868 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7871 // Don't look at users of the chain.
7872 if (I.getUse().getResNo() != 0)
7875 // Abort if we can't understand the usage
7876 if (!I->isMachineOpcode() ||
7877 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7880 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7881 // Note that subregs are packed, i.e. Lane==0 is the first bit set
7882 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7884 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7886 // Set which texture component corresponds to the lane.
7888 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7889 Comp = countTrailingZeros(Dmask);
7890 Dmask &= ~(1 << Comp);
7893 // Abort if we have more than one user per component
7898 NewDmask |= 1 << Comp;
7901 // Abort if there's no change
7902 if (NewDmask == OldDmask)
7905 unsigned BitsSet = countPopulation(NewDmask);
7907 int NewOpcode = AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), BitsSet);
7908 assert(NewOpcode != -1 &&
7909 NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7910 "failed to find equivalent MIMG op");
7912 // Adjust the writemask in the node
7913 SmallVector<SDValue, 12> Ops;
7914 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
7915 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
7916 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
7918 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
7920 MVT ResultVT = BitsSet == 1 ?
7921 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
7922 SDVTList NewVTList = HasChain ?
7923 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
7926 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
7931 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
7932 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
7936 assert(Node->hasNUsesOfValue(1, 0));
7937 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
7938 SDLoc(Node), Users[Lane]->getValueType(0),
7939 SDValue(NewNode, 0));
7940 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
7944 // Update the users of the node with the new indices
7945 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
7946 SDNode *User = Users[i];
7950 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
7951 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
7955 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
7956 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
7957 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
7961 DAG.RemoveDeadNode(Node);
7965 static bool isFrameIndexOp(SDValue Op) {
7966 if (Op.getOpcode() == ISD::AssertZext)
7967 Op = Op.getOperand(0);
7969 return isa<FrameIndexSDNode>(Op);
7972 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
7973 /// with frame index operands.
7974 /// LLVM assumes that inputs are to these instructions are registers.
7975 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
7976 SelectionDAG &DAG) const {
7977 if (Node->getOpcode() == ISD::CopyToReg) {
7978 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
7979 SDValue SrcVal = Node->getOperand(2);
7981 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
7982 // to try understanding copies to physical registers.
7983 if (SrcVal.getValueType() == MVT::i1 &&
7984 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
7986 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7987 SDValue VReg = DAG.getRegister(
7988 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
7990 SDNode *Glued = Node->getGluedNode();
7992 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
7993 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
7995 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
7996 VReg, ToVReg.getValue(1));
7997 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
7998 DAG.RemoveDeadNode(Node);
7999 return ToResultReg.getNode();
8003 SmallVector<SDValue, 8> Ops;
8004 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
8005 if (!isFrameIndexOp(Node->getOperand(i))) {
8006 Ops.push_back(Node->getOperand(i));
8011 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
8012 Node->getOperand(i).getValueType(),
8013 Node->getOperand(i)), 0));
8016 return DAG.UpdateNodeOperands(Node, Ops);
8019 /// Fold the instructions after selecting them.
8020 /// Returns null if users were already updated.
8021 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
8022 SelectionDAG &DAG) const {
8023 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8024 unsigned Opcode = Node->getMachineOpcode();
8026 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
8027 !TII->isGather4(Opcode)) {
8028 return adjustWritemask(Node, DAG);
8031 if (Opcode == AMDGPU::INSERT_SUBREG ||
8032 Opcode == AMDGPU::REG_SEQUENCE) {
8033 legalizeTargetIndependentNode(Node, DAG);
8038 case AMDGPU::V_DIV_SCALE_F32:
8039 case AMDGPU::V_DIV_SCALE_F64: {
8040 // Satisfy the operand register constraint when one of the inputs is
8041 // undefined. Ordinarily each undef value will have its own implicit_def of
8042 // a vreg, so force these to use a single register.
8043 SDValue Src0 = Node->getOperand(0);
8044 SDValue Src1 = Node->getOperand(1);
8045 SDValue Src2 = Node->getOperand(2);
8047 if ((Src0.isMachineOpcode() &&
8048 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
8049 (Src0 == Src1 || Src0 == Src2))
8052 MVT VT = Src0.getValueType().getSimpleVT();
8053 const TargetRegisterClass *RC = getRegClassFor(VT);
8055 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
8056 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
8058 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
8059 UndefReg, Src0, SDValue());
8061 // src0 must be the same register as src1 or src2, even if the value is
8062 // undefined, so make sure we don't violate this constraint.
8063 if (Src0.isMachineOpcode() &&
8064 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
8065 if (Src1.isMachineOpcode() &&
8066 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8068 else if (Src2.isMachineOpcode() &&
8069 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
8072 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
8079 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
8080 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
8081 Ops.push_back(Node->getOperand(I));
8083 Ops.push_back(ImpDef.getValue(1));
8084 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
8093 /// Assign the register class depending on the number of
8094 /// bits set in the writemask
8095 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8096 SDNode *Node) const {
8097 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8099 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
8101 if (TII->isVOP3(MI.getOpcode())) {
8102 // Make sure constant bus requirements are respected.
8103 TII->legalizeOperandsVOP3(MRI, MI);
8107 // Replace unused atomics with the no return version.
8108 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
8109 if (NoRetAtomicOp != -1) {
8110 if (!Node->hasAnyUseOfValue(0)) {
8111 MI.setDesc(TII->get(NoRetAtomicOp));
8112 MI.RemoveOperand(0);
8116 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
8117 // instruction, because the return type of these instructions is a vec2 of
8118 // the memory type, so it can be tied to the input operand.
8119 // This means these instructions always have a use, so we need to add a
8120 // special case to check if the atomic has only one extract_subreg use,
8121 // which itself has no uses.
8122 if ((Node->hasNUsesOfValue(1, 0) &&
8123 Node->use_begin()->isMachineOpcode() &&
8124 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
8125 !Node->use_begin()->hasAnyUseOfValue(0))) {
8126 unsigned Def = MI.getOperand(0).getReg();
8128 // Change this into a noret atomic.
8129 MI.setDesc(TII->get(NoRetAtomicOp));
8130 MI.RemoveOperand(0);
8132 // If we only remove the def operand from the atomic instruction, the
8133 // extract_subreg will be left with a use of a vreg without a def.
8134 // So we need to insert an implicit_def to avoid machine verifier
8136 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
8137 TII->get(AMDGPU::IMPLICIT_DEF), Def);
8143 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
8145 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
8146 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
8149 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
8151 SDValue Ptr) const {
8152 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8154 // Build the half of the subregister with the constants before building the
8155 // full 128-bit register. If we are building multiple resource descriptors,
8156 // this will allow CSEing of the 2-component register.
8157 const SDValue Ops0[] = {
8158 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
8159 buildSMovImm32(DAG, DL, 0),
8160 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8161 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
8162 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
8165 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
8166 MVT::v2i32, Ops0), 0);
8168 // Combine the constants and the pointer.
8169 const SDValue Ops1[] = {
8170 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8172 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
8174 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
8177 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
8180 /// Return a resource descriptor with the 'Add TID' bit enabled
8181 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
8182 /// of the resource descriptor) to create an offset, which is added to
8183 /// the resource pointer.
8184 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
8185 SDValue Ptr, uint32_t RsrcDword1,
8186 uint64_t RsrcDword2And3) const {
8187 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
8188 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
8190 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
8191 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
8195 SDValue DataLo = buildSMovImm32(DAG, DL,
8196 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
8197 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
8199 const SDValue Ops[] = {
8200 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8202 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8204 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
8206 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
8208 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
8211 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
8214 //===----------------------------------------------------------------------===//
8215 // SI Inline Assembly Support
8216 //===----------------------------------------------------------------------===//
8218 std::pair<unsigned, const TargetRegisterClass *>
8219 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8220 StringRef Constraint,
8222 const TargetRegisterClass *RC = nullptr;
8223 if (Constraint.size() == 1) {
8224 switch (Constraint[0]) {
8226 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8229 switch (VT.getSizeInBits()) {
8231 return std::make_pair(0U, nullptr);
8234 RC = &AMDGPU::SReg_32_XM0RegClass;
8237 RC = &AMDGPU::SGPR_64RegClass;
8240 RC = &AMDGPU::SReg_128RegClass;
8243 RC = &AMDGPU::SReg_256RegClass;
8246 RC = &AMDGPU::SReg_512RegClass;
8251 switch (VT.getSizeInBits()) {
8253 return std::make_pair(0U, nullptr);
8256 RC = &AMDGPU::VGPR_32RegClass;
8259 RC = &AMDGPU::VReg_64RegClass;
8262 RC = &AMDGPU::VReg_96RegClass;
8265 RC = &AMDGPU::VReg_128RegClass;
8268 RC = &AMDGPU::VReg_256RegClass;
8271 RC = &AMDGPU::VReg_512RegClass;
8276 // We actually support i128, i16 and f16 as inline parameters
8277 // even if they are not reported as legal
8278 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
8279 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
8280 return std::make_pair(0U, RC);
8283 if (Constraint.size() > 1) {
8284 if (Constraint[1] == 'v') {
8285 RC = &AMDGPU::VGPR_32RegClass;
8286 } else if (Constraint[1] == 's') {
8287 RC = &AMDGPU::SGPR_32RegClass;
8292 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
8293 if (!Failed && Idx < RC->getNumRegs())
8294 return std::make_pair(RC->getRegister(Idx), RC);
8297 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8300 SITargetLowering::ConstraintType
8301 SITargetLowering::getConstraintType(StringRef Constraint) const {
8302 if (Constraint.size() == 1) {
8303 switch (Constraint[0]) {
8307 return C_RegisterClass;
8310 return TargetLowering::getConstraintType(Constraint);
8313 // Figure out which registers should be reserved for stack access. Only after
8314 // the function is legalized do we know all of the non-spill stack objects or if
8315 // calls are present.
8316 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
8317 MachineRegisterInfo &MRI = MF.getRegInfo();
8318 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8319 const MachineFrameInfo &MFI = MF.getFrameInfo();
8320 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
8322 if (Info->isEntryFunction()) {
8323 // Callable functions have fixed registers used for stack access.
8324 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
8327 // We have to assume the SP is needed in case there are calls in the function
8328 // during lowering. Calls are only detected after the function is
8329 // lowered. We're about to reserve registers, so don't bother using it if we
8330 // aren't really going to use it.
8331 bool NeedSP = !Info->isEntryFunction() ||
8332 MFI.hasVarSizedObjects() ||
8336 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
8337 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
8339 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
8340 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
8341 Info->getStackPtrOffsetReg()));
8342 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
8345 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
8346 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
8347 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
8348 Info->getScratchWaveOffsetReg());
8350 Info->limitOccupancy(MF);
8352 TargetLoweringBase::finalizeLowering(MF);
8355 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
8357 const APInt &DemandedElts,
8358 const SelectionDAG &DAG,
8359 unsigned Depth) const {
8360 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
8363 if (getSubtarget()->enableHugePrivateBuffer())
8366 // Technically it may be possible to have a dispatch with a single workitem
8367 // that uses the full private memory size, but that's not really useful. We
8368 // can't use vaddr in MUBUF instructions if we don't know the address
8369 // calculation won't overflow, so assume the sign bit is never set.
8370 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
8373 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
8374 FunctionLoweringInfo * FLI, DivergenceAnalysis * DA) const
8376 switch (N->getOpcode()) {
8378 case ISD::CopyFromReg:
8380 const RegisterSDNode *R = nullptr;
8381 if (N->getOpcode() == ISD::Register) {
8382 R = dyn_cast<RegisterSDNode>(N);
8385 R = dyn_cast<RegisterSDNode>(N->getOperand(1));
8389 const MachineFunction * MF = FLI->MF;
8390 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
8391 const MachineRegisterInfo &MRI = MF->getRegInfo();
8392 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
8393 unsigned Reg = R->getReg();
8394 if (TRI.isPhysicalRegister(Reg))
8395 return TRI.isVGPR(MRI, Reg);
8397 if (MRI.isLiveIn(Reg)) {
8398 // workitem.id.x workitem.id.y workitem.id.z
8399 // Any VGPR formal argument is also considered divergent
8400 if (TRI.isVGPR(MRI, Reg))
8402 // Formal arguments of non-entry functions
8403 // are conservatively considered divergent
8404 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
8407 return !DA || DA->isDivergent(FLI->getValueFromVirtualReg(Reg));
8412 const LoadSDNode *L = dyn_cast<LoadSDNode>(N);
8413 if (L->getMemOperand()->getAddrSpace() ==
8414 Subtarget->getAMDGPUAS().PRIVATE_ADDRESS)
8417 case ISD::CALLSEQ_END:
8420 case ISD::INTRINSIC_WO_CHAIN:
8424 return AMDGPU::isIntrinsicSourceOfDivergence(
8425 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
8426 case ISD::INTRINSIC_W_CHAIN:
8427 return AMDGPU::isIntrinsicSourceOfDivergence(
8428 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
8429 // In some cases intrinsics that are a source of divergence have been
8430 // lowered to AMDGPUISD so we also need to check those too.
8431 case AMDGPUISD::INTERP_MOV:
8432 case AMDGPUISD::INTERP_P1:
8433 case AMDGPUISD::INTERP_P2: