1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "AMDGPUIntrinsicInfo.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIDefines.h"
25 #include "SIISelLowering.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Target/TargetCallingConv.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include "llvm/Target/TargetRegisterInfo.h"
85 static cl::opt<bool> EnableVGPRIndexMode(
86 "amdgpu-vgpr-index-mode",
87 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
90 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
91 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
92 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
93 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
94 return AMDGPU::SGPR0 + Reg;
97 llvm_unreachable("Cannot allocate sgpr");
100 SITargetLowering::SITargetLowering(const TargetMachine &TM,
101 const SISubtarget &STI)
102 : AMDGPUTargetLowering(TM, STI) {
103 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
104 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
106 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
107 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
109 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
110 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
111 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
113 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
114 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
116 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
117 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
119 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
120 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
122 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
123 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
125 if (Subtarget->has16BitInsts()) {
126 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
127 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
130 if (Subtarget->hasVOP3PInsts()) {
131 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
132 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
135 computeRegisterProperties(STI.getRegisterInfo());
137 // We need to custom lower vector stores from local memory
138 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
139 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
140 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
141 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
142 setOperationAction(ISD::LOAD, MVT::i1, Custom);
144 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
145 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
146 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
147 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
148 setOperationAction(ISD::STORE, MVT::i1, Custom);
150 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
151 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
152 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
153 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
154 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
155 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
156 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
157 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
158 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
159 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
161 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
162 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
163 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
165 setOperationAction(ISD::SELECT, MVT::i1, Promote);
166 setOperationAction(ISD::SELECT, MVT::i64, Custom);
167 setOperationAction(ISD::SELECT, MVT::f64, Promote);
168 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
170 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
171 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
176 setOperationAction(ISD::SETCC, MVT::i1, Promote);
177 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
178 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
179 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
181 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
182 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
184 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
192 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
194 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
195 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
197 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
199 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
200 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
201 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
203 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
204 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
205 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
206 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
207 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
208 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
210 setOperationAction(ISD::UADDO, MVT::i32, Legal);
211 setOperationAction(ISD::USUBO, MVT::i32, Legal);
213 // We only support LOAD/STORE and vector manipulation ops for vectors
214 // with > 4 elements.
215 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
216 MVT::v2i64, MVT::v2f64}) {
217 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
221 case ISD::BUILD_VECTOR:
223 case ISD::EXTRACT_VECTOR_ELT:
224 case ISD::INSERT_VECTOR_ELT:
225 case ISD::INSERT_SUBVECTOR:
226 case ISD::EXTRACT_SUBVECTOR:
227 case ISD::SCALAR_TO_VECTOR:
229 case ISD::CONCAT_VECTORS:
230 setOperationAction(Op, VT, Custom);
233 setOperationAction(Op, VT, Expand);
239 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
240 // is expanded to avoid having two separate loops in case the index is a VGPR.
242 // Most operations are naturally 32-bit vector operations. We only support
243 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
244 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
245 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
246 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
248 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
249 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
251 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
252 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
254 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
255 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
258 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
259 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
260 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
261 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
263 // Avoid stack access for these.
264 // TODO: Generalize to more vector types.
265 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
266 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
267 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
270 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
271 // and output demarshalling
272 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
273 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
275 // We can't return success/failure, only the old value,
276 // let LLVM add the comparison
277 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
278 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
280 if (getSubtarget()->hasFlatAddressSpace()) {
281 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
282 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
285 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
286 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
288 // On SI this is s_memtime and s_memrealtime on VI.
289 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
291 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
293 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
294 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
296 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
297 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
298 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
299 setOperationAction(ISD::FRINT, MVT::f64, Legal);
302 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
304 setOperationAction(ISD::FSIN, MVT::f32, Custom);
305 setOperationAction(ISD::FCOS, MVT::f32, Custom);
306 setOperationAction(ISD::FDIV, MVT::f32, Custom);
307 setOperationAction(ISD::FDIV, MVT::f64, Custom);
309 if (Subtarget->has16BitInsts()) {
310 setOperationAction(ISD::Constant, MVT::i16, Legal);
312 setOperationAction(ISD::SMIN, MVT::i16, Legal);
313 setOperationAction(ISD::SMAX, MVT::i16, Legal);
315 setOperationAction(ISD::UMIN, MVT::i16, Legal);
316 setOperationAction(ISD::UMAX, MVT::i16, Legal);
318 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
319 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
321 setOperationAction(ISD::ROTR, MVT::i16, Promote);
322 setOperationAction(ISD::ROTL, MVT::i16, Promote);
324 setOperationAction(ISD::SDIV, MVT::i16, Promote);
325 setOperationAction(ISD::UDIV, MVT::i16, Promote);
326 setOperationAction(ISD::SREM, MVT::i16, Promote);
327 setOperationAction(ISD::UREM, MVT::i16, Promote);
329 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
330 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
332 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
334 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
335 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
337 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
339 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
341 setOperationAction(ISD::LOAD, MVT::i16, Custom);
343 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
345 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
346 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
347 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
348 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
350 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
351 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
352 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
353 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
355 // F16 - Constant Actions.
356 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
358 // F16 - Load/Store Actions.
359 setOperationAction(ISD::LOAD, MVT::f16, Promote);
360 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
361 setOperationAction(ISD::STORE, MVT::f16, Promote);
362 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
364 // F16 - VOP1 Actions.
365 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
366 setOperationAction(ISD::FCOS, MVT::f16, Promote);
367 setOperationAction(ISD::FSIN, MVT::f16, Promote);
368 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
369 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
370 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
371 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
372 setOperationAction(ISD::FROUND, MVT::f16, Custom);
374 // F16 - VOP2 Actions.
375 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
376 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
377 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
378 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
379 setOperationAction(ISD::FDIV, MVT::f16, Custom);
381 // F16 - VOP3 Actions.
382 setOperationAction(ISD::FMA, MVT::f16, Legal);
383 if (!Subtarget->hasFP16Denormals())
384 setOperationAction(ISD::FMAD, MVT::f16, Legal);
387 if (Subtarget->hasVOP3PInsts()) {
388 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
389 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
393 case ISD::BUILD_VECTOR:
395 case ISD::EXTRACT_VECTOR_ELT:
396 case ISD::INSERT_VECTOR_ELT:
397 case ISD::INSERT_SUBVECTOR:
398 case ISD::EXTRACT_SUBVECTOR:
399 case ISD::SCALAR_TO_VECTOR:
401 case ISD::CONCAT_VECTORS:
402 setOperationAction(Op, VT, Custom);
405 setOperationAction(Op, VT, Expand);
411 // XXX - Do these do anything? Vector constants turn into build_vector.
412 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
413 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
415 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
416 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
417 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
418 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
420 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
421 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
422 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
423 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
425 setOperationAction(ISD::AND, MVT::v2i16, Promote);
426 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
427 setOperationAction(ISD::OR, MVT::v2i16, Promote);
428 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
429 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
430 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
431 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
432 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
433 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
434 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
436 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
437 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
438 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
439 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
440 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
441 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
442 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
443 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
444 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
445 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
447 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
448 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
449 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
450 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
451 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
452 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
454 // This isn't really legal, but this avoids the legalizer unrolling it (and
455 // allows matching fneg (fabs x) patterns)
456 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
458 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
459 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
461 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
462 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
463 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
465 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
466 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
469 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
470 setOperationAction(ISD::SELECT, VT, Custom);
473 setTargetDAGCombine(ISD::FADD);
474 setTargetDAGCombine(ISD::FSUB);
475 setTargetDAGCombine(ISD::FMINNUM);
476 setTargetDAGCombine(ISD::FMAXNUM);
477 setTargetDAGCombine(ISD::SMIN);
478 setTargetDAGCombine(ISD::SMAX);
479 setTargetDAGCombine(ISD::UMIN);
480 setTargetDAGCombine(ISD::UMAX);
481 setTargetDAGCombine(ISD::SETCC);
482 setTargetDAGCombine(ISD::AND);
483 setTargetDAGCombine(ISD::OR);
484 setTargetDAGCombine(ISD::XOR);
485 setTargetDAGCombine(ISD::SINT_TO_FP);
486 setTargetDAGCombine(ISD::UINT_TO_FP);
487 setTargetDAGCombine(ISD::FCANONICALIZE);
488 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
489 setTargetDAGCombine(ISD::ZERO_EXTEND);
491 // All memory operations. Some folding on the pointer operand is done to help
492 // matching the constant offsets in the addressing modes.
493 setTargetDAGCombine(ISD::LOAD);
494 setTargetDAGCombine(ISD::STORE);
495 setTargetDAGCombine(ISD::ATOMIC_LOAD);
496 setTargetDAGCombine(ISD::ATOMIC_STORE);
497 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
498 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
499 setTargetDAGCombine(ISD::ATOMIC_SWAP);
500 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
501 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
502 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
503 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
504 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
505 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
506 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
507 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
508 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
509 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
511 setSchedulingPreference(Sched::RegPressure);
514 const SISubtarget *SITargetLowering::getSubtarget() const {
515 return static_cast<const SISubtarget *>(Subtarget);
518 //===----------------------------------------------------------------------===//
519 // TargetLowering queries
520 //===----------------------------------------------------------------------===//
522 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
524 // SI has some legal vector types, but no legal vector operations. Say no
525 // shuffles are legal in order to prefer scalarizing some vector operations.
529 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
531 unsigned IntrID) const {
533 case Intrinsic::amdgcn_atomic_inc:
534 case Intrinsic::amdgcn_atomic_dec: {
535 Info.opc = ISD::INTRINSIC_W_CHAIN;
536 Info.memVT = MVT::getVT(CI.getType());
537 Info.ptrVal = CI.getOperand(0);
540 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
541 Info.vol = !Vol || !Vol->isNullValue();
543 Info.writeMem = true;
551 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
552 SmallVectorImpl<Value*> &Ops,
553 Type *&AccessTy) const {
554 switch (II->getIntrinsicID()) {
555 case Intrinsic::amdgcn_atomic_inc:
556 case Intrinsic::amdgcn_atomic_dec: {
557 Value *Ptr = II->getArgOperand(0);
558 AccessTy = II->getType();
567 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
568 // Flat instructions do not have offsets, and only have the register
570 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
573 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
574 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
575 // additionally can do r + r + i with addr64. 32-bit has more addressing
576 // mode options. Depending on the resource constant, it can also do
577 // (i64 r0) + (i32 r1) * (i14 i).
579 // Private arrays end up using a scratch buffer most of the time, so also
580 // assume those use MUBUF instructions. Scratch loads / stores are currently
581 // implemented as mubuf instructions with offen bit set, so slightly
582 // different than the normal addr64.
583 if (!isUInt<12>(AM.BaseOffs))
586 // FIXME: Since we can split immediate into soffset and immediate offset,
587 // would it make sense to allow any immediate?
590 case 0: // r + i or just i, depending on HasBaseReg.
593 return true; // We have r + r or r + i.
600 // Allow 2 * r as r + r
601 // Or 2 * r + i is allowed as r + r + i.
603 default: // Don't allow n * r
608 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
609 const AddrMode &AM, Type *Ty,
611 // No global is ever allowed as a base.
615 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
616 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
617 // Assume the we will use FLAT for all global memory accesses
619 // FIXME: This assumption is currently wrong. On VI we still use
620 // MUBUF instructions for the r + i addressing mode. As currently
621 // implemented, the MUBUF instructions only work on buffer < 4GB.
622 // It may be possible to support > 4GB buffers with MUBUF instructions,
623 // by setting the stride value in the resource descriptor which would
624 // increase the size limit to (stride * 4GB). However, this is risky,
625 // because it has never been validated.
626 return isLegalFlatAddressingMode(AM);
629 return isLegalMUBUFAddressingMode(AM);
630 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
631 // If the offset isn't a multiple of 4, it probably isn't going to be
632 // correctly aligned.
633 // FIXME: Can we get the real alignment here?
634 if (AM.BaseOffs % 4 != 0)
635 return isLegalMUBUFAddressingMode(AM);
637 // There are no SMRD extloads, so if we have to do a small type access we
638 // will use a MUBUF load.
639 // FIXME?: We also need to do this if unaligned, but we don't know the
641 if (DL.getTypeStoreSize(Ty) < 4)
642 return isLegalMUBUFAddressingMode(AM);
644 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
645 // SMRD instructions have an 8-bit, dword offset on SI.
646 if (!isUInt<8>(AM.BaseOffs / 4))
648 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
649 // On CI+, this can also be a 32-bit literal constant offset. If it fits
650 // in 8-bits, it can use a smaller encoding.
651 if (!isUInt<32>(AM.BaseOffs / 4))
653 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
654 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
655 if (!isUInt<20>(AM.BaseOffs))
658 llvm_unreachable("unhandled generation");
660 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
663 if (AM.Scale == 1 && AM.HasBaseReg)
668 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
669 return isLegalMUBUFAddressingMode(AM);
670 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
671 AS == AMDGPUASI.REGION_ADDRESS) {
672 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
674 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
675 // an 8-bit dword offset but we don't know the alignment here.
676 if (!isUInt<16>(AM.BaseOffs))
679 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
682 if (AM.Scale == 1 && AM.HasBaseReg)
686 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
687 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
688 // For an unknown address space, this usually means that this is for some
689 // reason being used for pure arithmetic, and not based on some addressing
690 // computation. We don't have instructions that compute pointers with any
691 // addressing modes, so treat them as having no offset like flat
693 return isLegalFlatAddressingMode(AM);
695 llvm_unreachable("unhandled address space");
699 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
702 bool *IsFast) const {
706 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
707 // which isn't a simple VT.
708 // Until MVT is extended to handle this, simply check for the size and
709 // rely on the condition below: allow accesses if the size is a multiple of 4.
710 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
711 VT.getStoreSize() > 16)) {
715 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
716 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
717 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
718 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
719 // with adjacent offsets.
720 bool AlignedBy4 = (Align % 4 == 0);
722 *IsFast = AlignedBy4;
727 // FIXME: We have to be conservative here and assume that flat operations
728 // will access scratch. If we had access to the IR function, then we
729 // could determine if any private memory was used in the function.
730 if (!Subtarget->hasUnalignedScratchAccess() &&
731 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
732 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
736 if (Subtarget->hasUnalignedBufferAccess()) {
737 // If we have an uniform constant load, it still requires using a slow
738 // buffer instruction if unaligned.
740 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
741 (Align % 4 == 0) : true;
747 // Smaller than dword value must be aligned.
748 if (VT.bitsLT(MVT::i32))
751 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
752 // byte-address are ignored, thus forcing Dword alignment.
753 // This applies to private, global, and constant memory.
757 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
760 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
761 unsigned SrcAlign, bool IsMemset,
764 MachineFunction &MF) const {
765 // FIXME: Should account for address space here.
767 // The default fallback uses the private pointer size as a guess for a type to
768 // use. Make sure we switch these to 64-bit accesses.
770 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
773 if (Size >= 8 && DstAlign >= 4)
780 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
781 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
782 AS == AMDGPUASI.FLAT_ADDRESS ||
783 AS == AMDGPUASI.CONSTANT_ADDRESS;
786 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
787 unsigned DestAS) const {
788 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
789 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
792 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
793 const MemSDNode *MemNode = cast<MemSDNode>(N);
794 const Value *Ptr = MemNode->getMemOperand()->getValue();
795 const Instruction *I = dyn_cast<Instruction>(Ptr);
796 return I && I->getMetadata("amdgpu.noclobber");
799 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
800 unsigned DestAS) const {
801 // Flat -> private/local is a simple truncate.
802 // Flat -> global is no-op
803 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
806 return isNoopAddrSpaceCast(SrcAS, DestAS);
809 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
810 const MemSDNode *MemNode = cast<MemSDNode>(N);
812 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
815 TargetLoweringBase::LegalizeTypeAction
816 SITargetLowering::getPreferredVectorAction(EVT VT) const {
817 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
818 return TypeSplitVector;
820 return TargetLoweringBase::getPreferredVectorAction(VT);
823 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
825 // FIXME: Could be smarter if called for vector constants.
829 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
830 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
835 // These operations are done with 32-bit instructions anyway.
847 // SimplifySetCC uses this function to determine whether or not it should
848 // create setcc with i1 operands. We don't have instructions for i1 setcc.
849 if (VT == MVT::i1 && Op == ISD::SETCC)
852 return TargetLowering::isTypeDesirableForOp(Op, VT);
855 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
858 uint64_t Offset) const {
859 const DataLayout &DL = DAG.getDataLayout();
860 MachineFunction &MF = DAG.getMachineFunction();
861 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
862 unsigned InputPtrReg = TRI->getPreloadedValue(MF,
863 SIRegisterInfo::KERNARG_SEGMENT_PTR);
865 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
866 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
867 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
868 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
869 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
870 DAG.getConstant(Offset, SL, PtrVT));
873 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
874 const SDLoc &SL, SDValue Val,
876 const ISD::InputArg *Arg) const {
877 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
879 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
880 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
883 if (MemVT.isFloatingPoint())
884 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
886 Val = DAG.getSExtOrTrunc(Val, SL, VT);
888 Val = DAG.getZExtOrTrunc(Val, SL, VT);
893 SDValue SITargetLowering::lowerKernargMemParameter(
894 SelectionDAG &DAG, EVT VT, EVT MemVT,
895 const SDLoc &SL, SDValue Chain,
896 uint64_t Offset, bool Signed,
897 const ISD::InputArg *Arg) const {
898 const DataLayout &DL = DAG.getDataLayout();
899 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
900 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
901 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
903 unsigned Align = DL.getABITypeAlignment(Ty);
905 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
906 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
907 MachineMemOperand::MONonTemporal |
908 MachineMemOperand::MODereferenceable |
909 MachineMemOperand::MOInvariant);
911 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
912 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
915 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
916 CallingConv::ID CallConv,
917 ArrayRef<ISD::InputArg> Ins,
920 SIMachineFunctionInfo *Info) {
921 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
922 const ISD::InputArg &Arg = Ins[I];
924 // First check if it's a PS input addr.
925 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
926 !Arg.Flags.isByVal() && PSInputNum <= 15) {
928 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
929 // We can safely skip PS inputs.
935 Info->markPSInputAllocated(PSInputNum);
937 Info->markPSInputEnabled(PSInputNum);
942 // Second split vertices into their elements.
943 if (Arg.VT.isVector()) {
944 ISD::InputArg NewArg = Arg;
945 NewArg.Flags.setSplit();
946 NewArg.VT = Arg.VT.getVectorElementType();
948 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
949 // three or five element vertex only needs three or five registers,
950 // NOT four or eight.
951 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
952 unsigned NumElements = ParamType->getVectorNumElements();
954 for (unsigned J = 0; J != NumElements; ++J) {
955 Splits.push_back(NewArg);
956 NewArg.PartOffset += NewArg.VT.getStoreSize();
959 Splits.push_back(Arg);
964 // Allocate special inputs passed in VGPRs.
965 static void allocateSpecialInputVGPRs(CCState &CCInfo,
967 const SIRegisterInfo &TRI,
968 SIMachineFunctionInfo &Info) {
969 if (Info.hasWorkItemIDX()) {
970 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
971 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
972 CCInfo.AllocateReg(Reg);
975 if (Info.hasWorkItemIDY()) {
976 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
977 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
978 CCInfo.AllocateReg(Reg);
981 if (Info.hasWorkItemIDZ()) {
982 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
983 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
984 CCInfo.AllocateReg(Reg);
988 // Allocate special inputs passed in user SGPRs.
989 static void allocateHSAUserSGPRs(CCState &CCInfo,
991 const SIRegisterInfo &TRI,
992 SIMachineFunctionInfo &Info) {
993 if (Info.hasPrivateMemoryInputPtr()) {
994 unsigned PrivateMemoryPtrReg = Info.addPrivateMemoryPtr(TRI);
995 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SGPR_64RegClass);
996 CCInfo.AllocateReg(PrivateMemoryPtrReg);
999 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1000 if (Info.hasPrivateSegmentBuffer()) {
1001 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1002 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1003 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1006 if (Info.hasDispatchPtr()) {
1007 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1008 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1009 CCInfo.AllocateReg(DispatchPtrReg);
1012 if (Info.hasQueuePtr()) {
1013 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1014 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1015 CCInfo.AllocateReg(QueuePtrReg);
1018 if (Info.hasKernargSegmentPtr()) {
1019 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1020 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1021 CCInfo.AllocateReg(InputPtrReg);
1024 if (Info.hasDispatchID()) {
1025 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1026 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1027 CCInfo.AllocateReg(DispatchIDReg);
1030 if (Info.hasFlatScratchInit()) {
1031 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1032 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1033 CCInfo.AllocateReg(FlatScratchInitReg);
1036 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1037 // these from the dispatch pointer.
1040 // Allocate special input registers that are initialized per-wave.
1041 static void allocateSystemSGPRs(CCState &CCInfo,
1042 MachineFunction &MF,
1043 SIMachineFunctionInfo &Info,
1045 if (Info.hasWorkGroupIDX()) {
1046 unsigned Reg = Info.addWorkGroupIDX();
1047 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1048 CCInfo.AllocateReg(Reg);
1051 if (Info.hasWorkGroupIDY()) {
1052 unsigned Reg = Info.addWorkGroupIDY();
1053 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1054 CCInfo.AllocateReg(Reg);
1057 if (Info.hasWorkGroupIDZ()) {
1058 unsigned Reg = Info.addWorkGroupIDZ();
1059 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1060 CCInfo.AllocateReg(Reg);
1063 if (Info.hasWorkGroupInfo()) {
1064 unsigned Reg = Info.addWorkGroupInfo();
1065 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1066 CCInfo.AllocateReg(Reg);
1069 if (Info.hasPrivateSegmentWaveByteOffset()) {
1070 // Scratch wave offset passed in system SGPR.
1071 unsigned PrivateSegmentWaveByteOffsetReg;
1074 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1075 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1077 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1079 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1080 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1084 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1085 MachineFunction &MF,
1086 const SIRegisterInfo &TRI,
1087 SIMachineFunctionInfo &Info) {
1088 // Now that we've figured out where the scratch register inputs are, see if
1089 // should reserve the arguments and use them directly.
1090 bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1092 // Record that we know we have non-spill stack objects so we don't need to
1093 // check all stack objects later.
1094 if (HasStackObjects)
1095 Info.setHasNonSpillStackObjects(true);
1097 // Everything live out of a block is spilled with fast regalloc, so it's
1098 // almost certain that spilling will be required.
1099 if (TM.getOptLevel() == CodeGenOpt::None)
1100 HasStackObjects = true;
1102 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1103 if (ST.isAmdCodeObjectV2(MF)) {
1104 if (HasStackObjects) {
1105 // If we have stack objects, we unquestionably need the private buffer
1106 // resource. For the Code Object V2 ABI, this will be the first 4 user
1107 // SGPR inputs. We can reserve those and use them directly.
1109 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue(
1110 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1111 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1113 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue(
1114 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1115 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1117 unsigned ReservedBufferReg
1118 = TRI.reservedPrivateSegmentBufferReg(MF);
1119 unsigned ReservedOffsetReg
1120 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1122 // We tentatively reserve the last registers (skipping the last two
1123 // which may contain VCC). After register allocation, we'll replace
1124 // these with the ones immediately after those which were really
1125 // allocated. In the prologue copies will be inserted from the argument
1126 // to these reserved registers.
1127 Info.setScratchRSrcReg(ReservedBufferReg);
1128 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1131 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1133 // Without HSA, relocations are used for the scratch pointer and the
1134 // buffer resource setup is always inserted in the prologue. Scratch wave
1135 // offset is still in an input SGPR.
1136 Info.setScratchRSrcReg(ReservedBufferReg);
1138 if (HasStackObjects) {
1139 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue(
1140 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1141 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1143 unsigned ReservedOffsetReg
1144 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1145 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1150 SDValue SITargetLowering::LowerFormalArguments(
1151 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1152 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1153 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1154 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1156 MachineFunction &MF = DAG.getMachineFunction();
1157 FunctionType *FType = MF.getFunction()->getFunctionType();
1158 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1159 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1161 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1162 const Function *Fn = MF.getFunction();
1163 DiagnosticInfoUnsupported NoGraphicsHSA(
1164 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1165 DAG.getContext()->diagnose(NoGraphicsHSA);
1166 return DAG.getEntryNode();
1169 // Create stack objects that are used for emitting debugger prologue if
1170 // "amdgpu-debugger-emit-prologue" attribute was specified.
1171 if (ST.debuggerEmitPrologue())
1172 createDebuggerPrologueStackObjects(MF);
1174 SmallVector<ISD::InputArg, 16> Splits;
1175 SmallVector<CCValAssign, 16> ArgLocs;
1176 BitVector Skipped(Ins.size());
1177 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1180 bool IsShader = AMDGPU::isShader(CallConv);
1181 bool IsKernel = AMDGPU::isKernel(CallConv);
1182 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1185 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1187 // At least one interpolation mode must be enabled or else the GPU will
1190 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1191 // set PSInputAddr, the user wants to enable some bits after the compilation
1192 // based on run-time states. Since we can't know what the final PSInputEna
1193 // will look like, so we shouldn't do anything here and the user should take
1194 // responsibility for the correct programming.
1196 // Otherwise, the following restrictions apply:
1197 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1198 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1200 if (CallConv == CallingConv::AMDGPU_PS &&
1201 ((Info->getPSInputAddr() & 0x7F) == 0 ||
1202 ((Info->getPSInputAddr() & 0xF) == 0 &&
1203 Info->isPSInputAllocated(11)))) {
1204 CCInfo.AllocateReg(AMDGPU::VGPR0);
1205 CCInfo.AllocateReg(AMDGPU::VGPR1);
1206 Info->markPSInputAllocated(0);
1207 Info->markPSInputEnabled(0);
1210 assert(!Info->hasDispatchPtr() &&
1211 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1212 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1213 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1214 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1215 !Info->hasWorkItemIDZ());
1217 assert(!IsKernel || (Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()));
1221 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1222 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1226 analyzeFormalArgumentsCompute(CCInfo, Ins);
1228 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1229 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1232 SmallVector<SDValue, 16> Chains;
1234 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1235 const ISD::InputArg &Arg = Ins[i];
1237 InVals.push_back(DAG.getUNDEF(Arg.VT));
1241 CCValAssign &VA = ArgLocs[ArgIdx++];
1242 MVT VT = VA.getLocVT();
1244 if (IsEntryFunc && VA.isMemLoc()) {
1246 EVT MemVT = VA.getLocVT();
1248 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1249 VA.getLocMemOffset();
1250 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1252 // The first 36 bytes of the input buffer contains information about
1253 // thread group and global sizes.
1254 SDValue Arg = lowerKernargMemParameter(
1255 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1256 Chains.push_back(Arg.getValue(1));
1259 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1260 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1261 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1262 // On SI local pointers are just offsets into LDS, so they are always
1263 // less than 16-bits. On CI and newer they could potentially be
1264 // real pointers, so we can't guarantee their size.
1265 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1266 DAG.getValueType(MVT::i16));
1269 InVals.push_back(Arg);
1274 report_fatal_error("memloc not supported with calling convention");
1276 assert(VA.isRegLoc() && "Parameter must be in a register!");
1278 unsigned Reg = VA.getLocReg();
1279 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1281 Reg = MF.addLiveIn(Reg, RC);
1282 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1284 if (Arg.VT.isVector()) {
1285 // Build a vector from the registers
1286 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1287 unsigned NumElements = ParamType->getVectorNumElements();
1289 SmallVector<SDValue, 4> Regs;
1290 Regs.push_back(Val);
1291 for (unsigned j = 1; j != NumElements; ++j) {
1292 Reg = ArgLocs[ArgIdx++].getLocReg();
1293 Reg = MF.addLiveIn(Reg, RC);
1295 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1296 Regs.push_back(Copy);
1299 // Fill up the missing vector elements
1300 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1301 Regs.append(NumElements, DAG.getUNDEF(VT));
1303 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1307 InVals.push_back(Val);
1310 // Start adding system SGPRs.
1312 allocateSystemSGPRs(CCInfo, MF, *Info, IsShader);
1314 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
1316 return Chains.empty() ? Chain :
1317 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1321 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1323 const SmallVectorImpl<ISD::OutputArg> &Outs,
1324 const SmallVectorImpl<SDValue> &OutVals,
1325 const SDLoc &DL, SelectionDAG &DAG) const {
1326 MachineFunction &MF = DAG.getMachineFunction();
1327 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1329 if (!AMDGPU::isShader(CallConv))
1330 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1333 Info->setIfReturnsVoid(Outs.size() == 0);
1335 SmallVector<ISD::OutputArg, 48> Splits;
1336 SmallVector<SDValue, 48> SplitVals;
1338 // Split vectors into their elements.
1339 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1340 const ISD::OutputArg &Out = Outs[i];
1342 if (Out.VT.isVector()) {
1343 MVT VT = Out.VT.getVectorElementType();
1344 ISD::OutputArg NewOut = Out;
1345 NewOut.Flags.setSplit();
1348 // We want the original number of vector elements here, e.g.
1349 // three or five, not four or eight.
1350 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1352 for (unsigned j = 0; j != NumElements; ++j) {
1353 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1354 DAG.getConstant(j, DL, MVT::i32));
1355 SplitVals.push_back(Elem);
1356 Splits.push_back(NewOut);
1357 NewOut.PartOffset += NewOut.VT.getStoreSize();
1360 SplitVals.push_back(OutVals[i]);
1361 Splits.push_back(Out);
1365 // CCValAssign - represent the assignment of the return value to a location.
1366 SmallVector<CCValAssign, 48> RVLocs;
1368 // CCState - Info about the registers and stack slots.
1369 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1372 // Analyze outgoing return values.
1373 AnalyzeReturn(CCInfo, Splits);
1376 SmallVector<SDValue, 48> RetOps;
1377 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1379 // Copy the result values into the output registers.
1380 for (unsigned i = 0, realRVLocIdx = 0;
1382 ++i, ++realRVLocIdx) {
1383 CCValAssign &VA = RVLocs[i];
1384 assert(VA.isRegLoc() && "Can only return in registers!");
1386 SDValue Arg = SplitVals[realRVLocIdx];
1388 // Copied from other backends.
1389 switch (VA.getLocInfo()) {
1390 default: llvm_unreachable("Unknown loc info!");
1391 case CCValAssign::Full:
1393 case CCValAssign::BCvt:
1394 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1398 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1399 Flag = Chain.getValue(1);
1400 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1403 // Update chain and glue.
1406 RetOps.push_back(Flag);
1408 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN_TO_EPILOG;
1409 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1412 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1413 SelectionDAG &DAG) const {
1414 unsigned Reg = StringSwitch<unsigned>(RegName)
1415 .Case("m0", AMDGPU::M0)
1416 .Case("exec", AMDGPU::EXEC)
1417 .Case("exec_lo", AMDGPU::EXEC_LO)
1418 .Case("exec_hi", AMDGPU::EXEC_HI)
1419 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1420 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1421 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1422 .Default(AMDGPU::NoRegister);
1424 if (Reg == AMDGPU::NoRegister) {
1425 report_fatal_error(Twine("invalid register name \""
1426 + StringRef(RegName) + "\"."));
1430 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1431 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1432 report_fatal_error(Twine("invalid register \""
1433 + StringRef(RegName) + "\" for subtarget."));
1438 case AMDGPU::EXEC_LO:
1439 case AMDGPU::EXEC_HI:
1440 case AMDGPU::FLAT_SCR_LO:
1441 case AMDGPU::FLAT_SCR_HI:
1442 if (VT.getSizeInBits() == 32)
1446 case AMDGPU::FLAT_SCR:
1447 if (VT.getSizeInBits() == 64)
1451 llvm_unreachable("missing register type checking");
1454 report_fatal_error(Twine("invalid type for register \""
1455 + StringRef(RegName) + "\"."));
1458 // If kill is not the last instruction, split the block so kill is always a
1459 // proper terminator.
1460 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1461 MachineBasicBlock *BB) const {
1462 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1464 MachineBasicBlock::iterator SplitPoint(&MI);
1467 if (SplitPoint == BB->end()) {
1468 // Don't bother with a new block.
1469 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1473 MachineFunction *MF = BB->getParent();
1474 MachineBasicBlock *SplitBB
1475 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1477 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1478 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1480 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1481 BB->addSuccessor(SplitBB);
1483 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1487 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1488 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1489 // will only do one iteration. In the worst case, this will loop 64 times.
1491 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1492 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1493 const SIInstrInfo *TII,
1494 MachineRegisterInfo &MRI,
1495 MachineBasicBlock &OrigBB,
1496 MachineBasicBlock &LoopBB,
1498 const MachineOperand &IdxReg,
1502 unsigned InitSaveExecReg,
1504 bool UseGPRIdxMode) {
1505 MachineBasicBlock::iterator I = LoopBB.begin();
1507 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1508 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1509 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1510 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1512 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1518 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1519 .addReg(InitSaveExecReg)
1524 // Read the next variant <- also loop target.
1525 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1526 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1528 // Compare the just read M0 value to all possible Idx values.
1529 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1530 .addReg(CurrentIdxReg)
1531 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1533 if (UseGPRIdxMode) {
1536 IdxReg = CurrentIdxReg;
1538 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1539 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1540 .addReg(CurrentIdxReg, RegState::Kill)
1544 MachineInstr *SetIdx =
1545 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1546 .addReg(IdxReg, RegState::Kill);
1547 SetIdx->getOperand(2).setIsUndef();
1549 // Move index from VCC into M0
1551 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1552 .addReg(CurrentIdxReg, RegState::Kill);
1554 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1555 .addReg(CurrentIdxReg, RegState::Kill)
1560 // Update EXEC, save the original EXEC value to VCC.
1561 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1562 .addReg(CondReg, RegState::Kill);
1564 MRI.setSimpleHint(NewExec, CondReg);
1566 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1567 MachineInstr *InsertPt =
1568 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1569 .addReg(AMDGPU::EXEC)
1572 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1575 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1576 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1579 return InsertPt->getIterator();
1582 // This has slightly sub-optimal regalloc when the source vector is killed by
1583 // the read. The register allocator does not understand that the kill is
1584 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1585 // subregister from it, using 1 more VGPR than necessary. This was saved when
1586 // this was expanded after register allocation.
1587 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1588 MachineBasicBlock &MBB,
1590 unsigned InitResultReg,
1593 bool UseGPRIdxMode) {
1594 MachineFunction *MF = MBB.getParent();
1595 MachineRegisterInfo &MRI = MF->getRegInfo();
1596 const DebugLoc &DL = MI.getDebugLoc();
1597 MachineBasicBlock::iterator I(&MI);
1599 unsigned DstReg = MI.getOperand(0).getReg();
1600 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1601 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1603 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1605 // Save the EXEC mask
1606 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1607 .addReg(AMDGPU::EXEC);
1609 // To insert the loop we need to split the block. Move everything after this
1610 // point to a new block, and insert a new empty block between the two.
1611 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1612 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1613 MachineFunction::iterator MBBI(MBB);
1616 MF->insert(MBBI, LoopBB);
1617 MF->insert(MBBI, RemainderBB);
1619 LoopBB->addSuccessor(LoopBB);
1620 LoopBB->addSuccessor(RemainderBB);
1622 // Move the rest of the block into a new block.
1623 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1624 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1626 MBB.addSuccessor(LoopBB);
1628 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1630 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1631 InitResultReg, DstReg, PhiReg, TmpExec,
1632 Offset, UseGPRIdxMode);
1634 MachineBasicBlock::iterator First = RemainderBB->begin();
1635 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1641 // Returns subreg index, offset
1642 static std::pair<unsigned, int>
1643 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1644 const TargetRegisterClass *SuperRC,
1647 int NumElts = SuperRC->getSize() / 4;
1649 // Skip out of bounds offsets, or else we would end up using an undefined
1651 if (Offset >= NumElts || Offset < 0)
1652 return std::make_pair(AMDGPU::sub0, Offset);
1654 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1657 // Return true if the index is an SGPR and was set.
1658 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1659 MachineRegisterInfo &MRI,
1663 bool IsIndirectSrc) {
1664 MachineBasicBlock *MBB = MI.getParent();
1665 const DebugLoc &DL = MI.getDebugLoc();
1666 MachineBasicBlock::iterator I(&MI);
1668 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1669 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1671 assert(Idx->getReg() != AMDGPU::NoRegister);
1673 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1676 if (UseGPRIdxMode) {
1677 unsigned IdxMode = IsIndirectSrc ?
1678 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1680 MachineInstr *SetOn =
1681 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1685 SetOn->getOperand(3).setIsUndef();
1687 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1688 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1691 MachineInstr *SetOn =
1692 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1693 .addReg(Tmp, RegState::Kill)
1696 SetOn->getOperand(3).setIsUndef();
1703 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1706 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1714 // Control flow needs to be inserted if indexing with a VGPR.
1715 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1716 MachineBasicBlock &MBB,
1717 const SISubtarget &ST) {
1718 const SIInstrInfo *TII = ST.getInstrInfo();
1719 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1720 MachineFunction *MF = MBB.getParent();
1721 MachineRegisterInfo &MRI = MF->getRegInfo();
1723 unsigned Dst = MI.getOperand(0).getReg();
1724 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1725 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1727 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1730 std::tie(SubReg, Offset)
1731 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1733 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1735 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1736 MachineBasicBlock::iterator I(&MI);
1737 const DebugLoc &DL = MI.getDebugLoc();
1739 if (UseGPRIdxMode) {
1740 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1741 // to avoid interfering with other uses, so probably requires a new
1742 // optimization pass.
1743 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1744 .addReg(SrcReg, RegState::Undef, SubReg)
1745 .addReg(SrcReg, RegState::Implicit)
1746 .addReg(AMDGPU::M0, RegState::Implicit);
1747 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1749 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1750 .addReg(SrcReg, RegState::Undef, SubReg)
1751 .addReg(SrcReg, RegState::Implicit);
1754 MI.eraseFromParent();
1759 const DebugLoc &DL = MI.getDebugLoc();
1760 MachineBasicBlock::iterator I(&MI);
1762 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1763 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1765 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1767 if (UseGPRIdxMode) {
1768 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1769 .addImm(0) // Reset inside loop.
1770 .addImm(VGPRIndexMode::SRC0_ENABLE);
1771 SetOn->getOperand(3).setIsUndef();
1773 // Disable again after the loop.
1774 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1777 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1778 MachineBasicBlock *LoopBB = InsPt->getParent();
1780 if (UseGPRIdxMode) {
1781 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1782 .addReg(SrcReg, RegState::Undef, SubReg)
1783 .addReg(SrcReg, RegState::Implicit)
1784 .addReg(AMDGPU::M0, RegState::Implicit);
1786 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1787 .addReg(SrcReg, RegState::Undef, SubReg)
1788 .addReg(SrcReg, RegState::Implicit);
1791 MI.eraseFromParent();
1796 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1797 switch (VecRC->getSize()) {
1799 return AMDGPU::V_MOVRELD_B32_V1;
1801 return AMDGPU::V_MOVRELD_B32_V2;
1803 return AMDGPU::V_MOVRELD_B32_V4;
1805 return AMDGPU::V_MOVRELD_B32_V8;
1807 return AMDGPU::V_MOVRELD_B32_V16;
1809 llvm_unreachable("unsupported size for MOVRELD pseudos");
1813 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1814 MachineBasicBlock &MBB,
1815 const SISubtarget &ST) {
1816 const SIInstrInfo *TII = ST.getInstrInfo();
1817 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1818 MachineFunction *MF = MBB.getParent();
1819 MachineRegisterInfo &MRI = MF->getRegInfo();
1821 unsigned Dst = MI.getOperand(0).getReg();
1822 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1823 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1824 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1825 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1826 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1828 // This can be an immediate, but will be folded later.
1829 assert(Val->getReg());
1832 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1835 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1837 if (Idx->getReg() == AMDGPU::NoRegister) {
1838 MachineBasicBlock::iterator I(&MI);
1839 const DebugLoc &DL = MI.getDebugLoc();
1841 assert(Offset == 0);
1843 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1848 MI.eraseFromParent();
1852 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1853 MachineBasicBlock::iterator I(&MI);
1854 const DebugLoc &DL = MI.getDebugLoc();
1856 if (UseGPRIdxMode) {
1857 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1858 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1860 .addReg(Dst, RegState::ImplicitDefine)
1861 .addReg(SrcVec->getReg(), RegState::Implicit)
1862 .addReg(AMDGPU::M0, RegState::Implicit);
1864 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1866 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1868 BuildMI(MBB, I, DL, MovRelDesc)
1869 .addReg(Dst, RegState::Define)
1870 .addReg(SrcVec->getReg())
1872 .addImm(SubReg - AMDGPU::sub0);
1875 MI.eraseFromParent();
1880 MRI.clearKillFlags(Val->getReg());
1882 const DebugLoc &DL = MI.getDebugLoc();
1884 if (UseGPRIdxMode) {
1885 MachineBasicBlock::iterator I(&MI);
1887 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1888 .addImm(0) // Reset inside loop.
1889 .addImm(VGPRIndexMode::DST_ENABLE);
1890 SetOn->getOperand(3).setIsUndef();
1892 // Disable again after the loop.
1893 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1896 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1898 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1899 Offset, UseGPRIdxMode);
1900 MachineBasicBlock *LoopBB = InsPt->getParent();
1902 if (UseGPRIdxMode) {
1903 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1904 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1906 .addReg(Dst, RegState::ImplicitDefine)
1907 .addReg(PhiReg, RegState::Implicit)
1908 .addReg(AMDGPU::M0, RegState::Implicit);
1910 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1912 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1913 .addReg(Dst, RegState::Define)
1916 .addImm(SubReg - AMDGPU::sub0);
1919 MI.eraseFromParent();
1924 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1925 MachineInstr &MI, MachineBasicBlock *BB) const {
1927 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1928 MachineFunction *MF = BB->getParent();
1929 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1931 if (TII->isMIMG(MI)) {
1932 if (!MI.memoperands_empty())
1934 // Add a memoperand for mimg instructions so that they aren't assumed to
1935 // be ordered memory instuctions.
1937 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1938 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1940 Flags |= MachineMemOperand::MOStore;
1943 Flags |= MachineMemOperand::MOLoad;
1945 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1946 MI.addMemOperand(*MF, MMO);
1950 switch (MI.getOpcode()) {
1951 case AMDGPU::S_TRAP_PSEUDO: {
1952 const DebugLoc &DL = MI.getDebugLoc();
1953 const int TrapType = MI.getOperand(0).getImm();
1955 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
1956 Subtarget->isTrapHandlerEnabled()) {
1958 MachineFunction *MF = BB->getParent();
1959 SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1960 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
1961 assert(UserSGPR != AMDGPU::NoRegister);
1963 if (!BB->isLiveIn(UserSGPR))
1964 BB->addLiveIn(UserSGPR);
1966 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), AMDGPU::SGPR0_SGPR1)
1968 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_TRAP))
1970 .addReg(AMDGPU::SGPR0_SGPR1, RegState::Implicit);
1973 case SISubtarget::TrapIDLLVMTrap:
1974 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_ENDPGM));
1976 case SISubtarget::TrapIDLLVMDebugTrap: {
1977 DiagnosticInfoUnsupported NoTrap(*MF->getFunction(),
1978 "debugtrap handler not supported",
1981 LLVMContext &C = MF->getFunction()->getContext();
1983 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_NOP))
1988 llvm_unreachable("unsupported trap handler type!");
1992 MI.eraseFromParent();
1995 case AMDGPU::SI_INIT_M0:
1996 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1997 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1998 .add(MI.getOperand(0));
1999 MI.eraseFromParent();
2002 case AMDGPU::GET_GROUPSTATICSIZE: {
2003 DebugLoc DL = MI.getDebugLoc();
2004 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
2005 .add(MI.getOperand(0))
2006 .addImm(MFI->getLDSSize());
2007 MI.eraseFromParent();
2010 case AMDGPU::SI_INDIRECT_SRC_V1:
2011 case AMDGPU::SI_INDIRECT_SRC_V2:
2012 case AMDGPU::SI_INDIRECT_SRC_V4:
2013 case AMDGPU::SI_INDIRECT_SRC_V8:
2014 case AMDGPU::SI_INDIRECT_SRC_V16:
2015 return emitIndirectSrc(MI, *BB, *getSubtarget());
2016 case AMDGPU::SI_INDIRECT_DST_V1:
2017 case AMDGPU::SI_INDIRECT_DST_V2:
2018 case AMDGPU::SI_INDIRECT_DST_V4:
2019 case AMDGPU::SI_INDIRECT_DST_V8:
2020 case AMDGPU::SI_INDIRECT_DST_V16:
2021 return emitIndirectDst(MI, *BB, *getSubtarget());
2022 case AMDGPU::SI_KILL:
2023 return splitKillBlock(MI, BB);
2024 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
2025 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2027 unsigned Dst = MI.getOperand(0).getReg();
2028 unsigned Src0 = MI.getOperand(1).getReg();
2029 unsigned Src1 = MI.getOperand(2).getReg();
2030 const DebugLoc &DL = MI.getDebugLoc();
2031 unsigned SrcCond = MI.getOperand(3).getReg();
2033 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2034 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2036 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
2037 .addReg(Src0, 0, AMDGPU::sub0)
2038 .addReg(Src1, 0, AMDGPU::sub0)
2040 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
2041 .addReg(Src0, 0, AMDGPU::sub1)
2042 .addReg(Src1, 0, AMDGPU::sub1)
2045 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2047 .addImm(AMDGPU::sub0)
2049 .addImm(AMDGPU::sub1);
2050 MI.eraseFromParent();
2053 case AMDGPU::SI_BR_UNDEF: {
2054 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2055 const DebugLoc &DL = MI.getDebugLoc();
2056 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2057 .add(MI.getOperand(0));
2058 Br->getOperand(1).setIsUndef(true); // read undef SCC
2059 MI.eraseFromParent();
2063 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2067 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2068 // This currently forces unfolding various combinations of fsub into fma with
2069 // free fneg'd operands. As long as we have fast FMA (controlled by
2070 // isFMAFasterThanFMulAndFAdd), we should perform these.
2072 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2073 // most of these combines appear to be cycle neutral but save on instruction
2074 // count / code size.
2078 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2080 if (!VT.isVector()) {
2083 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2086 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2087 // TODO: Should i16 be used always if legal? For now it would force VALU
2089 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2092 // Answering this is somewhat tricky and depends on the specific device which
2093 // have different rates for fma or all f64 operations.
2095 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2096 // regardless of which device (although the number of cycles differs between
2097 // devices), so it is always profitable for f64.
2099 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2100 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2101 // which we can always do even without fused FP ops since it returns the same
2102 // result as the separate operations and since it is always full
2103 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2104 // however does not support denormals, so we do report fma as faster if we have
2105 // a fast fma device and require denormals.
2107 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2108 VT = VT.getScalarType();
2110 switch (VT.getSimpleVT().SimpleTy) {
2112 // This is as fast on some subtargets. However, we always have full rate f32
2113 // mad available which returns the same result as the separate operations
2114 // which we should prefer over fma. We can't use this if we want to support
2115 // denormals, so only report this in these cases.
2116 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2120 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2128 //===----------------------------------------------------------------------===//
2129 // Custom DAG Lowering Operations
2130 //===----------------------------------------------------------------------===//
2132 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2133 switch (Op.getOpcode()) {
2134 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2135 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2137 SDValue Result = LowerLOAD(Op, DAG);
2138 assert((!Result.getNode() ||
2139 Result.getNode()->getNumValues() == 2) &&
2140 "Load should return a value and a chain");
2146 return LowerTrig(Op, DAG);
2147 case ISD::SELECT: return LowerSELECT(Op, DAG);
2148 case ISD::FDIV: return LowerFDIV(Op, DAG);
2149 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2150 case ISD::STORE: return LowerSTORE(Op, DAG);
2151 case ISD::GlobalAddress: {
2152 MachineFunction &MF = DAG.getMachineFunction();
2153 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2154 return LowerGlobalAddress(MFI, Op, DAG);
2156 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2157 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2158 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2159 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2160 case ISD::INSERT_VECTOR_ELT:
2161 return lowerINSERT_VECTOR_ELT(Op, DAG);
2162 case ISD::EXTRACT_VECTOR_ELT:
2163 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2165 return lowerFP_ROUND(Op, DAG);
2170 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2171 SmallVectorImpl<SDValue> &Results,
2172 SelectionDAG &DAG) const {
2173 switch (N->getOpcode()) {
2174 case ISD::INSERT_VECTOR_ELT: {
2175 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2176 Results.push_back(Res);
2179 case ISD::EXTRACT_VECTOR_ELT: {
2180 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2181 Results.push_back(Res);
2184 case ISD::INTRINSIC_WO_CHAIN: {
2185 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2187 case Intrinsic::amdgcn_cvt_pkrtz: {
2188 SDValue Src0 = N->getOperand(1);
2189 SDValue Src1 = N->getOperand(2);
2191 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2194 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2203 EVT VT = N->getValueType(0);
2204 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2205 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
2206 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
2208 EVT SelectVT = NewVT;
2209 if (NewVT.bitsLT(MVT::i32)) {
2210 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
2211 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
2212 SelectVT = MVT::i32;
2215 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
2216 N->getOperand(0), LHS, RHS);
2218 if (NewVT != SelectVT)
2219 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
2220 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
2228 /// \brief Helper function for LowerBRCOND
2229 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2231 SDNode *Parent = Value.getNode();
2232 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2235 if (I.getUse().get() != Value)
2238 if (I->getOpcode() == Opcode)
2244 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2245 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2246 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2247 case Intrinsic::amdgcn_if:
2248 return AMDGPUISD::IF;
2249 case Intrinsic::amdgcn_else:
2250 return AMDGPUISD::ELSE;
2251 case Intrinsic::amdgcn_loop:
2252 return AMDGPUISD::LOOP;
2253 case Intrinsic::amdgcn_end_cf:
2254 llvm_unreachable("should not occur");
2260 // break, if_break, else_break are all only used as inputs to loop, not
2261 // directly as branch conditions.
2265 void SITargetLowering::createDebuggerPrologueStackObjects(
2266 MachineFunction &MF) const {
2267 // Create stack objects that are used for emitting debugger prologue.
2269 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2270 // at fixed location in the following format:
2271 // offset 0: work group ID x
2272 // offset 4: work group ID y
2273 // offset 8: work group ID z
2274 // offset 16: work item ID x
2275 // offset 20: work item ID y
2276 // offset 24: work item ID z
2277 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2280 // For each dimension:
2281 for (unsigned i = 0; i < 3; ++i) {
2282 // Create fixed stack object for work group ID.
2283 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2284 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2285 // Create fixed stack object for work item ID.
2286 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2287 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2291 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2292 const Triple &TT = getTargetMachine().getTargetTriple();
2293 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2294 AMDGPU::shouldEmitConstantsToTextSection(TT);
2297 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2298 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2299 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2300 !shouldEmitFixup(GV) &&
2301 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2304 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2305 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2308 /// This transforms the control flow intrinsics to get the branch destination as
2309 /// last parameter, also switches branch target with BR if the need arise
2310 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2311 SelectionDAG &DAG) const {
2314 SDNode *Intr = BRCOND.getOperand(1).getNode();
2315 SDValue Target = BRCOND.getOperand(2);
2316 SDNode *BR = nullptr;
2317 SDNode *SetCC = nullptr;
2319 if (Intr->getOpcode() == ISD::SETCC) {
2320 // As long as we negate the condition everything is fine
2322 Intr = SetCC->getOperand(0).getNode();
2325 // Get the target from BR if we don't negate the condition
2326 BR = findUser(BRCOND, ISD::BR);
2327 Target = BR->getOperand(1);
2330 // FIXME: This changes the types of the intrinsics instead of introducing new
2331 // nodes with the correct types.
2332 // e.g. llvm.amdgcn.loop
2334 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2335 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2337 unsigned CFNode = isCFIntrinsic(Intr);
2339 // This is a uniform branch so we don't need to legalize.
2343 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2344 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2347 (SetCC->getConstantOperandVal(1) == 1 &&
2348 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2351 // operands of the new intrinsic call
2352 SmallVector<SDValue, 4> Ops;
2354 Ops.push_back(BRCOND.getOperand(0));
2356 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2357 Ops.push_back(Target);
2359 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2361 // build the new intrinsic call
2362 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2367 BRCOND.getOperand(0)
2370 Result = DAG.getMergeValues(Ops, DL).getNode();
2374 // Give the branch instruction our target
2377 BRCOND.getOperand(2)
2379 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2380 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2381 BR = NewBR.getNode();
2384 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2386 // Copy the intrinsic results to registers
2387 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2388 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2392 Chain = DAG.getCopyToReg(
2394 CopyToReg->getOperand(1),
2395 SDValue(Result, i - 1),
2398 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2401 // Remove the old intrinsic from the chain
2402 DAG.ReplaceAllUsesOfValueWith(
2403 SDValue(Intr, Intr->getNumValues() - 1),
2404 Intr->getOperand(0));
2409 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2413 return Op.getValueType().bitsLE(VT) ?
2414 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2415 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2418 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2419 assert(Op.getValueType() == MVT::f16 &&
2420 "Do not know how to custom lower FP_ROUND for non-f16 type");
2422 SDValue Src = Op.getOperand(0);
2423 EVT SrcVT = Src.getValueType();
2424 if (SrcVT != MVT::f64)
2429 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2430 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2431 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2434 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2435 SelectionDAG &DAG) const {
2436 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2437 if (Subtarget->hasApertureRegs()) {
2438 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2439 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2440 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2441 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2442 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2443 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2445 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2446 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2447 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2449 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2450 SDValue ApertureReg = SDValue(
2451 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2452 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2453 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2456 MachineFunction &MF = DAG.getMachineFunction();
2457 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2458 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2459 assert(UserSGPR != AMDGPU::NoRegister);
2461 SDValue QueuePtr = CreateLiveInRegister(
2462 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2464 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2465 // private_segment_aperture_base_hi.
2466 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2468 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2469 DAG.getConstant(StructOffset, DL, MVT::i64));
2471 // TODO: Use custom target PseudoSourceValue.
2472 // TODO: We should use the value from the IR intrinsic call, but it might not
2473 // be available and how do we get it?
2474 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2475 AMDGPUASI.CONSTANT_ADDRESS));
2477 MachinePointerInfo PtrInfo(V, StructOffset);
2478 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2479 MinAlign(64, StructOffset),
2480 MachineMemOperand::MODereferenceable |
2481 MachineMemOperand::MOInvariant);
2484 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2485 SelectionDAG &DAG) const {
2487 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2489 SDValue Src = ASC->getOperand(0);
2490 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2492 const AMDGPUTargetMachine &TM =
2493 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2495 // flat -> local/private
2496 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2497 unsigned DestAS = ASC->getDestAddressSpace();
2499 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2500 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2501 unsigned NullVal = TM.getNullPointerValue(DestAS);
2502 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2503 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2504 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2506 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2507 NonNull, Ptr, SegmentNullPtr);
2511 // local/private -> flat
2512 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2513 unsigned SrcAS = ASC->getSrcAddressSpace();
2515 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2516 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2517 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2518 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2521 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2523 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2525 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2527 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2528 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2533 // global <-> flat are no-ops and never emitted.
2535 const MachineFunction &MF = DAG.getMachineFunction();
2536 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2537 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2538 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2540 return DAG.getUNDEF(ASC->getValueType(0));
2543 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 SDValue Idx = Op.getOperand(2);
2546 if (isa<ConstantSDNode>(Idx))
2549 // Avoid stack access for dynamic indexing.
2551 SDValue Vec = Op.getOperand(0);
2552 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2554 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2555 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2557 // Convert vector index to bit-index.
2558 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2559 DAG.getConstant(16, SL, MVT::i32));
2561 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2563 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2564 DAG.getConstant(0xffff, SL, MVT::i32),
2567 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2568 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2569 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2571 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2572 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2575 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2576 SelectionDAG &DAG) const {
2579 EVT ResultVT = Op.getValueType();
2580 SDValue Vec = Op.getOperand(0);
2581 SDValue Idx = Op.getOperand(1);
2583 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2584 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2586 if (CIdx->getZExtValue() == 1) {
2587 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2588 DAG.getConstant(16, SL, MVT::i32));
2590 assert(CIdx->getZExtValue() == 0);
2593 if (ResultVT.bitsLT(MVT::i32))
2594 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2595 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2598 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2600 // Convert vector index to bit-index.
2601 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2603 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2604 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2606 SDValue Result = Elt;
2607 if (ResultVT.bitsLT(MVT::i32))
2608 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2610 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2614 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2615 // We can fold offsets for anything that doesn't require a GOT relocation.
2616 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2617 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2618 !shouldEmitGOTReloc(GA->getGlobal());
2622 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2623 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2624 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2625 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2626 // lowered to the following code sequence:
2628 // For constant address space:
2629 // s_getpc_b64 s[0:1]
2630 // s_add_u32 s0, s0, $symbol
2631 // s_addc_u32 s1, s1, 0
2633 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2634 // a fixup or relocation is emitted to replace $symbol with a literal
2635 // constant, which is a pc-relative offset from the encoding of the $symbol
2636 // operand to the global variable.
2638 // For global address space:
2639 // s_getpc_b64 s[0:1]
2640 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2641 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2643 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2644 // fixups or relocations are emitted to replace $symbol@*@lo and
2645 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2646 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2647 // operand to the global variable.
2649 // What we want here is an offset from the value returned by s_getpc
2650 // (which is the address of the s_add_u32 instruction) to the global
2651 // variable, but since the encoding of $symbol starts 4 bytes after the start
2652 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2653 // small. This requires us to add 4 to the global variable offset in order to
2654 // compute the correct address.
2655 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2657 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2658 GAFlags == SIInstrInfo::MO_NONE ?
2659 GAFlags : GAFlags + 1);
2660 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2663 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2665 SelectionDAG &DAG) const {
2666 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2668 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2669 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2670 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2673 const GlobalValue *GV = GSD->getGlobal();
2674 EVT PtrVT = Op.getValueType();
2676 if (shouldEmitFixup(GV))
2677 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2678 else if (shouldEmitPCReloc(GV))
2679 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2680 SIInstrInfo::MO_REL32);
2682 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2683 SIInstrInfo::MO_GOTPCREL32);
2685 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2686 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2687 const DataLayout &DataLayout = DAG.getDataLayout();
2688 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2689 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2690 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2692 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2693 MachineMemOperand::MODereferenceable |
2694 MachineMemOperand::MOInvariant);
2697 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2698 const SDLoc &DL, SDValue V) const {
2699 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2700 // the destination register.
2702 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2703 // so we will end up with redundant moves to m0.
2705 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2707 // A Null SDValue creates a glue result.
2708 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2710 return SDValue(M0, 0);
2713 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2716 unsigned Offset) const {
2718 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2719 DAG.getEntryNode(), Offset, false);
2720 // The local size values will have the hi 16-bits as zero.
2721 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2722 DAG.getValueType(VT));
2725 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2727 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2728 "non-hsa intrinsic with hsa target",
2730 DAG.getContext()->diagnose(BadIntrin);
2731 return DAG.getUNDEF(VT);
2734 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2736 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2737 "intrinsic not supported on subtarget",
2739 DAG.getContext()->diagnose(BadIntrin);
2740 return DAG.getUNDEF(VT);
2743 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2744 SelectionDAG &DAG) const {
2745 MachineFunction &MF = DAG.getMachineFunction();
2746 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2747 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2749 EVT VT = Op.getValueType();
2751 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2753 // TODO: Should this propagate fast-math-flags?
2755 switch (IntrinsicID) {
2756 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2757 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2758 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2760 case Intrinsic::amdgcn_dispatch_ptr:
2761 case Intrinsic::amdgcn_queue_ptr: {
2762 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2763 DiagnosticInfoUnsupported BadIntrin(
2764 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2766 DAG.getContext()->diagnose(BadIntrin);
2767 return DAG.getUNDEF(VT);
2770 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2771 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2772 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2773 TRI->getPreloadedValue(MF, Reg), VT);
2775 case Intrinsic::amdgcn_implicitarg_ptr: {
2776 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2777 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2779 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2781 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2782 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2784 case Intrinsic::amdgcn_dispatch_id: {
2785 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2786 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2788 case Intrinsic::amdgcn_rcp:
2789 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2790 case Intrinsic::amdgcn_rsq:
2791 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2792 case Intrinsic::amdgcn_rsq_legacy:
2793 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2794 return emitRemovedIntrinsicError(DAG, DL, VT);
2796 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2797 case Intrinsic::amdgcn_rcp_legacy:
2798 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2799 return emitRemovedIntrinsicError(DAG, DL, VT);
2800 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2801 case Intrinsic::amdgcn_rsq_clamp: {
2802 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2803 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2805 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2806 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2807 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2809 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2810 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2811 DAG.getConstantFP(Max, DL, VT));
2812 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2813 DAG.getConstantFP(Min, DL, VT));
2815 case Intrinsic::r600_read_ngroups_x:
2816 if (Subtarget->isAmdHsaOS())
2817 return emitNonHSAIntrinsicError(DAG, DL, VT);
2819 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2820 SI::KernelInputOffsets::NGROUPS_X, false);
2821 case Intrinsic::r600_read_ngroups_y:
2822 if (Subtarget->isAmdHsaOS())
2823 return emitNonHSAIntrinsicError(DAG, DL, VT);
2825 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2826 SI::KernelInputOffsets::NGROUPS_Y, false);
2827 case Intrinsic::r600_read_ngroups_z:
2828 if (Subtarget->isAmdHsaOS())
2829 return emitNonHSAIntrinsicError(DAG, DL, VT);
2831 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2832 SI::KernelInputOffsets::NGROUPS_Z, false);
2833 case Intrinsic::r600_read_global_size_x:
2834 if (Subtarget->isAmdHsaOS())
2835 return emitNonHSAIntrinsicError(DAG, DL, VT);
2837 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2838 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2839 case Intrinsic::r600_read_global_size_y:
2840 if (Subtarget->isAmdHsaOS())
2841 return emitNonHSAIntrinsicError(DAG, DL, VT);
2843 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2844 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2845 case Intrinsic::r600_read_global_size_z:
2846 if (Subtarget->isAmdHsaOS())
2847 return emitNonHSAIntrinsicError(DAG, DL, VT);
2849 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2850 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2851 case Intrinsic::r600_read_local_size_x:
2852 if (Subtarget->isAmdHsaOS())
2853 return emitNonHSAIntrinsicError(DAG, DL, VT);
2855 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2856 SI::KernelInputOffsets::LOCAL_SIZE_X);
2857 case Intrinsic::r600_read_local_size_y:
2858 if (Subtarget->isAmdHsaOS())
2859 return emitNonHSAIntrinsicError(DAG, DL, VT);
2861 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2862 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2863 case Intrinsic::r600_read_local_size_z:
2864 if (Subtarget->isAmdHsaOS())
2865 return emitNonHSAIntrinsicError(DAG, DL, VT);
2867 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2868 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2869 case Intrinsic::amdgcn_workgroup_id_x:
2870 case Intrinsic::r600_read_tgid_x:
2871 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2872 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2873 case Intrinsic::amdgcn_workgroup_id_y:
2874 case Intrinsic::r600_read_tgid_y:
2875 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2876 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2877 case Intrinsic::amdgcn_workgroup_id_z:
2878 case Intrinsic::r600_read_tgid_z:
2879 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2880 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2881 case Intrinsic::amdgcn_workitem_id_x:
2882 case Intrinsic::r600_read_tidig_x:
2883 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2884 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2885 case Intrinsic::amdgcn_workitem_id_y:
2886 case Intrinsic::r600_read_tidig_y:
2887 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2888 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2889 case Intrinsic::amdgcn_workitem_id_z:
2890 case Intrinsic::r600_read_tidig_z:
2891 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2892 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2893 case AMDGPUIntrinsic::SI_load_const: {
2899 MachineMemOperand *MMO = MF.getMachineMemOperand(
2900 MachinePointerInfo(),
2901 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2902 MachineMemOperand::MOInvariant,
2903 VT.getStoreSize(), 4);
2904 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2905 Op->getVTList(), Ops, VT, MMO);
2907 case Intrinsic::amdgcn_fdiv_fast:
2908 return lowerFDIV_FAST(Op, DAG);
2909 case Intrinsic::amdgcn_interp_mov: {
2910 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2911 SDValue Glue = M0.getValue(1);
2912 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2913 Op.getOperand(2), Op.getOperand(3), Glue);
2915 case Intrinsic::amdgcn_interp_p1: {
2916 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2917 SDValue Glue = M0.getValue(1);
2918 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2919 Op.getOperand(2), Op.getOperand(3), Glue);
2921 case Intrinsic::amdgcn_interp_p2: {
2922 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2923 SDValue Glue = SDValue(M0.getNode(), 1);
2924 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2925 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2928 case Intrinsic::amdgcn_sin:
2929 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2931 case Intrinsic::amdgcn_cos:
2932 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2934 case Intrinsic::amdgcn_log_clamp: {
2935 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2938 DiagnosticInfoUnsupported BadIntrin(
2939 *MF.getFunction(), "intrinsic not supported on subtarget",
2941 DAG.getContext()->diagnose(BadIntrin);
2942 return DAG.getUNDEF(VT);
2944 case Intrinsic::amdgcn_ldexp:
2945 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2946 Op.getOperand(1), Op.getOperand(2));
2948 case Intrinsic::amdgcn_fract:
2949 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2951 case Intrinsic::amdgcn_class:
2952 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2953 Op.getOperand(1), Op.getOperand(2));
2954 case Intrinsic::amdgcn_div_fmas:
2955 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2956 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2959 case Intrinsic::amdgcn_div_fixup:
2960 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2961 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2963 case Intrinsic::amdgcn_trig_preop:
2964 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2965 Op.getOperand(1), Op.getOperand(2));
2966 case Intrinsic::amdgcn_div_scale: {
2967 // 3rd parameter required to be a constant.
2968 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2970 return DAG.getUNDEF(VT);
2972 // Translate to the operands expected by the machine instruction. The
2973 // first parameter must be the same as the first instruction.
2974 SDValue Numerator = Op.getOperand(1);
2975 SDValue Denominator = Op.getOperand(2);
2977 // Note this order is opposite of the machine instruction's operations,
2978 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2979 // intrinsic has the numerator as the first operand to match a normal
2980 // division operation.
2982 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2984 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2985 Denominator, Numerator);
2987 case Intrinsic::amdgcn_icmp: {
2988 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2990 return DAG.getUNDEF(VT);
2992 int CondCode = CD->getSExtValue();
2993 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2994 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
2995 return DAG.getUNDEF(VT);
2997 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2998 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2999 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3000 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3002 case Intrinsic::amdgcn_fcmp: {
3003 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3005 return DAG.getUNDEF(VT);
3007 int CondCode = CD->getSExtValue();
3008 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3009 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
3010 return DAG.getUNDEF(VT);
3012 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3013 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3014 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3015 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3017 case Intrinsic::amdgcn_fmed3:
3018 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
3019 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3020 case Intrinsic::amdgcn_fmul_legacy:
3021 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
3022 Op.getOperand(1), Op.getOperand(2));
3023 case Intrinsic::amdgcn_sffbh:
3024 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
3025 case Intrinsic::amdgcn_sbfe:
3026 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
3027 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3028 case Intrinsic::amdgcn_ubfe:
3029 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3030 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3031 case Intrinsic::amdgcn_cvt_pkrtz: {
3032 // FIXME: Stop adding cast if v2f16 legal.
3033 EVT VT = Op.getValueType();
3034 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3035 Op.getOperand(1), Op.getOperand(2));
3036 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3043 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3044 SelectionDAG &DAG) const {
3045 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3048 case Intrinsic::amdgcn_atomic_inc:
3049 case Intrinsic::amdgcn_atomic_dec: {
3050 MemSDNode *M = cast<MemSDNode>(Op);
3051 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3052 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3054 M->getOperand(0), // Chain
3055 M->getOperand(2), // Ptr
3056 M->getOperand(3) // Value
3059 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3060 M->getMemoryVT(), M->getMemOperand());
3062 case Intrinsic::amdgcn_buffer_load:
3063 case Intrinsic::amdgcn_buffer_load_format: {
3065 Op.getOperand(0), // Chain
3066 Op.getOperand(2), // rsrc
3067 Op.getOperand(3), // vindex
3068 Op.getOperand(4), // offset
3069 Op.getOperand(5), // glc
3070 Op.getOperand(6) // slc
3072 MachineFunction &MF = DAG.getMachineFunction();
3073 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3075 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3076 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3077 EVT VT = Op.getValueType();
3078 EVT IntVT = VT.changeTypeToInteger();
3080 MachineMemOperand *MMO = MF.getMachineMemOperand(
3081 MachinePointerInfo(MFI->getBufferPSV()),
3082 MachineMemOperand::MOLoad,
3083 VT.getStoreSize(), VT.getStoreSize());
3085 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3088 case Intrinsic::amdgcn_image_sample:
3089 case Intrinsic::amdgcn_image_sample_cl:
3090 case Intrinsic::amdgcn_image_sample_d:
3091 case Intrinsic::amdgcn_image_sample_d_cl:
3092 case Intrinsic::amdgcn_image_sample_l:
3093 case Intrinsic::amdgcn_image_sample_b:
3094 case Intrinsic::amdgcn_image_sample_b_cl:
3095 case Intrinsic::amdgcn_image_sample_lz:
3096 case Intrinsic::amdgcn_image_sample_cd:
3097 case Intrinsic::amdgcn_image_sample_cd_cl:
3099 // Sample with comparison.
3100 case Intrinsic::amdgcn_image_sample_c:
3101 case Intrinsic::amdgcn_image_sample_c_cl:
3102 case Intrinsic::amdgcn_image_sample_c_d:
3103 case Intrinsic::amdgcn_image_sample_c_d_cl:
3104 case Intrinsic::amdgcn_image_sample_c_l:
3105 case Intrinsic::amdgcn_image_sample_c_b:
3106 case Intrinsic::amdgcn_image_sample_c_b_cl:
3107 case Intrinsic::amdgcn_image_sample_c_lz:
3108 case Intrinsic::amdgcn_image_sample_c_cd:
3109 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3111 // Sample with offsets.
3112 case Intrinsic::amdgcn_image_sample_o:
3113 case Intrinsic::amdgcn_image_sample_cl_o:
3114 case Intrinsic::amdgcn_image_sample_d_o:
3115 case Intrinsic::amdgcn_image_sample_d_cl_o:
3116 case Intrinsic::amdgcn_image_sample_l_o:
3117 case Intrinsic::amdgcn_image_sample_b_o:
3118 case Intrinsic::amdgcn_image_sample_b_cl_o:
3119 case Intrinsic::amdgcn_image_sample_lz_o:
3120 case Intrinsic::amdgcn_image_sample_cd_o:
3121 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3123 // Sample with comparison and offsets.
3124 case Intrinsic::amdgcn_image_sample_c_o:
3125 case Intrinsic::amdgcn_image_sample_c_cl_o:
3126 case Intrinsic::amdgcn_image_sample_c_d_o:
3127 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3128 case Intrinsic::amdgcn_image_sample_c_l_o:
3129 case Intrinsic::amdgcn_image_sample_c_b_o:
3130 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3131 case Intrinsic::amdgcn_image_sample_c_lz_o:
3132 case Intrinsic::amdgcn_image_sample_c_cd_o:
3133 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3135 case Intrinsic::amdgcn_image_getlod: {
3136 // Replace dmask with everything disabled with undef.
3137 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3138 if (!DMask || DMask->isNullValue()) {
3139 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3140 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3150 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3151 SelectionDAG &DAG) const {
3152 MachineFunction &MF = DAG.getMachineFunction();
3154 SDValue Chain = Op.getOperand(0);
3155 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3157 switch (IntrinsicID) {
3158 case Intrinsic::amdgcn_exp: {
3159 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3160 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3161 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3162 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3164 const SDValue Ops[] = {
3166 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3167 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3168 Op.getOperand(4), // src0
3169 Op.getOperand(5), // src1
3170 Op.getOperand(6), // src2
3171 Op.getOperand(7), // src3
3172 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3173 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3176 unsigned Opc = Done->isNullValue() ?
3177 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3178 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3180 case Intrinsic::amdgcn_exp_compr: {
3181 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3182 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3183 SDValue Src0 = Op.getOperand(4);
3184 SDValue Src1 = Op.getOperand(5);
3185 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3186 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3188 SDValue Undef = DAG.getUNDEF(MVT::f32);
3189 const SDValue Ops[] = {
3191 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3192 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3193 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3194 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3197 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3198 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3201 unsigned Opc = Done->isNullValue() ?
3202 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3203 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3205 case Intrinsic::amdgcn_s_sendmsg:
3206 case Intrinsic::amdgcn_s_sendmsghalt: {
3207 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3208 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3209 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3210 SDValue Glue = Chain.getValue(1);
3211 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3212 Op.getOperand(2), Glue);
3214 case AMDGPUIntrinsic::SI_tbuffer_store: {
3232 EVT VT = Op.getOperand(3).getValueType();
3234 MachineMemOperand *MMO = MF.getMachineMemOperand(
3235 MachinePointerInfo(),
3236 MachineMemOperand::MOStore,
3237 VT.getStoreSize(), 4);
3238 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3239 Op->getVTList(), Ops, VT, MMO);
3241 case AMDGPUIntrinsic::AMDGPU_kill: {
3242 SDValue Src = Op.getOperand(2);
3243 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3244 if (!K->isNegative())
3247 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3248 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3251 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3252 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3254 case Intrinsic::amdgcn_s_barrier: {
3255 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3256 const MachineFunction &MF = DAG.getMachineFunction();
3257 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3258 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3259 if (WGSize <= ST.getWavefrontSize())
3260 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3261 Op.getOperand(0)), 0);
3270 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3272 LoadSDNode *Load = cast<LoadSDNode>(Op);
3273 ISD::LoadExtType ExtType = Load->getExtensionType();
3274 EVT MemVT = Load->getMemoryVT();
3276 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3277 // FIXME: Copied from PPC
3278 // First, load into 32 bits, then truncate to 1 bit.
3280 SDValue Chain = Load->getChain();
3281 SDValue BasePtr = Load->getBasePtr();
3282 MachineMemOperand *MMO = Load->getMemOperand();
3284 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3286 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3287 BasePtr, RealMemVT, MMO);
3290 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3294 return DAG.getMergeValues(Ops, DL);
3297 if (!MemVT.isVector())
3300 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3301 "Custom lowering for non-i32 vectors hasn't been implemented.");
3303 unsigned AS = Load->getAddressSpace();
3304 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3305 AS, Load->getAlignment())) {
3307 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3308 return DAG.getMergeValues(Ops, DL);
3311 MachineFunction &MF = DAG.getMachineFunction();
3312 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3313 // If there is a possibilty that flat instruction access scratch memory
3314 // then we need to use the same legalization rules we use for private.
3315 if (AS == AMDGPUASI.FLAT_ADDRESS)
3316 AS = MFI->hasFlatScratchInit() ?
3317 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3319 unsigned NumElements = MemVT.getVectorNumElements();
3320 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3321 if (isMemOpUniform(Load))
3323 // Non-uniform loads will be selected to MUBUF instructions, so they
3324 // have the same legalization requirements as global and private
3328 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3329 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3330 isMemOpHasNoClobberedMemOperand(Load))
3332 // Non-uniform loads will be selected to MUBUF instructions, so they
3333 // have the same legalization requirements as global and private
3337 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3338 AS == AMDGPUASI.FLAT_ADDRESS) {
3339 if (NumElements > 4)
3340 return SplitVectorLoad(Op, DAG);
3341 // v4 loads are supported for private and global memory.
3344 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3345 // Depending on the setting of the private_element_size field in the
3346 // resource descriptor, we can only make private accesses up to a certain
3348 switch (Subtarget->getMaxPrivateElementSize()) {
3350 return scalarizeVectorLoad(Load, DAG);
3352 if (NumElements > 2)
3353 return SplitVectorLoad(Op, DAG);
3356 // Same as global/flat
3357 if (NumElements > 4)
3358 return SplitVectorLoad(Op, DAG);
3361 llvm_unreachable("unsupported private_element_size");
3363 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3364 if (NumElements > 2)
3365 return SplitVectorLoad(Op, DAG);
3367 if (NumElements == 2)
3370 // If properly aligned, if we split we might be able to use ds_read_b64.
3371 return SplitVectorLoad(Op, DAG);
3376 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3377 if (Op.getValueType() != MVT::i64)
3381 SDValue Cond = Op.getOperand(0);
3383 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3384 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3386 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3387 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3389 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3390 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3392 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3394 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3395 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3397 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3399 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3400 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3403 // Catch division cases where we can use shortcuts with rcp and rsq
3405 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3406 SelectionDAG &DAG) const {
3408 SDValue LHS = Op.getOperand(0);
3409 SDValue RHS = Op.getOperand(1);
3410 EVT VT = Op.getValueType();
3411 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3413 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3414 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3416 if (CLHS->isExactlyValue(1.0)) {
3417 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3418 // the CI documentation has a worst case error of 1 ulp.
3419 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3420 // use it as long as we aren't trying to use denormals.
3422 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3424 // 1.0 / sqrt(x) -> rsq(x)
3426 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3427 // error seems really high at 2^29 ULP.
3428 if (RHS.getOpcode() == ISD::FSQRT)
3429 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3431 // 1.0 / x -> rcp(x)
3432 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3435 // Same as for 1.0, but expand the sign out of the constant.
3436 if (CLHS->isExactlyValue(-1.0)) {
3437 // -1.0 / x -> rcp (fneg x)
3438 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3439 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3444 const SDNodeFlags *Flags = Op->getFlags();
3446 if (Unsafe || Flags->hasAllowReciprocal()) {
3447 // Turn into multiply by the reciprocal.
3448 // x / y -> x * (1.0 / y)
3450 Flags.setUnsafeAlgebra(true);
3451 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3452 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3458 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3459 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3460 if (GlueChain->getNumValues() <= 1) {
3461 return DAG.getNode(Opcode, SL, VT, A, B);
3464 assert(GlueChain->getNumValues() == 3);
3466 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3468 default: llvm_unreachable("no chain equivalent for opcode");
3470 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3474 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3475 GlueChain.getValue(2));
3478 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3479 EVT VT, SDValue A, SDValue B, SDValue C,
3480 SDValue GlueChain) {
3481 if (GlueChain->getNumValues() <= 1) {
3482 return DAG.getNode(Opcode, SL, VT, A, B, C);
3485 assert(GlueChain->getNumValues() == 3);
3487 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3489 default: llvm_unreachable("no chain equivalent for opcode");
3491 Opcode = AMDGPUISD::FMA_W_CHAIN;
3495 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3496 GlueChain.getValue(2));
3499 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3500 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3504 SDValue Src0 = Op.getOperand(0);
3505 SDValue Src1 = Op.getOperand(1);
3507 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3508 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3510 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3511 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3513 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3514 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3516 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3519 // Faster 2.5 ULP division that does not support denormals.
3520 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3522 SDValue LHS = Op.getOperand(1);
3523 SDValue RHS = Op.getOperand(2);
3525 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3527 const APFloat K0Val(BitsToFloat(0x6f800000));
3528 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3530 const APFloat K1Val(BitsToFloat(0x2f800000));
3531 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3533 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3536 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3538 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3540 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3542 // TODO: Should this propagate fast-math-flags?
3543 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3545 // rcp does not support denormals.
3546 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3548 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3550 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3553 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3554 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3558 SDValue LHS = Op.getOperand(0);
3559 SDValue RHS = Op.getOperand(1);
3561 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3563 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3565 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3567 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3570 // Denominator is scaled to not be denormal, so using rcp is ok.
3571 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3573 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3576 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3577 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3578 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3580 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3582 if (!Subtarget->hasFP32Denormals()) {
3583 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3584 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3586 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3588 EnableDenormValue, BitField);
3591 EnableDenorm.getValue(0),
3592 EnableDenorm.getValue(1)
3595 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3598 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3599 ApproxRcp, One, NegDivScale0);
3601 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3604 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3607 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3608 NumeratorScaled, Mul);
3610 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3612 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3613 NumeratorScaled, Fma3);
3615 if (!Subtarget->hasFP32Denormals()) {
3616 const SDValue DisableDenormValue =
3617 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3618 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3624 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3625 DisableDenorm, DAG.getRoot());
3626 DAG.setRoot(OutputChain);
3629 SDValue Scale = NumeratorScaled.getValue(1);
3630 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3631 Fma4, Fma1, Fma3, Scale);
3633 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3636 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3637 if (DAG.getTarget().Options.UnsafeFPMath)
3638 return lowerFastUnsafeFDIV(Op, DAG);
3641 SDValue X = Op.getOperand(0);
3642 SDValue Y = Op.getOperand(1);
3644 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3646 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3648 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3650 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3652 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3654 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3656 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3658 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3660 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3662 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3663 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3665 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3666 NegDivScale0, Mul, DivScale1);
3670 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3671 // Workaround a hardware bug on SI where the condition output from div_scale
3674 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3676 // Figure out if the scale to use for div_fmas.
3677 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3678 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3679 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3680 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3682 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3683 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3686 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3688 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3690 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3691 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3692 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3694 Scale = DivScale1.getValue(1);
3697 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3698 Fma4, Fma3, Mul, Scale);
3700 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3703 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3704 EVT VT = Op.getValueType();
3707 return LowerFDIV32(Op, DAG);
3710 return LowerFDIV64(Op, DAG);
3713 return LowerFDIV16(Op, DAG);
3715 llvm_unreachable("Unexpected type for fdiv");
3718 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3720 StoreSDNode *Store = cast<StoreSDNode>(Op);
3721 EVT VT = Store->getMemoryVT();
3723 if (VT == MVT::i1) {
3724 return DAG.getTruncStore(Store->getChain(), DL,
3725 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3726 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3729 assert(VT.isVector() &&
3730 Store->getValue().getValueType().getScalarType() == MVT::i32);
3732 unsigned AS = Store->getAddressSpace();
3733 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3734 AS, Store->getAlignment())) {
3735 return expandUnalignedStore(Store, DAG);
3738 MachineFunction &MF = DAG.getMachineFunction();
3739 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3740 // If there is a possibilty that flat instruction access scratch memory
3741 // then we need to use the same legalization rules we use for private.
3742 if (AS == AMDGPUASI.FLAT_ADDRESS)
3743 AS = MFI->hasFlatScratchInit() ?
3744 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3746 unsigned NumElements = VT.getVectorNumElements();
3747 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3748 AS == AMDGPUASI.FLAT_ADDRESS) {
3749 if (NumElements > 4)
3750 return SplitVectorStore(Op, DAG);
3752 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3753 switch (Subtarget->getMaxPrivateElementSize()) {
3755 return scalarizeVectorStore(Store, DAG);
3757 if (NumElements > 2)
3758 return SplitVectorStore(Op, DAG);
3761 if (NumElements > 4)
3762 return SplitVectorStore(Op, DAG);
3765 llvm_unreachable("unsupported private_element_size");
3767 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3768 if (NumElements > 2)
3769 return SplitVectorStore(Op, DAG);
3771 if (NumElements == 2)
3774 // If properly aligned, if we split we might be able to use ds_write_b64.
3775 return SplitVectorStore(Op, DAG);
3777 llvm_unreachable("unhandled address space");
3781 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3783 EVT VT = Op.getValueType();
3784 SDValue Arg = Op.getOperand(0);
3785 // TODO: Should this propagate fast-math-flags?
3786 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3787 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3788 DAG.getConstantFP(0.5/M_PI, DL,
3791 switch (Op.getOpcode()) {
3793 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3795 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3797 llvm_unreachable("Wrong trig opcode");
3801 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3802 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3803 assert(AtomicNode->isCompareAndSwap());
3804 unsigned AS = AtomicNode->getAddressSpace();
3806 // No custom lowering required for local address space
3807 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
3810 // Non-local address space requires custom lowering for atomic compare
3811 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3813 SDValue ChainIn = Op.getOperand(0);
3814 SDValue Addr = Op.getOperand(1);
3815 SDValue Old = Op.getOperand(2);
3816 SDValue New = Op.getOperand(3);
3817 EVT VT = Op.getValueType();
3818 MVT SimpleVT = VT.getSimpleVT();
3819 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3821 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3822 SDValue Ops[] = { ChainIn, Addr, NewOld };
3824 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3825 Ops, VT, AtomicNode->getMemOperand());
3828 //===----------------------------------------------------------------------===//
3829 // Custom DAG optimizations
3830 //===----------------------------------------------------------------------===//
3832 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3833 DAGCombinerInfo &DCI) const {
3834 EVT VT = N->getValueType(0);
3835 EVT ScalarVT = VT.getScalarType();
3836 if (ScalarVT != MVT::f32)
3839 SelectionDAG &DAG = DCI.DAG;
3842 SDValue Src = N->getOperand(0);
3843 EVT SrcVT = Src.getValueType();
3845 // TODO: We could try to match extracting the higher bytes, which would be
3846 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3847 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3848 // about in practice.
3849 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3850 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3851 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3852 DCI.AddToWorklist(Cvt.getNode());
3860 /// \brief Return true if the given offset Size in bytes can be folded into
3861 /// the immediate offsets of a memory instruction for the given address space.
3862 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3863 const SISubtarget &STI) {
3864 auto AMDGPUASI = STI.getAMDGPUAS();
3865 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
3866 // MUBUF instructions a 12-bit offset in bytes.
3867 return isUInt<12>(OffsetSize);
3869 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3870 // SMRD instructions have an 8-bit offset in dwords on SI and
3871 // a 20-bit offset in bytes on VI.
3872 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3873 return isUInt<20>(OffsetSize);
3875 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3877 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
3878 AS == AMDGPUASI.REGION_ADDRESS) {
3879 // The single offset versions have a 16-bit offset in bytes.
3880 return isUInt<16>(OffsetSize);
3882 // Indirect register addressing does not use any offsets.
3886 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3888 // This is a variant of
3889 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3891 // The normal DAG combiner will do this, but only if the add has one use since
3892 // that would increase the number of instructions.
3894 // This prevents us from seeing a constant offset that can be folded into a
3895 // memory instruction's addressing mode. If we know the resulting add offset of
3896 // a pointer can be folded into an addressing offset, we can replace the pointer
3897 // operand with the add of new constant offset. This eliminates one of the uses,
3898 // and may allow the remaining use to also be simplified.
3900 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3902 DAGCombinerInfo &DCI) const {
3903 SDValue N0 = N->getOperand(0);
3904 SDValue N1 = N->getOperand(1);
3906 if (N0.getOpcode() != ISD::ADD)
3909 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3913 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3917 // If the resulting offset is too large, we can't fold it into the addressing
3919 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3920 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3923 SelectionDAG &DAG = DCI.DAG;
3925 EVT VT = N->getValueType(0);
3927 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3928 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3930 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3933 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3934 DAGCombinerInfo &DCI) const {
3935 SDValue Ptr = N->getBasePtr();
3936 SelectionDAG &DAG = DCI.DAG;
3939 // TODO: We could also do this for multiplies.
3940 unsigned AS = N->getAddressSpace();
3941 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
3942 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3944 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3946 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3947 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3954 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3955 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3956 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3957 (Opc == ISD::XOR && Val == 0);
3960 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3961 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3962 // integer combine opportunities since most 64-bit operations are decomposed
3963 // this way. TODO: We won't want this for SALU especially if it is an inline
3965 SDValue SITargetLowering::splitBinaryBitConstantOp(
3966 DAGCombinerInfo &DCI,
3968 unsigned Opc, SDValue LHS,
3969 const ConstantSDNode *CRHS) const {
3970 uint64_t Val = CRHS->getZExtValue();
3971 uint32_t ValLo = Lo_32(Val);
3972 uint32_t ValHi = Hi_32(Val);
3973 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3975 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3976 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3977 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3978 // If we need to materialize a 64-bit immediate, it will be split up later
3979 // anyway. Avoid creating the harder to understand 64-bit immediate
3981 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3987 SDValue SITargetLowering::performAndCombine(SDNode *N,
3988 DAGCombinerInfo &DCI) const {
3989 if (DCI.isBeforeLegalize())
3992 SelectionDAG &DAG = DCI.DAG;
3993 EVT VT = N->getValueType(0);
3994 SDValue LHS = N->getOperand(0);
3995 SDValue RHS = N->getOperand(1);
3998 if (VT == MVT::i64) {
3999 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4002 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
4007 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
4008 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
4009 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
4010 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
4011 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
4013 SDValue X = LHS.getOperand(0);
4014 SDValue Y = RHS.getOperand(0);
4015 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
4018 if (LCC == ISD::SETO) {
4019 if (X != LHS.getOperand(1))
4022 if (RCC == ISD::SETUNE) {
4023 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
4024 if (!C1 || !C1->isInfinity() || C1->isNegative())
4027 const uint32_t Mask = SIInstrFlags::N_NORMAL |
4028 SIInstrFlags::N_SUBNORMAL |
4029 SIInstrFlags::N_ZERO |
4030 SIInstrFlags::P_ZERO |
4031 SIInstrFlags::P_SUBNORMAL |
4032 SIInstrFlags::P_NORMAL;
4034 static_assert(((~(SIInstrFlags::S_NAN |
4035 SIInstrFlags::Q_NAN |
4036 SIInstrFlags::N_INFINITY |
4037 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4041 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4042 X, DAG.getConstant(Mask, DL, MVT::i32));
4050 SDValue SITargetLowering::performOrCombine(SDNode *N,
4051 DAGCombinerInfo &DCI) const {
4052 SelectionDAG &DAG = DCI.DAG;
4053 SDValue LHS = N->getOperand(0);
4054 SDValue RHS = N->getOperand(1);
4056 EVT VT = N->getValueType(0);
4057 if (VT == MVT::i1) {
4058 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4059 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4060 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4061 SDValue Src = LHS.getOperand(0);
4062 if (Src != RHS.getOperand(0))
4065 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4066 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4070 // Only 10 bits are used.
4071 static const uint32_t MaxMask = 0x3ff;
4073 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4075 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4076 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4085 // TODO: This could be a generic combine with a predicate for extracting the
4086 // high half of an integer being free.
4088 // (or i64:x, (zero_extend i32:y)) ->
4089 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4090 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4091 RHS.getOpcode() != ISD::ZERO_EXTEND)
4092 std::swap(LHS, RHS);
4094 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4095 SDValue ExtSrc = RHS.getOperand(0);
4096 EVT SrcVT = ExtSrc.getValueType();
4097 if (SrcVT == MVT::i32) {
4099 SDValue LowLHS, HiBits;
4100 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4101 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4103 DCI.AddToWorklist(LowOr.getNode());
4104 DCI.AddToWorklist(HiBits.getNode());
4106 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4108 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4112 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4115 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4122 SDValue SITargetLowering::performXorCombine(SDNode *N,
4123 DAGCombinerInfo &DCI) const {
4124 EVT VT = N->getValueType(0);
4128 SDValue LHS = N->getOperand(0);
4129 SDValue RHS = N->getOperand(1);
4131 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4134 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4141 // Instructions that will be lowered with a final instruction that zeros the
4142 // high result bits.
4143 // XXX - probably only need to list legal operations.
4144 static bool fp16SrcZerosHighBits(unsigned Opc) {
4153 case ISD::FCANONICALIZE:
4155 case ISD::UINT_TO_FP:
4156 case ISD::SINT_TO_FP:
4158 // Fabs is lowered to a bit operation, but it's an and which will clear the
4159 // high bits anyway.
4173 case ISD::FNEARBYINT:
4178 case AMDGPUISD::FRACT:
4179 case AMDGPUISD::CLAMP:
4180 case AMDGPUISD::COS_HW:
4181 case AMDGPUISD::SIN_HW:
4182 case AMDGPUISD::FMIN3:
4183 case AMDGPUISD::FMAX3:
4184 case AMDGPUISD::FMED3:
4185 case AMDGPUISD::FMAD_FTZ:
4186 case AMDGPUISD::RCP:
4187 case AMDGPUISD::RSQ:
4188 case AMDGPUISD::LDEXP:
4191 // fcopysign, select and others may be lowered to 32-bit bit operations
4192 // which don't zero the high bits.
4197 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4198 DAGCombinerInfo &DCI) const {
4199 if (!Subtarget->has16BitInsts() ||
4200 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4203 EVT VT = N->getValueType(0);
4207 SDValue Src = N->getOperand(0);
4208 if (Src.getValueType() != MVT::i16)
4211 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4212 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4213 if (Src.getOpcode() == ISD::BITCAST) {
4214 SDValue BCSrc = Src.getOperand(0);
4215 if (BCSrc.getValueType() == MVT::f16 &&
4216 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4217 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4223 SDValue SITargetLowering::performClassCombine(SDNode *N,
4224 DAGCombinerInfo &DCI) const {
4225 SelectionDAG &DAG = DCI.DAG;
4226 SDValue Mask = N->getOperand(1);
4228 // fp_class x, 0 -> false
4229 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4230 if (CMask->isNullValue())
4231 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4234 if (N->getOperand(0).isUndef())
4235 return DAG.getUNDEF(MVT::i1);
4240 // Constant fold canonicalize.
4241 SDValue SITargetLowering::performFCanonicalizeCombine(
4243 DAGCombinerInfo &DCI) const {
4244 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4248 SelectionDAG &DAG = DCI.DAG;
4249 const APFloat &C = CFP->getValueAPF();
4251 // Flush denormals to 0 if not enabled.
4252 if (C.isDenormal()) {
4253 EVT VT = N->getValueType(0);
4254 EVT SVT = VT.getScalarType();
4255 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4256 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4258 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4259 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4261 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4262 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4266 EVT VT = N->getValueType(0);
4267 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4268 if (C.isSignaling()) {
4269 // Quiet a signaling NaN.
4270 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4273 // Make sure it is the canonical NaN bitpattern.
4275 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4277 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4278 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4281 return N->getOperand(0);
4284 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4287 return AMDGPUISD::FMAX3;
4289 return AMDGPUISD::SMAX3;
4291 return AMDGPUISD::UMAX3;
4293 return AMDGPUISD::FMIN3;
4295 return AMDGPUISD::SMIN3;
4297 return AMDGPUISD::UMIN3;
4299 llvm_unreachable("Not a min/max opcode");
4303 SDValue SITargetLowering::performIntMed3ImmCombine(
4304 SelectionDAG &DAG, const SDLoc &SL,
4305 SDValue Op0, SDValue Op1, bool Signed) const {
4306 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4310 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4315 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4318 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4322 EVT VT = K0->getValueType(0);
4323 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4324 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4325 return DAG.getNode(Med3Opc, SL, VT,
4326 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4329 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4331 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4333 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4334 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4335 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4337 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4338 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4341 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4342 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4345 return DAG.isKnownNeverNaN(Op);
4348 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4351 SDValue Op1) const {
4352 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4356 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4360 // Ordered >= (although NaN inputs should have folded away by now).
4361 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4362 if (Cmp == APFloat::cmpGreaterThan)
4365 // TODO: Check IEEE bit enabled?
4366 EVT VT = K0->getValueType(0);
4367 if (Subtarget->enableDX10Clamp()) {
4368 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4369 // hardware fmed3 behavior converting to a min.
4370 // FIXME: Should this be allowing -0.0?
4371 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4372 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4375 // med3 for f16 is only available on gfx9+.
4376 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4379 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4380 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4381 // give the other result, which is different from med3 with a NaN input.
4382 SDValue Var = Op0.getOperand(0);
4383 if (!isKnownNeverSNan(DAG, Var))
4386 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4387 Var, SDValue(K0, 0), SDValue(K1, 0));
4390 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4391 DAGCombinerInfo &DCI) const {
4392 SelectionDAG &DAG = DCI.DAG;
4394 EVT VT = N->getValueType(0);
4395 unsigned Opc = N->getOpcode();
4396 SDValue Op0 = N->getOperand(0);
4397 SDValue Op1 = N->getOperand(1);
4399 // Only do this if the inner op has one use since this will just increases
4400 // register pressure for no benefit.
4403 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4405 // max(max(a, b), c) -> max3(a, b, c)
4406 // min(min(a, b), c) -> min3(a, b, c)
4407 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4409 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4418 // max(a, max(b, c)) -> max3(a, b, c)
4419 // min(a, min(b, c)) -> min3(a, b, c)
4420 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4422 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4431 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4432 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4433 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4437 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4438 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4442 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4443 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4444 (Opc == AMDGPUISD::FMIN_LEGACY &&
4445 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4446 (VT == MVT::f32 || VT == MVT::f64 ||
4447 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4449 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4456 static bool isClampZeroToOne(SDValue A, SDValue B) {
4457 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4458 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4459 // FIXME: Should this be allowing -0.0?
4460 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4461 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4468 // FIXME: Should only worry about snans for version with chain.
4469 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4470 DAGCombinerInfo &DCI) const {
4471 EVT VT = N->getValueType(0);
4472 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4473 // NaNs. With a NaN input, the order of the operands may change the result.
4475 SelectionDAG &DAG = DCI.DAG;
4478 SDValue Src0 = N->getOperand(0);
4479 SDValue Src1 = N->getOperand(1);
4480 SDValue Src2 = N->getOperand(2);
4482 if (isClampZeroToOne(Src0, Src1)) {
4483 // const_a, const_b, x -> clamp is safe in all cases including signaling
4485 // FIXME: Should this be allowing -0.0?
4486 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4489 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4490 // handling no dx10-clamp?
4491 if (Subtarget->enableDX10Clamp()) {
4492 // If NaNs is clamped to 0, we are free to reorder the inputs.
4494 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4495 std::swap(Src0, Src1);
4497 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4498 std::swap(Src1, Src2);
4500 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4501 std::swap(Src0, Src1);
4503 if (isClampZeroToOne(Src1, Src2))
4504 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4510 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4511 DAGCombinerInfo &DCI) const {
4512 SDValue Src0 = N->getOperand(0);
4513 SDValue Src1 = N->getOperand(1);
4514 if (Src0.isUndef() && Src1.isUndef())
4515 return DCI.DAG.getUNDEF(N->getValueType(0));
4519 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4521 const SDNode *N1) const {
4522 EVT VT = N0->getValueType(0);
4524 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4525 // support denormals ever.
4526 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4527 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4530 const TargetOptions &Options = DAG.getTarget().Options;
4531 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4532 Options.UnsafeFPMath ||
4533 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4534 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4535 isFMAFasterThanFMulAndFAdd(VT)) {
4542 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4543 DAGCombinerInfo &DCI) const {
4544 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4547 SelectionDAG &DAG = DCI.DAG;
4548 EVT VT = N->getValueType(0);
4551 SDValue LHS = N->getOperand(0);
4552 SDValue RHS = N->getOperand(1);
4554 // These should really be instruction patterns, but writing patterns with
4555 // source modiifiers is a pain.
4557 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4558 if (LHS.getOpcode() == ISD::FADD) {
4559 SDValue A = LHS.getOperand(0);
4560 if (A == LHS.getOperand(1)) {
4561 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4563 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4564 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4569 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4570 if (RHS.getOpcode() == ISD::FADD) {
4571 SDValue A = RHS.getOperand(0);
4572 if (A == RHS.getOperand(1)) {
4573 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4575 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4576 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4584 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4585 DAGCombinerInfo &DCI) const {
4586 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4589 SelectionDAG &DAG = DCI.DAG;
4591 EVT VT = N->getValueType(0);
4592 assert(!VT.isVector());
4594 // Try to get the fneg to fold into the source modifier. This undoes generic
4595 // DAG combines and folds them into the mad.
4597 // Only do this if we are not trying to support denormals. v_mad_f32 does
4598 // not support denormals ever.
4599 SDValue LHS = N->getOperand(0);
4600 SDValue RHS = N->getOperand(1);
4601 if (LHS.getOpcode() == ISD::FADD) {
4602 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4603 SDValue A = LHS.getOperand(0);
4604 if (A == LHS.getOperand(1)) {
4605 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4607 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4608 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4610 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4615 if (RHS.getOpcode() == ISD::FADD) {
4616 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4618 SDValue A = RHS.getOperand(0);
4619 if (A == RHS.getOperand(1)) {
4620 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4622 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4623 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4631 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4632 DAGCombinerInfo &DCI) const {
4633 SelectionDAG &DAG = DCI.DAG;
4636 SDValue LHS = N->getOperand(0);
4637 SDValue RHS = N->getOperand(1);
4638 EVT VT = LHS.getValueType();
4640 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4644 // Match isinf pattern
4645 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4646 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4647 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4648 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4652 const APFloat &APF = CRHS->getValueAPF();
4653 if (APF.isInfinity() && !APF.isNegative()) {
4654 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4655 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4656 DAG.getConstant(Mask, SL, MVT::i32));
4663 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4664 DAGCombinerInfo &DCI) const {
4665 SelectionDAG &DAG = DCI.DAG;
4667 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4669 SDValue Src = N->getOperand(0);
4670 SDValue Srl = N->getOperand(0);
4671 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4672 Srl = Srl.getOperand(0);
4674 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4675 if (Srl.getOpcode() == ISD::SRL) {
4676 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4677 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4678 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4680 if (const ConstantSDNode *C =
4681 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4682 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4685 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4686 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4687 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4693 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4695 APInt KnownZero, KnownOne;
4696 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4697 !DCI.isBeforeLegalizeOps());
4698 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4699 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4700 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4701 DCI.CommitTargetLoweringOpt(TLO);
4707 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4708 DAGCombinerInfo &DCI) const {
4709 switch (N->getOpcode()) {
4711 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4713 return performFAddCombine(N, DCI);
4715 return performFSubCombine(N, DCI);
4717 return performSetCCCombine(N, DCI);
4724 case AMDGPUISD::FMIN_LEGACY:
4725 case AMDGPUISD::FMAX_LEGACY: {
4726 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4727 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4728 return performMinMaxCombine(N, DCI);
4733 case ISD::ATOMIC_LOAD:
4734 case ISD::ATOMIC_STORE:
4735 case ISD::ATOMIC_CMP_SWAP:
4736 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4737 case ISD::ATOMIC_SWAP:
4738 case ISD::ATOMIC_LOAD_ADD:
4739 case ISD::ATOMIC_LOAD_SUB:
4740 case ISD::ATOMIC_LOAD_AND:
4741 case ISD::ATOMIC_LOAD_OR:
4742 case ISD::ATOMIC_LOAD_XOR:
4743 case ISD::ATOMIC_LOAD_NAND:
4744 case ISD::ATOMIC_LOAD_MIN:
4745 case ISD::ATOMIC_LOAD_MAX:
4746 case ISD::ATOMIC_LOAD_UMIN:
4747 case ISD::ATOMIC_LOAD_UMAX:
4748 case AMDGPUISD::ATOMIC_INC:
4749 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4750 if (DCI.isBeforeLegalize())
4752 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4754 return performAndCombine(N, DCI);
4756 return performOrCombine(N, DCI);
4758 return performXorCombine(N, DCI);
4759 case ISD::ZERO_EXTEND:
4760 return performZeroExtendCombine(N, DCI);
4761 case AMDGPUISD::FP_CLASS:
4762 return performClassCombine(N, DCI);
4763 case ISD::FCANONICALIZE:
4764 return performFCanonicalizeCombine(N, DCI);
4765 case AMDGPUISD::FRACT:
4766 case AMDGPUISD::RCP:
4767 case AMDGPUISD::RSQ:
4768 case AMDGPUISD::RCP_LEGACY:
4769 case AMDGPUISD::RSQ_LEGACY:
4770 case AMDGPUISD::RSQ_CLAMP:
4771 case AMDGPUISD::LDEXP: {
4772 SDValue Src = N->getOperand(0);
4777 case ISD::SINT_TO_FP:
4778 case ISD::UINT_TO_FP:
4779 return performUCharToFloatCombine(N, DCI);
4780 case AMDGPUISD::CVT_F32_UBYTE0:
4781 case AMDGPUISD::CVT_F32_UBYTE1:
4782 case AMDGPUISD::CVT_F32_UBYTE2:
4783 case AMDGPUISD::CVT_F32_UBYTE3:
4784 return performCvtF32UByteNCombine(N, DCI);
4785 case AMDGPUISD::FMED3:
4786 return performFMed3Combine(N, DCI);
4787 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4788 return performCvtPkRTZCombine(N, DCI);
4789 case ISD::SCALAR_TO_VECTOR: {
4790 SelectionDAG &DAG = DCI.DAG;
4791 EVT VT = N->getValueType(0);
4793 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4794 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4796 SDValue Src = N->getOperand(0);
4797 EVT EltVT = Src.getValueType();
4798 if (EltVT == MVT::f16)
4799 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4801 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4802 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4808 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4811 /// \brief Helper function for adjustWritemask
4812 static unsigned SubIdx2Lane(unsigned Idx) {
4815 case AMDGPU::sub0: return 0;
4816 case AMDGPU::sub1: return 1;
4817 case AMDGPU::sub2: return 2;
4818 case AMDGPU::sub3: return 3;
4822 /// \brief Adjust the writemask of MIMG instructions
4823 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4824 SelectionDAG &DAG) const {
4825 SDNode *Users[4] = { };
4827 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4828 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4829 unsigned NewDmask = 0;
4831 // Try to figure out the used register components
4832 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4835 // Don't look at users of the chain.
4836 if (I.getUse().getResNo() != 0)
4839 // Abort if we can't understand the usage
4840 if (!I->isMachineOpcode() ||
4841 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4844 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4845 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4846 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4848 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4850 // Set which texture component corresponds to the lane.
4852 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4854 Comp = countTrailingZeros(Dmask);
4855 Dmask &= ~(1 << Comp);
4858 // Abort if we have more than one user per component
4863 NewDmask |= 1 << Comp;
4866 // Abort if there's no change
4867 if (NewDmask == OldDmask)
4870 // Adjust the writemask in the node
4871 std::vector<SDValue> Ops;
4872 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4873 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4874 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4875 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4877 // If we only got one lane, replace it with a copy
4878 // (if NewDmask has only one bit set...)
4879 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4880 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4882 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4883 SDLoc(), Users[Lane]->getValueType(0),
4884 SDValue(Node, 0), RC);
4885 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4889 // Update the users of the node with the new indices
4890 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4891 SDNode *User = Users[i];
4895 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4896 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4900 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4901 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4902 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4907 static bool isFrameIndexOp(SDValue Op) {
4908 if (Op.getOpcode() == ISD::AssertZext)
4909 Op = Op.getOperand(0);
4911 return isa<FrameIndexSDNode>(Op);
4914 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4915 /// with frame index operands.
4916 /// LLVM assumes that inputs are to these instructions are registers.
4917 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4918 SelectionDAG &DAG) const {
4919 if (Node->getOpcode() == ISD::CopyToReg) {
4920 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
4921 SDValue SrcVal = Node->getOperand(2);
4923 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
4924 // to try understanding copies to physical registers.
4925 if (SrcVal.getValueType() == MVT::i1 &&
4926 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
4928 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
4929 SDValue VReg = DAG.getRegister(
4930 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
4932 SDNode *Glued = Node->getGluedNode();
4934 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
4935 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
4937 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
4938 VReg, ToVReg.getValue(1));
4939 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
4940 DAG.RemoveDeadNode(Node);
4941 return ToResultReg.getNode();
4945 SmallVector<SDValue, 8> Ops;
4946 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4947 if (!isFrameIndexOp(Node->getOperand(i))) {
4948 Ops.push_back(Node->getOperand(i));
4953 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4954 Node->getOperand(i).getValueType(),
4955 Node->getOperand(i)), 0));
4958 DAG.UpdateNodeOperands(Node, Ops);
4962 /// \brief Fold the instructions after selecting them.
4963 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4964 SelectionDAG &DAG) const {
4965 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4966 unsigned Opcode = Node->getMachineOpcode();
4968 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4969 !TII->isGather4(Opcode))
4970 adjustWritemask(Node, DAG);
4972 if (Opcode == AMDGPU::INSERT_SUBREG ||
4973 Opcode == AMDGPU::REG_SEQUENCE) {
4974 legalizeTargetIndependentNode(Node, DAG);
4980 /// \brief Assign the register class depending on the number of
4981 /// bits set in the writemask
4982 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4983 SDNode *Node) const {
4984 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4986 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4988 if (TII->isVOP3(MI.getOpcode())) {
4989 // Make sure constant bus requirements are respected.
4990 TII->legalizeOperandsVOP3(MRI, MI);
4994 if (TII->isMIMG(MI)) {
4995 unsigned VReg = MI.getOperand(0).getReg();
4996 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4997 // TODO: Need mapping tables to handle other cases (register classes).
4998 if (RC != &AMDGPU::VReg_128RegClass)
5001 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
5002 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
5003 unsigned BitsSet = 0;
5004 for (unsigned i = 0; i < 4; ++i)
5005 BitsSet += Writemask & (1 << i) ? 1 : 0;
5008 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
5009 case 2: RC = &AMDGPU::VReg_64RegClass; break;
5010 case 3: RC = &AMDGPU::VReg_96RegClass; break;
5013 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
5014 MI.setDesc(TII->get(NewOpcode));
5015 MRI.setRegClass(VReg, RC);
5019 // Replace unused atomics with the no return version.
5020 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
5021 if (NoRetAtomicOp != -1) {
5022 if (!Node->hasAnyUseOfValue(0)) {
5023 MI.setDesc(TII->get(NoRetAtomicOp));
5024 MI.RemoveOperand(0);
5028 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5029 // instruction, because the return type of these instructions is a vec2 of
5030 // the memory type, so it can be tied to the input operand.
5031 // This means these instructions always have a use, so we need to add a
5032 // special case to check if the atomic has only one extract_subreg use,
5033 // which itself has no uses.
5034 if ((Node->hasNUsesOfValue(1, 0) &&
5035 Node->use_begin()->isMachineOpcode() &&
5036 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5037 !Node->use_begin()->hasAnyUseOfValue(0))) {
5038 unsigned Def = MI.getOperand(0).getReg();
5040 // Change this into a noret atomic.
5041 MI.setDesc(TII->get(NoRetAtomicOp));
5042 MI.RemoveOperand(0);
5044 // If we only remove the def operand from the atomic instruction, the
5045 // extract_subreg will be left with a use of a vreg without a def.
5046 // So we need to insert an implicit_def to avoid machine verifier
5048 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5049 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5055 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5057 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5058 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5061 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5063 SDValue Ptr) const {
5064 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5066 // Build the half of the subregister with the constants before building the
5067 // full 128-bit register. If we are building multiple resource descriptors,
5068 // this will allow CSEing of the 2-component register.
5069 const SDValue Ops0[] = {
5070 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5071 buildSMovImm32(DAG, DL, 0),
5072 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5073 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5074 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5077 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5078 MVT::v2i32, Ops0), 0);
5080 // Combine the constants and the pointer.
5081 const SDValue Ops1[] = {
5082 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5084 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5086 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5089 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5092 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5093 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5094 /// of the resource descriptor) to create an offset, which is added to
5095 /// the resource pointer.
5096 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5097 SDValue Ptr, uint32_t RsrcDword1,
5098 uint64_t RsrcDword2And3) const {
5099 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5100 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5102 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5103 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5107 SDValue DataLo = buildSMovImm32(DAG, DL,
5108 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5109 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5111 const SDValue Ops[] = {
5112 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5114 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5116 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5118 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5120 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5123 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5126 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5127 const TargetRegisterClass *RC,
5128 unsigned Reg, EVT VT) const {
5129 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5131 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5132 cast<RegisterSDNode>(VReg)->getReg(), VT);
5135 //===----------------------------------------------------------------------===//
5136 // SI Inline Assembly Support
5137 //===----------------------------------------------------------------------===//
5139 std::pair<unsigned, const TargetRegisterClass *>
5140 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5141 StringRef Constraint,
5143 if (!isTypeLegal(VT))
5144 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5146 if (Constraint.size() == 1) {
5147 switch (Constraint[0]) {
5150 switch (VT.getSizeInBits()) {
5152 return std::make_pair(0U, nullptr);
5155 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5157 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5159 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5161 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5163 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5167 switch (VT.getSizeInBits()) {
5169 return std::make_pair(0U, nullptr);
5172 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5174 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5176 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5178 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5180 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5182 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5187 if (Constraint.size() > 1) {
5188 const TargetRegisterClass *RC = nullptr;
5189 if (Constraint[1] == 'v') {
5190 RC = &AMDGPU::VGPR_32RegClass;
5191 } else if (Constraint[1] == 's') {
5192 RC = &AMDGPU::SGPR_32RegClass;
5197 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5198 if (!Failed && Idx < RC->getNumRegs())
5199 return std::make_pair(RC->getRegister(Idx), RC);
5202 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5205 SITargetLowering::ConstraintType
5206 SITargetLowering::getConstraintType(StringRef Constraint) const {
5207 if (Constraint.size() == 1) {
5208 switch (Constraint[0]) {
5212 return C_RegisterClass;
5215 return TargetLowering::getConstraintType(Constraint);