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, Custom);
291 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
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 = TRI.getRegSizeInBits(*SuperRC) / 32;
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 SIRegisterInfo &TRI,
1797 const TargetRegisterClass *VecRC) {
1798 switch (TRI.getRegSizeInBits(*VecRC)) {
1800 return AMDGPU::V_MOVRELD_B32_V1;
1802 return AMDGPU::V_MOVRELD_B32_V2;
1803 case 128: // 16 bytes
1804 return AMDGPU::V_MOVRELD_B32_V4;
1805 case 256: // 32 bytes
1806 return AMDGPU::V_MOVRELD_B32_V8;
1807 case 512: // 64 bytes
1808 return AMDGPU::V_MOVRELD_B32_V16;
1810 llvm_unreachable("unsupported size for MOVRELD pseudos");
1814 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1815 MachineBasicBlock &MBB,
1816 const SISubtarget &ST) {
1817 const SIInstrInfo *TII = ST.getInstrInfo();
1818 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1819 MachineFunction *MF = MBB.getParent();
1820 MachineRegisterInfo &MRI = MF->getRegInfo();
1822 unsigned Dst = MI.getOperand(0).getReg();
1823 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1824 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1825 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1826 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1827 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1829 // This can be an immediate, but will be folded later.
1830 assert(Val->getReg());
1833 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1836 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1838 if (Idx->getReg() == AMDGPU::NoRegister) {
1839 MachineBasicBlock::iterator I(&MI);
1840 const DebugLoc &DL = MI.getDebugLoc();
1842 assert(Offset == 0);
1844 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1849 MI.eraseFromParent();
1853 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1854 MachineBasicBlock::iterator I(&MI);
1855 const DebugLoc &DL = MI.getDebugLoc();
1857 if (UseGPRIdxMode) {
1858 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1859 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1861 .addReg(Dst, RegState::ImplicitDefine)
1862 .addReg(SrcVec->getReg(), RegState::Implicit)
1863 .addReg(AMDGPU::M0, RegState::Implicit);
1865 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1867 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
1869 BuildMI(MBB, I, DL, MovRelDesc)
1870 .addReg(Dst, RegState::Define)
1871 .addReg(SrcVec->getReg())
1873 .addImm(SubReg - AMDGPU::sub0);
1876 MI.eraseFromParent();
1881 MRI.clearKillFlags(Val->getReg());
1883 const DebugLoc &DL = MI.getDebugLoc();
1885 if (UseGPRIdxMode) {
1886 MachineBasicBlock::iterator I(&MI);
1888 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1889 .addImm(0) // Reset inside loop.
1890 .addImm(VGPRIndexMode::DST_ENABLE);
1891 SetOn->getOperand(3).setIsUndef();
1893 // Disable again after the loop.
1894 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1897 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1899 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1900 Offset, UseGPRIdxMode);
1901 MachineBasicBlock *LoopBB = InsPt->getParent();
1903 if (UseGPRIdxMode) {
1904 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1905 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1907 .addReg(Dst, RegState::ImplicitDefine)
1908 .addReg(PhiReg, RegState::Implicit)
1909 .addReg(AMDGPU::M0, RegState::Implicit);
1911 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
1913 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1914 .addReg(Dst, RegState::Define)
1917 .addImm(SubReg - AMDGPU::sub0);
1920 MI.eraseFromParent();
1925 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1926 MachineInstr &MI, MachineBasicBlock *BB) const {
1928 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1929 MachineFunction *MF = BB->getParent();
1930 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1932 if (TII->isMIMG(MI)) {
1933 if (!MI.memoperands_empty())
1935 // Add a memoperand for mimg instructions so that they aren't assumed to
1936 // be ordered memory instuctions.
1938 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1939 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1941 Flags |= MachineMemOperand::MOStore;
1944 Flags |= MachineMemOperand::MOLoad;
1946 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1947 MI.addMemOperand(*MF, MMO);
1951 switch (MI.getOpcode()) {
1952 case AMDGPU::SI_INIT_M0:
1953 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1954 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1955 .add(MI.getOperand(0));
1956 MI.eraseFromParent();
1959 case AMDGPU::GET_GROUPSTATICSIZE: {
1960 DebugLoc DL = MI.getDebugLoc();
1961 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1962 .add(MI.getOperand(0))
1963 .addImm(MFI->getLDSSize());
1964 MI.eraseFromParent();
1967 case AMDGPU::SI_INDIRECT_SRC_V1:
1968 case AMDGPU::SI_INDIRECT_SRC_V2:
1969 case AMDGPU::SI_INDIRECT_SRC_V4:
1970 case AMDGPU::SI_INDIRECT_SRC_V8:
1971 case AMDGPU::SI_INDIRECT_SRC_V16:
1972 return emitIndirectSrc(MI, *BB, *getSubtarget());
1973 case AMDGPU::SI_INDIRECT_DST_V1:
1974 case AMDGPU::SI_INDIRECT_DST_V2:
1975 case AMDGPU::SI_INDIRECT_DST_V4:
1976 case AMDGPU::SI_INDIRECT_DST_V8:
1977 case AMDGPU::SI_INDIRECT_DST_V16:
1978 return emitIndirectDst(MI, *BB, *getSubtarget());
1979 case AMDGPU::SI_KILL:
1980 return splitKillBlock(MI, BB);
1981 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1982 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1984 unsigned Dst = MI.getOperand(0).getReg();
1985 unsigned Src0 = MI.getOperand(1).getReg();
1986 unsigned Src1 = MI.getOperand(2).getReg();
1987 const DebugLoc &DL = MI.getDebugLoc();
1988 unsigned SrcCond = MI.getOperand(3).getReg();
1990 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1991 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1993 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1994 .addReg(Src0, 0, AMDGPU::sub0)
1995 .addReg(Src1, 0, AMDGPU::sub0)
1997 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1998 .addReg(Src0, 0, AMDGPU::sub1)
1999 .addReg(Src1, 0, AMDGPU::sub1)
2002 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2004 .addImm(AMDGPU::sub0)
2006 .addImm(AMDGPU::sub1);
2007 MI.eraseFromParent();
2010 case AMDGPU::SI_BR_UNDEF: {
2011 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2012 const DebugLoc &DL = MI.getDebugLoc();
2013 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2014 .add(MI.getOperand(0));
2015 Br->getOperand(1).setIsUndef(true); // read undef SCC
2016 MI.eraseFromParent();
2020 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2024 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2025 // This currently forces unfolding various combinations of fsub into fma with
2026 // free fneg'd operands. As long as we have fast FMA (controlled by
2027 // isFMAFasterThanFMulAndFAdd), we should perform these.
2029 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2030 // most of these combines appear to be cycle neutral but save on instruction
2031 // count / code size.
2035 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2037 if (!VT.isVector()) {
2040 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2043 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2044 // TODO: Should i16 be used always if legal? For now it would force VALU
2046 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2049 // Answering this is somewhat tricky and depends on the specific device which
2050 // have different rates for fma or all f64 operations.
2052 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2053 // regardless of which device (although the number of cycles differs between
2054 // devices), so it is always profitable for f64.
2056 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2057 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2058 // which we can always do even without fused FP ops since it returns the same
2059 // result as the separate operations and since it is always full
2060 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2061 // however does not support denormals, so we do report fma as faster if we have
2062 // a fast fma device and require denormals.
2064 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2065 VT = VT.getScalarType();
2067 switch (VT.getSimpleVT().SimpleTy) {
2069 // This is as fast on some subtargets. However, we always have full rate f32
2070 // mad available which returns the same result as the separate operations
2071 // which we should prefer over fma. We can't use this if we want to support
2072 // denormals, so only report this in these cases.
2073 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2077 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2085 //===----------------------------------------------------------------------===//
2086 // Custom DAG Lowering Operations
2087 //===----------------------------------------------------------------------===//
2089 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2090 switch (Op.getOpcode()) {
2091 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2092 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2094 SDValue Result = LowerLOAD(Op, DAG);
2095 assert((!Result.getNode() ||
2096 Result.getNode()->getNumValues() == 2) &&
2097 "Load should return a value and a chain");
2103 return LowerTrig(Op, DAG);
2104 case ISD::SELECT: return LowerSELECT(Op, DAG);
2105 case ISD::FDIV: return LowerFDIV(Op, DAG);
2106 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2107 case ISD::STORE: return LowerSTORE(Op, DAG);
2108 case ISD::GlobalAddress: {
2109 MachineFunction &MF = DAG.getMachineFunction();
2110 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2111 return LowerGlobalAddress(MFI, Op, DAG);
2113 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2114 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2115 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2116 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2117 case ISD::INSERT_VECTOR_ELT:
2118 return lowerINSERT_VECTOR_ELT(Op, DAG);
2119 case ISD::EXTRACT_VECTOR_ELT:
2120 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2122 return lowerFP_ROUND(Op, DAG);
2125 case ISD::DEBUGTRAP:
2126 return lowerTRAP(Op, DAG);
2131 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2132 SmallVectorImpl<SDValue> &Results,
2133 SelectionDAG &DAG) const {
2134 switch (N->getOpcode()) {
2135 case ISD::INSERT_VECTOR_ELT: {
2136 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2137 Results.push_back(Res);
2140 case ISD::EXTRACT_VECTOR_ELT: {
2141 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2142 Results.push_back(Res);
2145 case ISD::INTRINSIC_WO_CHAIN: {
2146 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2148 case Intrinsic::amdgcn_cvt_pkrtz: {
2149 SDValue Src0 = N->getOperand(1);
2150 SDValue Src1 = N->getOperand(2);
2152 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2155 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2164 EVT VT = N->getValueType(0);
2165 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2166 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
2167 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
2169 EVT SelectVT = NewVT;
2170 if (NewVT.bitsLT(MVT::i32)) {
2171 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
2172 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
2173 SelectVT = MVT::i32;
2176 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
2177 N->getOperand(0), LHS, RHS);
2179 if (NewVT != SelectVT)
2180 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
2181 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
2189 /// \brief Helper function for LowerBRCOND
2190 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2192 SDNode *Parent = Value.getNode();
2193 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2196 if (I.getUse().get() != Value)
2199 if (I->getOpcode() == Opcode)
2205 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2206 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2207 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2208 case Intrinsic::amdgcn_if:
2209 return AMDGPUISD::IF;
2210 case Intrinsic::amdgcn_else:
2211 return AMDGPUISD::ELSE;
2212 case Intrinsic::amdgcn_loop:
2213 return AMDGPUISD::LOOP;
2214 case Intrinsic::amdgcn_end_cf:
2215 llvm_unreachable("should not occur");
2221 // break, if_break, else_break are all only used as inputs to loop, not
2222 // directly as branch conditions.
2226 void SITargetLowering::createDebuggerPrologueStackObjects(
2227 MachineFunction &MF) const {
2228 // Create stack objects that are used for emitting debugger prologue.
2230 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2231 // at fixed location in the following format:
2232 // offset 0: work group ID x
2233 // offset 4: work group ID y
2234 // offset 8: work group ID z
2235 // offset 16: work item ID x
2236 // offset 20: work item ID y
2237 // offset 24: work item ID z
2238 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2241 // For each dimension:
2242 for (unsigned i = 0; i < 3; ++i) {
2243 // Create fixed stack object for work group ID.
2244 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2245 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2246 // Create fixed stack object for work item ID.
2247 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2248 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2252 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2253 const Triple &TT = getTargetMachine().getTargetTriple();
2254 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2255 AMDGPU::shouldEmitConstantsToTextSection(TT);
2258 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2259 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2260 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2261 !shouldEmitFixup(GV) &&
2262 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2265 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2266 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2269 /// This transforms the control flow intrinsics to get the branch destination as
2270 /// last parameter, also switches branch target with BR if the need arise
2271 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2272 SelectionDAG &DAG) const {
2275 SDNode *Intr = BRCOND.getOperand(1).getNode();
2276 SDValue Target = BRCOND.getOperand(2);
2277 SDNode *BR = nullptr;
2278 SDNode *SetCC = nullptr;
2280 if (Intr->getOpcode() == ISD::SETCC) {
2281 // As long as we negate the condition everything is fine
2283 Intr = SetCC->getOperand(0).getNode();
2286 // Get the target from BR if we don't negate the condition
2287 BR = findUser(BRCOND, ISD::BR);
2288 Target = BR->getOperand(1);
2291 // FIXME: This changes the types of the intrinsics instead of introducing new
2292 // nodes with the correct types.
2293 // e.g. llvm.amdgcn.loop
2295 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2296 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2298 unsigned CFNode = isCFIntrinsic(Intr);
2300 // This is a uniform branch so we don't need to legalize.
2304 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2305 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2308 (SetCC->getConstantOperandVal(1) == 1 &&
2309 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2312 // operands of the new intrinsic call
2313 SmallVector<SDValue, 4> Ops;
2315 Ops.push_back(BRCOND.getOperand(0));
2317 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2318 Ops.push_back(Target);
2320 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2322 // build the new intrinsic call
2323 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2328 BRCOND.getOperand(0)
2331 Result = DAG.getMergeValues(Ops, DL).getNode();
2335 // Give the branch instruction our target
2338 BRCOND.getOperand(2)
2340 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2341 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2342 BR = NewBR.getNode();
2345 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2347 // Copy the intrinsic results to registers
2348 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2349 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2353 Chain = DAG.getCopyToReg(
2355 CopyToReg->getOperand(1),
2356 SDValue(Result, i - 1),
2359 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2362 // Remove the old intrinsic from the chain
2363 DAG.ReplaceAllUsesOfValueWith(
2364 SDValue(Intr, Intr->getNumValues() - 1),
2365 Intr->getOperand(0));
2370 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2374 return Op.getValueType().bitsLE(VT) ?
2375 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2376 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2379 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2380 assert(Op.getValueType() == MVT::f16 &&
2381 "Do not know how to custom lower FP_ROUND for non-f16 type");
2383 SDValue Src = Op.getOperand(0);
2384 EVT SrcVT = Src.getValueType();
2385 if (SrcVT != MVT::f64)
2390 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2391 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2392 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2395 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
2397 MachineFunction &MF = DAG.getMachineFunction();
2398 SDValue Chain = Op.getOperand(0);
2400 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
2401 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
2403 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
2404 Subtarget->isTrapHandlerEnabled()) {
2405 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2406 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2407 assert(UserSGPR != AMDGPU::NoRegister);
2409 SDValue QueuePtr = CreateLiveInRegister(
2410 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2412 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
2414 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
2415 QueuePtr, SDValue());
2419 DAG.getTargetConstant(TrapID, SL, MVT::i16),
2424 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
2428 case SISubtarget::TrapIDLLVMTrap:
2429 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
2430 case SISubtarget::TrapIDLLVMDebugTrap: {
2431 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2432 "debugtrap handler not supported",
2435 LLVMContext &Ctx = MF.getFunction()->getContext();
2436 Ctx.diagnose(NoTrap);
2440 llvm_unreachable("unsupported trap handler type!");
2446 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2447 SelectionDAG &DAG) const {
2448 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2449 if (Subtarget->hasApertureRegs()) {
2450 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2451 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2452 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2453 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2454 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2455 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2457 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2458 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2459 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2461 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2462 SDValue ApertureReg = SDValue(
2463 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2464 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2465 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2470 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2471 assert(UserSGPR != AMDGPU::NoRegister);
2473 SDValue QueuePtr = CreateLiveInRegister(
2474 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2476 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2477 // private_segment_aperture_base_hi.
2478 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2480 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2481 DAG.getConstant(StructOffset, DL, MVT::i64));
2483 // TODO: Use custom target PseudoSourceValue.
2484 // TODO: We should use the value from the IR intrinsic call, but it might not
2485 // be available and how do we get it?
2486 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2487 AMDGPUASI.CONSTANT_ADDRESS));
2489 MachinePointerInfo PtrInfo(V, StructOffset);
2490 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2491 MinAlign(64, StructOffset),
2492 MachineMemOperand::MODereferenceable |
2493 MachineMemOperand::MOInvariant);
2496 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2497 SelectionDAG &DAG) const {
2499 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2501 SDValue Src = ASC->getOperand(0);
2502 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2504 const AMDGPUTargetMachine &TM =
2505 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2507 // flat -> local/private
2508 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2509 unsigned DestAS = ASC->getDestAddressSpace();
2511 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2512 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2513 unsigned NullVal = TM.getNullPointerValue(DestAS);
2514 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2515 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2516 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2518 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2519 NonNull, Ptr, SegmentNullPtr);
2523 // local/private -> flat
2524 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2525 unsigned SrcAS = ASC->getSrcAddressSpace();
2527 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2528 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2529 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2530 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2533 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2535 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2537 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2539 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2540 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2545 // global <-> flat are no-ops and never emitted.
2547 const MachineFunction &MF = DAG.getMachineFunction();
2548 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2549 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2550 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2552 return DAG.getUNDEF(ASC->getValueType(0));
2555 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2556 SelectionDAG &DAG) const {
2557 SDValue Idx = Op.getOperand(2);
2558 if (isa<ConstantSDNode>(Idx))
2561 // Avoid stack access for dynamic indexing.
2563 SDValue Vec = Op.getOperand(0);
2564 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2566 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2567 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2569 // Convert vector index to bit-index.
2570 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2571 DAG.getConstant(16, SL, MVT::i32));
2573 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2575 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2576 DAG.getConstant(0xffff, SL, MVT::i32),
2579 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2580 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2581 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2583 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2584 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2587 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2588 SelectionDAG &DAG) const {
2591 EVT ResultVT = Op.getValueType();
2592 SDValue Vec = Op.getOperand(0);
2593 SDValue Idx = Op.getOperand(1);
2595 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2596 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2598 if (CIdx->getZExtValue() == 1) {
2599 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2600 DAG.getConstant(16, SL, MVT::i32));
2602 assert(CIdx->getZExtValue() == 0);
2605 if (ResultVT.bitsLT(MVT::i32))
2606 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2607 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2610 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2612 // Convert vector index to bit-index.
2613 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2615 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2616 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2618 SDValue Result = Elt;
2619 if (ResultVT.bitsLT(MVT::i32))
2620 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2622 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2626 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2627 // We can fold offsets for anything that doesn't require a GOT relocation.
2628 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2629 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2630 !shouldEmitGOTReloc(GA->getGlobal());
2634 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2635 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2636 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2637 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2638 // lowered to the following code sequence:
2640 // For constant address space:
2641 // s_getpc_b64 s[0:1]
2642 // s_add_u32 s0, s0, $symbol
2643 // s_addc_u32 s1, s1, 0
2645 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2646 // a fixup or relocation is emitted to replace $symbol with a literal
2647 // constant, which is a pc-relative offset from the encoding of the $symbol
2648 // operand to the global variable.
2650 // For global address space:
2651 // s_getpc_b64 s[0:1]
2652 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2653 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2655 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2656 // fixups or relocations are emitted to replace $symbol@*@lo and
2657 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2658 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2659 // operand to the global variable.
2661 // What we want here is an offset from the value returned by s_getpc
2662 // (which is the address of the s_add_u32 instruction) to the global
2663 // variable, but since the encoding of $symbol starts 4 bytes after the start
2664 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2665 // small. This requires us to add 4 to the global variable offset in order to
2666 // compute the correct address.
2667 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2669 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2670 GAFlags == SIInstrInfo::MO_NONE ?
2671 GAFlags : GAFlags + 1);
2672 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2675 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2677 SelectionDAG &DAG) const {
2678 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2680 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2681 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2682 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2685 const GlobalValue *GV = GSD->getGlobal();
2686 EVT PtrVT = Op.getValueType();
2688 if (shouldEmitFixup(GV))
2689 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2690 else if (shouldEmitPCReloc(GV))
2691 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2692 SIInstrInfo::MO_REL32);
2694 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2695 SIInstrInfo::MO_GOTPCREL32);
2697 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2698 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2699 const DataLayout &DataLayout = DAG.getDataLayout();
2700 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2701 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2702 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2704 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2705 MachineMemOperand::MODereferenceable |
2706 MachineMemOperand::MOInvariant);
2709 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2710 const SDLoc &DL, SDValue V) const {
2711 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2712 // the destination register.
2714 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2715 // so we will end up with redundant moves to m0.
2717 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2719 // A Null SDValue creates a glue result.
2720 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2722 return SDValue(M0, 0);
2725 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2728 unsigned Offset) const {
2730 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2731 DAG.getEntryNode(), Offset, false);
2732 // The local size values will have the hi 16-bits as zero.
2733 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2734 DAG.getValueType(VT));
2737 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2739 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2740 "non-hsa intrinsic with hsa target",
2742 DAG.getContext()->diagnose(BadIntrin);
2743 return DAG.getUNDEF(VT);
2746 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2748 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2749 "intrinsic not supported on subtarget",
2751 DAG.getContext()->diagnose(BadIntrin);
2752 return DAG.getUNDEF(VT);
2755 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2756 SelectionDAG &DAG) const {
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2759 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2761 EVT VT = Op.getValueType();
2763 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2765 // TODO: Should this propagate fast-math-flags?
2767 switch (IntrinsicID) {
2768 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2769 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2770 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2772 case Intrinsic::amdgcn_dispatch_ptr:
2773 case Intrinsic::amdgcn_queue_ptr: {
2774 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2775 DiagnosticInfoUnsupported BadIntrin(
2776 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2778 DAG.getContext()->diagnose(BadIntrin);
2779 return DAG.getUNDEF(VT);
2782 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2783 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2784 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2785 TRI->getPreloadedValue(MF, Reg), VT);
2787 case Intrinsic::amdgcn_implicitarg_ptr: {
2788 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2789 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2791 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2793 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2794 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2796 case Intrinsic::amdgcn_dispatch_id: {
2797 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2798 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2800 case Intrinsic::amdgcn_rcp:
2801 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2802 case Intrinsic::amdgcn_rsq:
2803 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2804 case Intrinsic::amdgcn_rsq_legacy:
2805 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2806 return emitRemovedIntrinsicError(DAG, DL, VT);
2808 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2809 case Intrinsic::amdgcn_rcp_legacy:
2810 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2811 return emitRemovedIntrinsicError(DAG, DL, VT);
2812 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2813 case Intrinsic::amdgcn_rsq_clamp: {
2814 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2815 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2817 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2818 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2819 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2821 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2822 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2823 DAG.getConstantFP(Max, DL, VT));
2824 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2825 DAG.getConstantFP(Min, DL, VT));
2827 case Intrinsic::r600_read_ngroups_x:
2828 if (Subtarget->isAmdHsaOS())
2829 return emitNonHSAIntrinsicError(DAG, DL, VT);
2831 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2832 SI::KernelInputOffsets::NGROUPS_X, false);
2833 case Intrinsic::r600_read_ngroups_y:
2834 if (Subtarget->isAmdHsaOS())
2835 return emitNonHSAIntrinsicError(DAG, DL, VT);
2837 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2838 SI::KernelInputOffsets::NGROUPS_Y, false);
2839 case Intrinsic::r600_read_ngroups_z:
2840 if (Subtarget->isAmdHsaOS())
2841 return emitNonHSAIntrinsicError(DAG, DL, VT);
2843 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2844 SI::KernelInputOffsets::NGROUPS_Z, false);
2845 case Intrinsic::r600_read_global_size_x:
2846 if (Subtarget->isAmdHsaOS())
2847 return emitNonHSAIntrinsicError(DAG, DL, VT);
2849 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2850 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2851 case Intrinsic::r600_read_global_size_y:
2852 if (Subtarget->isAmdHsaOS())
2853 return emitNonHSAIntrinsicError(DAG, DL, VT);
2855 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2856 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2857 case Intrinsic::r600_read_global_size_z:
2858 if (Subtarget->isAmdHsaOS())
2859 return emitNonHSAIntrinsicError(DAG, DL, VT);
2861 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2862 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2863 case Intrinsic::r600_read_local_size_x:
2864 if (Subtarget->isAmdHsaOS())
2865 return emitNonHSAIntrinsicError(DAG, DL, VT);
2867 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2868 SI::KernelInputOffsets::LOCAL_SIZE_X);
2869 case Intrinsic::r600_read_local_size_y:
2870 if (Subtarget->isAmdHsaOS())
2871 return emitNonHSAIntrinsicError(DAG, DL, VT);
2873 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2874 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2875 case Intrinsic::r600_read_local_size_z:
2876 if (Subtarget->isAmdHsaOS())
2877 return emitNonHSAIntrinsicError(DAG, DL, VT);
2879 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2880 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2881 case Intrinsic::amdgcn_workgroup_id_x:
2882 case Intrinsic::r600_read_tgid_x:
2883 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2884 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2885 case Intrinsic::amdgcn_workgroup_id_y:
2886 case Intrinsic::r600_read_tgid_y:
2887 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2888 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2889 case Intrinsic::amdgcn_workgroup_id_z:
2890 case Intrinsic::r600_read_tgid_z:
2891 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2892 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2893 case Intrinsic::amdgcn_workitem_id_x:
2894 case Intrinsic::r600_read_tidig_x:
2895 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2896 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2897 case Intrinsic::amdgcn_workitem_id_y:
2898 case Intrinsic::r600_read_tidig_y:
2899 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2900 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2901 case Intrinsic::amdgcn_workitem_id_z:
2902 case Intrinsic::r600_read_tidig_z:
2903 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2904 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2905 case AMDGPUIntrinsic::SI_load_const: {
2911 MachineMemOperand *MMO = MF.getMachineMemOperand(
2912 MachinePointerInfo(),
2913 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2914 MachineMemOperand::MOInvariant,
2915 VT.getStoreSize(), 4);
2916 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2917 Op->getVTList(), Ops, VT, MMO);
2919 case Intrinsic::amdgcn_fdiv_fast:
2920 return lowerFDIV_FAST(Op, DAG);
2921 case Intrinsic::amdgcn_interp_mov: {
2922 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2923 SDValue Glue = M0.getValue(1);
2924 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2925 Op.getOperand(2), Op.getOperand(3), Glue);
2927 case Intrinsic::amdgcn_interp_p1: {
2928 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2929 SDValue Glue = M0.getValue(1);
2930 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2931 Op.getOperand(2), Op.getOperand(3), Glue);
2933 case Intrinsic::amdgcn_interp_p2: {
2934 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2935 SDValue Glue = SDValue(M0.getNode(), 1);
2936 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2937 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2940 case Intrinsic::amdgcn_sin:
2941 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2943 case Intrinsic::amdgcn_cos:
2944 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2946 case Intrinsic::amdgcn_log_clamp: {
2947 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2950 DiagnosticInfoUnsupported BadIntrin(
2951 *MF.getFunction(), "intrinsic not supported on subtarget",
2953 DAG.getContext()->diagnose(BadIntrin);
2954 return DAG.getUNDEF(VT);
2956 case Intrinsic::amdgcn_ldexp:
2957 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2958 Op.getOperand(1), Op.getOperand(2));
2960 case Intrinsic::amdgcn_fract:
2961 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2963 case Intrinsic::amdgcn_class:
2964 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2965 Op.getOperand(1), Op.getOperand(2));
2966 case Intrinsic::amdgcn_div_fmas:
2967 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2968 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2971 case Intrinsic::amdgcn_div_fixup:
2972 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2973 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2975 case Intrinsic::amdgcn_trig_preop:
2976 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2977 Op.getOperand(1), Op.getOperand(2));
2978 case Intrinsic::amdgcn_div_scale: {
2979 // 3rd parameter required to be a constant.
2980 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2982 return DAG.getUNDEF(VT);
2984 // Translate to the operands expected by the machine instruction. The
2985 // first parameter must be the same as the first instruction.
2986 SDValue Numerator = Op.getOperand(1);
2987 SDValue Denominator = Op.getOperand(2);
2989 // Note this order is opposite of the machine instruction's operations,
2990 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2991 // intrinsic has the numerator as the first operand to match a normal
2992 // division operation.
2994 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2996 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2997 Denominator, Numerator);
2999 case Intrinsic::amdgcn_icmp: {
3000 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3002 return DAG.getUNDEF(VT);
3004 int CondCode = CD->getSExtValue();
3005 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3006 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3007 return DAG.getUNDEF(VT);
3009 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3010 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3011 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3012 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3014 case Intrinsic::amdgcn_fcmp: {
3015 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3017 return DAG.getUNDEF(VT);
3019 int CondCode = CD->getSExtValue();
3020 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3021 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
3022 return DAG.getUNDEF(VT);
3024 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3025 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3026 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3027 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3029 case Intrinsic::amdgcn_fmed3:
3030 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
3031 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3032 case Intrinsic::amdgcn_fmul_legacy:
3033 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
3034 Op.getOperand(1), Op.getOperand(2));
3035 case Intrinsic::amdgcn_sffbh:
3036 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
3037 case Intrinsic::amdgcn_sbfe:
3038 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
3039 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3040 case Intrinsic::amdgcn_ubfe:
3041 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3042 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3043 case Intrinsic::amdgcn_cvt_pkrtz: {
3044 // FIXME: Stop adding cast if v2f16 legal.
3045 EVT VT = Op.getValueType();
3046 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3047 Op.getOperand(1), Op.getOperand(2));
3048 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3055 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3056 SelectionDAG &DAG) const {
3057 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3060 case Intrinsic::amdgcn_atomic_inc:
3061 case Intrinsic::amdgcn_atomic_dec: {
3062 MemSDNode *M = cast<MemSDNode>(Op);
3063 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3064 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3066 M->getOperand(0), // Chain
3067 M->getOperand(2), // Ptr
3068 M->getOperand(3) // Value
3071 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3072 M->getMemoryVT(), M->getMemOperand());
3074 case Intrinsic::amdgcn_buffer_load:
3075 case Intrinsic::amdgcn_buffer_load_format: {
3077 Op.getOperand(0), // Chain
3078 Op.getOperand(2), // rsrc
3079 Op.getOperand(3), // vindex
3080 Op.getOperand(4), // offset
3081 Op.getOperand(5), // glc
3082 Op.getOperand(6) // slc
3084 MachineFunction &MF = DAG.getMachineFunction();
3085 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3087 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3088 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3089 EVT VT = Op.getValueType();
3090 EVT IntVT = VT.changeTypeToInteger();
3092 MachineMemOperand *MMO = MF.getMachineMemOperand(
3093 MachinePointerInfo(MFI->getBufferPSV()),
3094 MachineMemOperand::MOLoad,
3095 VT.getStoreSize(), VT.getStoreSize());
3097 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3100 case Intrinsic::amdgcn_image_sample:
3101 case Intrinsic::amdgcn_image_sample_cl:
3102 case Intrinsic::amdgcn_image_sample_d:
3103 case Intrinsic::amdgcn_image_sample_d_cl:
3104 case Intrinsic::amdgcn_image_sample_l:
3105 case Intrinsic::amdgcn_image_sample_b:
3106 case Intrinsic::amdgcn_image_sample_b_cl:
3107 case Intrinsic::amdgcn_image_sample_lz:
3108 case Intrinsic::amdgcn_image_sample_cd:
3109 case Intrinsic::amdgcn_image_sample_cd_cl:
3111 // Sample with comparison.
3112 case Intrinsic::amdgcn_image_sample_c:
3113 case Intrinsic::amdgcn_image_sample_c_cl:
3114 case Intrinsic::amdgcn_image_sample_c_d:
3115 case Intrinsic::amdgcn_image_sample_c_d_cl:
3116 case Intrinsic::amdgcn_image_sample_c_l:
3117 case Intrinsic::amdgcn_image_sample_c_b:
3118 case Intrinsic::amdgcn_image_sample_c_b_cl:
3119 case Intrinsic::amdgcn_image_sample_c_lz:
3120 case Intrinsic::amdgcn_image_sample_c_cd:
3121 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3123 // Sample with offsets.
3124 case Intrinsic::amdgcn_image_sample_o:
3125 case Intrinsic::amdgcn_image_sample_cl_o:
3126 case Intrinsic::amdgcn_image_sample_d_o:
3127 case Intrinsic::amdgcn_image_sample_d_cl_o:
3128 case Intrinsic::amdgcn_image_sample_l_o:
3129 case Intrinsic::amdgcn_image_sample_b_o:
3130 case Intrinsic::amdgcn_image_sample_b_cl_o:
3131 case Intrinsic::amdgcn_image_sample_lz_o:
3132 case Intrinsic::amdgcn_image_sample_cd_o:
3133 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3135 // Sample with comparison and offsets.
3136 case Intrinsic::amdgcn_image_sample_c_o:
3137 case Intrinsic::amdgcn_image_sample_c_cl_o:
3138 case Intrinsic::amdgcn_image_sample_c_d_o:
3139 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3140 case Intrinsic::amdgcn_image_sample_c_l_o:
3141 case Intrinsic::amdgcn_image_sample_c_b_o:
3142 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3143 case Intrinsic::amdgcn_image_sample_c_lz_o:
3144 case Intrinsic::amdgcn_image_sample_c_cd_o:
3145 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3147 case Intrinsic::amdgcn_image_getlod: {
3148 // Replace dmask with everything disabled with undef.
3149 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3150 if (!DMask || DMask->isNullValue()) {
3151 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3152 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3162 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3163 SelectionDAG &DAG) const {
3164 MachineFunction &MF = DAG.getMachineFunction();
3166 SDValue Chain = Op.getOperand(0);
3167 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3169 switch (IntrinsicID) {
3170 case Intrinsic::amdgcn_exp: {
3171 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3172 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3173 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3174 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3176 const SDValue Ops[] = {
3178 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3179 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3180 Op.getOperand(4), // src0
3181 Op.getOperand(5), // src1
3182 Op.getOperand(6), // src2
3183 Op.getOperand(7), // src3
3184 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3185 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3188 unsigned Opc = Done->isNullValue() ?
3189 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3190 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3192 case Intrinsic::amdgcn_exp_compr: {
3193 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3194 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3195 SDValue Src0 = Op.getOperand(4);
3196 SDValue Src1 = Op.getOperand(5);
3197 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3198 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3200 SDValue Undef = DAG.getUNDEF(MVT::f32);
3201 const SDValue Ops[] = {
3203 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3204 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3205 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3206 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3209 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3210 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3213 unsigned Opc = Done->isNullValue() ?
3214 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3215 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3217 case Intrinsic::amdgcn_s_sendmsg:
3218 case Intrinsic::amdgcn_s_sendmsghalt: {
3219 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3220 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3221 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3222 SDValue Glue = Chain.getValue(1);
3223 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3224 Op.getOperand(2), Glue);
3226 case AMDGPUIntrinsic::SI_tbuffer_store: {
3244 EVT VT = Op.getOperand(3).getValueType();
3246 MachineMemOperand *MMO = MF.getMachineMemOperand(
3247 MachinePointerInfo(),
3248 MachineMemOperand::MOStore,
3249 VT.getStoreSize(), 4);
3250 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3251 Op->getVTList(), Ops, VT, MMO);
3253 case AMDGPUIntrinsic::AMDGPU_kill: {
3254 SDValue Src = Op.getOperand(2);
3255 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3256 if (!K->isNegative())
3259 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3260 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3263 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3264 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3266 case Intrinsic::amdgcn_s_barrier: {
3267 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3268 const MachineFunction &MF = DAG.getMachineFunction();
3269 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3270 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3271 if (WGSize <= ST.getWavefrontSize())
3272 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3273 Op.getOperand(0)), 0);
3282 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3284 LoadSDNode *Load = cast<LoadSDNode>(Op);
3285 ISD::LoadExtType ExtType = Load->getExtensionType();
3286 EVT MemVT = Load->getMemoryVT();
3288 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3289 // FIXME: Copied from PPC
3290 // First, load into 32 bits, then truncate to 1 bit.
3292 SDValue Chain = Load->getChain();
3293 SDValue BasePtr = Load->getBasePtr();
3294 MachineMemOperand *MMO = Load->getMemOperand();
3296 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3298 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3299 BasePtr, RealMemVT, MMO);
3302 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3306 return DAG.getMergeValues(Ops, DL);
3309 if (!MemVT.isVector())
3312 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3313 "Custom lowering for non-i32 vectors hasn't been implemented.");
3315 unsigned AS = Load->getAddressSpace();
3316 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3317 AS, Load->getAlignment())) {
3319 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3320 return DAG.getMergeValues(Ops, DL);
3323 MachineFunction &MF = DAG.getMachineFunction();
3324 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3325 // If there is a possibilty that flat instruction access scratch memory
3326 // then we need to use the same legalization rules we use for private.
3327 if (AS == AMDGPUASI.FLAT_ADDRESS)
3328 AS = MFI->hasFlatScratchInit() ?
3329 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3331 unsigned NumElements = MemVT.getVectorNumElements();
3332 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3333 if (isMemOpUniform(Load))
3335 // Non-uniform loads will be selected to MUBUF instructions, so they
3336 // have the same legalization requirements as global and private
3340 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3341 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3342 isMemOpHasNoClobberedMemOperand(Load))
3344 // Non-uniform loads will be selected to MUBUF instructions, so they
3345 // have the same legalization requirements as global and private
3349 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3350 AS == AMDGPUASI.FLAT_ADDRESS) {
3351 if (NumElements > 4)
3352 return SplitVectorLoad(Op, DAG);
3353 // v4 loads are supported for private and global memory.
3356 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3357 // Depending on the setting of the private_element_size field in the
3358 // resource descriptor, we can only make private accesses up to a certain
3360 switch (Subtarget->getMaxPrivateElementSize()) {
3362 return scalarizeVectorLoad(Load, DAG);
3364 if (NumElements > 2)
3365 return SplitVectorLoad(Op, DAG);
3368 // Same as global/flat
3369 if (NumElements > 4)
3370 return SplitVectorLoad(Op, DAG);
3373 llvm_unreachable("unsupported private_element_size");
3375 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3376 if (NumElements > 2)
3377 return SplitVectorLoad(Op, DAG);
3379 if (NumElements == 2)
3382 // If properly aligned, if we split we might be able to use ds_read_b64.
3383 return SplitVectorLoad(Op, DAG);
3388 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3389 if (Op.getValueType() != MVT::i64)
3393 SDValue Cond = Op.getOperand(0);
3395 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3396 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3398 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3399 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3401 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3402 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3404 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3406 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3407 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3409 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3411 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3412 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3415 // Catch division cases where we can use shortcuts with rcp and rsq
3417 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3418 SelectionDAG &DAG) const {
3420 SDValue LHS = Op.getOperand(0);
3421 SDValue RHS = Op.getOperand(1);
3422 EVT VT = Op.getValueType();
3423 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3425 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
3428 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3429 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
3430 if (CLHS->isExactlyValue(1.0)) {
3431 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3432 // the CI documentation has a worst case error of 1 ulp.
3433 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3434 // use it as long as we aren't trying to use denormals.
3436 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3438 // 1.0 / sqrt(x) -> rsq(x)
3440 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3441 // error seems really high at 2^29 ULP.
3442 if (RHS.getOpcode() == ISD::FSQRT)
3443 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3445 // 1.0 / x -> rcp(x)
3446 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3449 // Same as for 1.0, but expand the sign out of the constant.
3450 if (CLHS->isExactlyValue(-1.0)) {
3451 // -1.0 / x -> rcp (fneg x)
3452 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3453 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3458 const SDNodeFlags *Flags = Op->getFlags();
3460 if (Unsafe || Flags->hasAllowReciprocal()) {
3461 // Turn into multiply by the reciprocal.
3462 // x / y -> x * (1.0 / y)
3464 Flags.setUnsafeAlgebra(true);
3465 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3466 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3472 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3473 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3474 if (GlueChain->getNumValues() <= 1) {
3475 return DAG.getNode(Opcode, SL, VT, A, B);
3478 assert(GlueChain->getNumValues() == 3);
3480 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3482 default: llvm_unreachable("no chain equivalent for opcode");
3484 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3488 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3489 GlueChain.getValue(2));
3492 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3493 EVT VT, SDValue A, SDValue B, SDValue C,
3494 SDValue GlueChain) {
3495 if (GlueChain->getNumValues() <= 1) {
3496 return DAG.getNode(Opcode, SL, VT, A, B, C);
3499 assert(GlueChain->getNumValues() == 3);
3501 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3503 default: llvm_unreachable("no chain equivalent for opcode");
3505 Opcode = AMDGPUISD::FMA_W_CHAIN;
3509 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3510 GlueChain.getValue(2));
3513 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3514 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3518 SDValue Src0 = Op.getOperand(0);
3519 SDValue Src1 = Op.getOperand(1);
3521 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3522 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3524 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3525 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3527 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3528 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3530 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3533 // Faster 2.5 ULP division that does not support denormals.
3534 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3536 SDValue LHS = Op.getOperand(1);
3537 SDValue RHS = Op.getOperand(2);
3539 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3541 const APFloat K0Val(BitsToFloat(0x6f800000));
3542 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3544 const APFloat K1Val(BitsToFloat(0x2f800000));
3545 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3547 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3550 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3552 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3554 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3556 // TODO: Should this propagate fast-math-flags?
3557 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3559 // rcp does not support denormals.
3560 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3562 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3564 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3567 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3568 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3572 SDValue LHS = Op.getOperand(0);
3573 SDValue RHS = Op.getOperand(1);
3575 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3577 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3579 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3581 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3584 // Denominator is scaled to not be denormal, so using rcp is ok.
3585 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3587 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3590 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3591 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3592 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3594 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3596 if (!Subtarget->hasFP32Denormals()) {
3597 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3598 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3600 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3602 EnableDenormValue, BitField);
3605 EnableDenorm.getValue(0),
3606 EnableDenorm.getValue(1)
3609 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3612 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3613 ApproxRcp, One, NegDivScale0);
3615 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3618 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3621 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3622 NumeratorScaled, Mul);
3624 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3626 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3627 NumeratorScaled, Fma3);
3629 if (!Subtarget->hasFP32Denormals()) {
3630 const SDValue DisableDenormValue =
3631 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3632 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3638 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3639 DisableDenorm, DAG.getRoot());
3640 DAG.setRoot(OutputChain);
3643 SDValue Scale = NumeratorScaled.getValue(1);
3644 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3645 Fma4, Fma1, Fma3, Scale);
3647 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3650 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3651 if (DAG.getTarget().Options.UnsafeFPMath)
3652 return lowerFastUnsafeFDIV(Op, DAG);
3655 SDValue X = Op.getOperand(0);
3656 SDValue Y = Op.getOperand(1);
3658 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3660 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3662 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3664 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3666 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3668 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3670 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3672 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3674 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3676 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3677 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3679 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3680 NegDivScale0, Mul, DivScale1);
3684 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3685 // Workaround a hardware bug on SI where the condition output from div_scale
3688 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3690 // Figure out if the scale to use for div_fmas.
3691 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3692 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3693 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3694 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3696 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3697 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3700 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3702 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3704 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3705 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3706 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3708 Scale = DivScale1.getValue(1);
3711 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3712 Fma4, Fma3, Mul, Scale);
3714 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3717 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3718 EVT VT = Op.getValueType();
3721 return LowerFDIV32(Op, DAG);
3724 return LowerFDIV64(Op, DAG);
3727 return LowerFDIV16(Op, DAG);
3729 llvm_unreachable("Unexpected type for fdiv");
3732 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3734 StoreSDNode *Store = cast<StoreSDNode>(Op);
3735 EVT VT = Store->getMemoryVT();
3737 if (VT == MVT::i1) {
3738 return DAG.getTruncStore(Store->getChain(), DL,
3739 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3740 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3743 assert(VT.isVector() &&
3744 Store->getValue().getValueType().getScalarType() == MVT::i32);
3746 unsigned AS = Store->getAddressSpace();
3747 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3748 AS, Store->getAlignment())) {
3749 return expandUnalignedStore(Store, DAG);
3752 MachineFunction &MF = DAG.getMachineFunction();
3753 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3754 // If there is a possibilty that flat instruction access scratch memory
3755 // then we need to use the same legalization rules we use for private.
3756 if (AS == AMDGPUASI.FLAT_ADDRESS)
3757 AS = MFI->hasFlatScratchInit() ?
3758 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3760 unsigned NumElements = VT.getVectorNumElements();
3761 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3762 AS == AMDGPUASI.FLAT_ADDRESS) {
3763 if (NumElements > 4)
3764 return SplitVectorStore(Op, DAG);
3766 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3767 switch (Subtarget->getMaxPrivateElementSize()) {
3769 return scalarizeVectorStore(Store, DAG);
3771 if (NumElements > 2)
3772 return SplitVectorStore(Op, DAG);
3775 if (NumElements > 4)
3776 return SplitVectorStore(Op, DAG);
3779 llvm_unreachable("unsupported private_element_size");
3781 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3782 if (NumElements > 2)
3783 return SplitVectorStore(Op, DAG);
3785 if (NumElements == 2)
3788 // If properly aligned, if we split we might be able to use ds_write_b64.
3789 return SplitVectorStore(Op, DAG);
3791 llvm_unreachable("unhandled address space");
3795 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3797 EVT VT = Op.getValueType();
3798 SDValue Arg = Op.getOperand(0);
3799 // TODO: Should this propagate fast-math-flags?
3800 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3801 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3802 DAG.getConstantFP(0.5/M_PI, DL,
3805 switch (Op.getOpcode()) {
3807 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3809 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3811 llvm_unreachable("Wrong trig opcode");
3815 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3816 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3817 assert(AtomicNode->isCompareAndSwap());
3818 unsigned AS = AtomicNode->getAddressSpace();
3820 // No custom lowering required for local address space
3821 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
3824 // Non-local address space requires custom lowering for atomic compare
3825 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3827 SDValue ChainIn = Op.getOperand(0);
3828 SDValue Addr = Op.getOperand(1);
3829 SDValue Old = Op.getOperand(2);
3830 SDValue New = Op.getOperand(3);
3831 EVT VT = Op.getValueType();
3832 MVT SimpleVT = VT.getSimpleVT();
3833 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3835 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3836 SDValue Ops[] = { ChainIn, Addr, NewOld };
3838 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3839 Ops, VT, AtomicNode->getMemOperand());
3842 //===----------------------------------------------------------------------===//
3843 // Custom DAG optimizations
3844 //===----------------------------------------------------------------------===//
3846 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3847 DAGCombinerInfo &DCI) const {
3848 EVT VT = N->getValueType(0);
3849 EVT ScalarVT = VT.getScalarType();
3850 if (ScalarVT != MVT::f32)
3853 SelectionDAG &DAG = DCI.DAG;
3856 SDValue Src = N->getOperand(0);
3857 EVT SrcVT = Src.getValueType();
3859 // TODO: We could try to match extracting the higher bytes, which would be
3860 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3861 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3862 // about in practice.
3863 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3864 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3865 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3866 DCI.AddToWorklist(Cvt.getNode());
3874 /// \brief Return true if the given offset Size in bytes can be folded into
3875 /// the immediate offsets of a memory instruction for the given address space.
3876 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3877 const SISubtarget &STI) {
3878 auto AMDGPUASI = STI.getAMDGPUAS();
3879 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
3880 // MUBUF instructions a 12-bit offset in bytes.
3881 return isUInt<12>(OffsetSize);
3883 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3884 // SMRD instructions have an 8-bit offset in dwords on SI and
3885 // a 20-bit offset in bytes on VI.
3886 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3887 return isUInt<20>(OffsetSize);
3889 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3891 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
3892 AS == AMDGPUASI.REGION_ADDRESS) {
3893 // The single offset versions have a 16-bit offset in bytes.
3894 return isUInt<16>(OffsetSize);
3896 // Indirect register addressing does not use any offsets.
3900 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3902 // This is a variant of
3903 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3905 // The normal DAG combiner will do this, but only if the add has one use since
3906 // that would increase the number of instructions.
3908 // This prevents us from seeing a constant offset that can be folded into a
3909 // memory instruction's addressing mode. If we know the resulting add offset of
3910 // a pointer can be folded into an addressing offset, we can replace the pointer
3911 // operand with the add of new constant offset. This eliminates one of the uses,
3912 // and may allow the remaining use to also be simplified.
3914 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3916 DAGCombinerInfo &DCI) const {
3917 SDValue N0 = N->getOperand(0);
3918 SDValue N1 = N->getOperand(1);
3920 if (N0.getOpcode() != ISD::ADD)
3923 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3927 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3931 // If the resulting offset is too large, we can't fold it into the addressing
3933 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3934 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3937 SelectionDAG &DAG = DCI.DAG;
3939 EVT VT = N->getValueType(0);
3941 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3942 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3944 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3947 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3948 DAGCombinerInfo &DCI) const {
3949 SDValue Ptr = N->getBasePtr();
3950 SelectionDAG &DAG = DCI.DAG;
3953 // TODO: We could also do this for multiplies.
3954 unsigned AS = N->getAddressSpace();
3955 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
3956 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3958 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3960 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3961 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3968 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3969 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3970 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3971 (Opc == ISD::XOR && Val == 0);
3974 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3975 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3976 // integer combine opportunities since most 64-bit operations are decomposed
3977 // this way. TODO: We won't want this for SALU especially if it is an inline
3979 SDValue SITargetLowering::splitBinaryBitConstantOp(
3980 DAGCombinerInfo &DCI,
3982 unsigned Opc, SDValue LHS,
3983 const ConstantSDNode *CRHS) const {
3984 uint64_t Val = CRHS->getZExtValue();
3985 uint32_t ValLo = Lo_32(Val);
3986 uint32_t ValHi = Hi_32(Val);
3987 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3989 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3990 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3991 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3992 // If we need to materialize a 64-bit immediate, it will be split up later
3993 // anyway. Avoid creating the harder to understand 64-bit immediate
3995 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
4001 SDValue SITargetLowering::performAndCombine(SDNode *N,
4002 DAGCombinerInfo &DCI) const {
4003 if (DCI.isBeforeLegalize())
4006 SelectionDAG &DAG = DCI.DAG;
4007 EVT VT = N->getValueType(0);
4008 SDValue LHS = N->getOperand(0);
4009 SDValue RHS = N->getOperand(1);
4012 if (VT == MVT::i64) {
4013 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4016 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
4021 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
4022 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
4023 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
4024 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
4025 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
4027 SDValue X = LHS.getOperand(0);
4028 SDValue Y = RHS.getOperand(0);
4029 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
4032 if (LCC == ISD::SETO) {
4033 if (X != LHS.getOperand(1))
4036 if (RCC == ISD::SETUNE) {
4037 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
4038 if (!C1 || !C1->isInfinity() || C1->isNegative())
4041 const uint32_t Mask = SIInstrFlags::N_NORMAL |
4042 SIInstrFlags::N_SUBNORMAL |
4043 SIInstrFlags::N_ZERO |
4044 SIInstrFlags::P_ZERO |
4045 SIInstrFlags::P_SUBNORMAL |
4046 SIInstrFlags::P_NORMAL;
4048 static_assert(((~(SIInstrFlags::S_NAN |
4049 SIInstrFlags::Q_NAN |
4050 SIInstrFlags::N_INFINITY |
4051 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4055 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4056 X, DAG.getConstant(Mask, DL, MVT::i32));
4064 SDValue SITargetLowering::performOrCombine(SDNode *N,
4065 DAGCombinerInfo &DCI) const {
4066 SelectionDAG &DAG = DCI.DAG;
4067 SDValue LHS = N->getOperand(0);
4068 SDValue RHS = N->getOperand(1);
4070 EVT VT = N->getValueType(0);
4071 if (VT == MVT::i1) {
4072 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4073 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4074 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4075 SDValue Src = LHS.getOperand(0);
4076 if (Src != RHS.getOperand(0))
4079 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4080 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4084 // Only 10 bits are used.
4085 static const uint32_t MaxMask = 0x3ff;
4087 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4089 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4090 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4099 // TODO: This could be a generic combine with a predicate for extracting the
4100 // high half of an integer being free.
4102 // (or i64:x, (zero_extend i32:y)) ->
4103 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4104 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4105 RHS.getOpcode() != ISD::ZERO_EXTEND)
4106 std::swap(LHS, RHS);
4108 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4109 SDValue ExtSrc = RHS.getOperand(0);
4110 EVT SrcVT = ExtSrc.getValueType();
4111 if (SrcVT == MVT::i32) {
4113 SDValue LowLHS, HiBits;
4114 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4115 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4117 DCI.AddToWorklist(LowOr.getNode());
4118 DCI.AddToWorklist(HiBits.getNode());
4120 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4122 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4126 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4129 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4136 SDValue SITargetLowering::performXorCombine(SDNode *N,
4137 DAGCombinerInfo &DCI) const {
4138 EVT VT = N->getValueType(0);
4142 SDValue LHS = N->getOperand(0);
4143 SDValue RHS = N->getOperand(1);
4145 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4148 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4155 // Instructions that will be lowered with a final instruction that zeros the
4156 // high result bits.
4157 // XXX - probably only need to list legal operations.
4158 static bool fp16SrcZerosHighBits(unsigned Opc) {
4167 case ISD::FCANONICALIZE:
4169 case ISD::UINT_TO_FP:
4170 case ISD::SINT_TO_FP:
4172 // Fabs is lowered to a bit operation, but it's an and which will clear the
4173 // high bits anyway.
4187 case ISD::FNEARBYINT:
4192 case AMDGPUISD::FRACT:
4193 case AMDGPUISD::CLAMP:
4194 case AMDGPUISD::COS_HW:
4195 case AMDGPUISD::SIN_HW:
4196 case AMDGPUISD::FMIN3:
4197 case AMDGPUISD::FMAX3:
4198 case AMDGPUISD::FMED3:
4199 case AMDGPUISD::FMAD_FTZ:
4200 case AMDGPUISD::RCP:
4201 case AMDGPUISD::RSQ:
4202 case AMDGPUISD::LDEXP:
4205 // fcopysign, select and others may be lowered to 32-bit bit operations
4206 // which don't zero the high bits.
4211 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4212 DAGCombinerInfo &DCI) const {
4213 if (!Subtarget->has16BitInsts() ||
4214 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4217 EVT VT = N->getValueType(0);
4221 SDValue Src = N->getOperand(0);
4222 if (Src.getValueType() != MVT::i16)
4225 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4226 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4227 if (Src.getOpcode() == ISD::BITCAST) {
4228 SDValue BCSrc = Src.getOperand(0);
4229 if (BCSrc.getValueType() == MVT::f16 &&
4230 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4231 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4237 SDValue SITargetLowering::performClassCombine(SDNode *N,
4238 DAGCombinerInfo &DCI) const {
4239 SelectionDAG &DAG = DCI.DAG;
4240 SDValue Mask = N->getOperand(1);
4242 // fp_class x, 0 -> false
4243 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4244 if (CMask->isNullValue())
4245 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4248 if (N->getOperand(0).isUndef())
4249 return DAG.getUNDEF(MVT::i1);
4254 // Constant fold canonicalize.
4255 SDValue SITargetLowering::performFCanonicalizeCombine(
4257 DAGCombinerInfo &DCI) const {
4258 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4262 SelectionDAG &DAG = DCI.DAG;
4263 const APFloat &C = CFP->getValueAPF();
4265 // Flush denormals to 0 if not enabled.
4266 if (C.isDenormal()) {
4267 EVT VT = N->getValueType(0);
4268 EVT SVT = VT.getScalarType();
4269 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4270 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4272 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4273 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4275 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4276 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4280 EVT VT = N->getValueType(0);
4281 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4282 if (C.isSignaling()) {
4283 // Quiet a signaling NaN.
4284 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4287 // Make sure it is the canonical NaN bitpattern.
4289 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4291 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4292 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4295 return N->getOperand(0);
4298 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4301 return AMDGPUISD::FMAX3;
4303 return AMDGPUISD::SMAX3;
4305 return AMDGPUISD::UMAX3;
4307 return AMDGPUISD::FMIN3;
4309 return AMDGPUISD::SMIN3;
4311 return AMDGPUISD::UMIN3;
4313 llvm_unreachable("Not a min/max opcode");
4317 SDValue SITargetLowering::performIntMed3ImmCombine(
4318 SelectionDAG &DAG, const SDLoc &SL,
4319 SDValue Op0, SDValue Op1, bool Signed) const {
4320 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4324 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4329 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4332 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4336 EVT VT = K0->getValueType(0);
4337 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4338 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4339 return DAG.getNode(Med3Opc, SL, VT,
4340 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4343 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4345 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4347 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4348 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4349 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4351 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4352 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4355 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4356 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4359 return DAG.isKnownNeverNaN(Op);
4362 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4365 SDValue Op1) const {
4366 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4370 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4374 // Ordered >= (although NaN inputs should have folded away by now).
4375 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4376 if (Cmp == APFloat::cmpGreaterThan)
4379 // TODO: Check IEEE bit enabled?
4380 EVT VT = K0->getValueType(0);
4381 if (Subtarget->enableDX10Clamp()) {
4382 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4383 // hardware fmed3 behavior converting to a min.
4384 // FIXME: Should this be allowing -0.0?
4385 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4386 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4389 // med3 for f16 is only available on gfx9+.
4390 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4393 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4394 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4395 // give the other result, which is different from med3 with a NaN input.
4396 SDValue Var = Op0.getOperand(0);
4397 if (!isKnownNeverSNan(DAG, Var))
4400 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4401 Var, SDValue(K0, 0), SDValue(K1, 0));
4404 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4405 DAGCombinerInfo &DCI) const {
4406 SelectionDAG &DAG = DCI.DAG;
4408 EVT VT = N->getValueType(0);
4409 unsigned Opc = N->getOpcode();
4410 SDValue Op0 = N->getOperand(0);
4411 SDValue Op1 = N->getOperand(1);
4413 // Only do this if the inner op has one use since this will just increases
4414 // register pressure for no benefit.
4417 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4419 // max(max(a, b), c) -> max3(a, b, c)
4420 // min(min(a, b), c) -> min3(a, b, c)
4421 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4423 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4432 // max(a, max(b, c)) -> max3(a, b, c)
4433 // min(a, min(b, c)) -> min3(a, b, c)
4434 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4436 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4445 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4446 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4447 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4451 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4452 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4456 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4457 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4458 (Opc == AMDGPUISD::FMIN_LEGACY &&
4459 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4460 (VT == MVT::f32 || VT == MVT::f64 ||
4461 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4463 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4470 static bool isClampZeroToOne(SDValue A, SDValue B) {
4471 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4472 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4473 // FIXME: Should this be allowing -0.0?
4474 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4475 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4482 // FIXME: Should only worry about snans for version with chain.
4483 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4484 DAGCombinerInfo &DCI) const {
4485 EVT VT = N->getValueType(0);
4486 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4487 // NaNs. With a NaN input, the order of the operands may change the result.
4489 SelectionDAG &DAG = DCI.DAG;
4492 SDValue Src0 = N->getOperand(0);
4493 SDValue Src1 = N->getOperand(1);
4494 SDValue Src2 = N->getOperand(2);
4496 if (isClampZeroToOne(Src0, Src1)) {
4497 // const_a, const_b, x -> clamp is safe in all cases including signaling
4499 // FIXME: Should this be allowing -0.0?
4500 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4503 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4504 // handling no dx10-clamp?
4505 if (Subtarget->enableDX10Clamp()) {
4506 // If NaNs is clamped to 0, we are free to reorder the inputs.
4508 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4509 std::swap(Src0, Src1);
4511 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4512 std::swap(Src1, Src2);
4514 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4515 std::swap(Src0, Src1);
4517 if (isClampZeroToOne(Src1, Src2))
4518 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4524 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4525 DAGCombinerInfo &DCI) const {
4526 SDValue Src0 = N->getOperand(0);
4527 SDValue Src1 = N->getOperand(1);
4528 if (Src0.isUndef() && Src1.isUndef())
4529 return DCI.DAG.getUNDEF(N->getValueType(0));
4533 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4535 const SDNode *N1) const {
4536 EVT VT = N0->getValueType(0);
4538 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4539 // support denormals ever.
4540 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4541 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4544 const TargetOptions &Options = DAG.getTarget().Options;
4545 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4546 Options.UnsafeFPMath ||
4547 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4548 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4549 isFMAFasterThanFMulAndFAdd(VT)) {
4556 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4557 DAGCombinerInfo &DCI) const {
4558 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4561 SelectionDAG &DAG = DCI.DAG;
4562 EVT VT = N->getValueType(0);
4565 SDValue LHS = N->getOperand(0);
4566 SDValue RHS = N->getOperand(1);
4568 // These should really be instruction patterns, but writing patterns with
4569 // source modiifiers is a pain.
4571 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4572 if (LHS.getOpcode() == ISD::FADD) {
4573 SDValue A = LHS.getOperand(0);
4574 if (A == LHS.getOperand(1)) {
4575 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4577 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4578 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4583 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4584 if (RHS.getOpcode() == ISD::FADD) {
4585 SDValue A = RHS.getOperand(0);
4586 if (A == RHS.getOperand(1)) {
4587 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4589 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4590 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4598 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4599 DAGCombinerInfo &DCI) const {
4600 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4603 SelectionDAG &DAG = DCI.DAG;
4605 EVT VT = N->getValueType(0);
4606 assert(!VT.isVector());
4608 // Try to get the fneg to fold into the source modifier. This undoes generic
4609 // DAG combines and folds them into the mad.
4611 // Only do this if we are not trying to support denormals. v_mad_f32 does
4612 // not support denormals ever.
4613 SDValue LHS = N->getOperand(0);
4614 SDValue RHS = N->getOperand(1);
4615 if (LHS.getOpcode() == ISD::FADD) {
4616 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4617 SDValue A = LHS.getOperand(0);
4618 if (A == LHS.getOperand(1)) {
4619 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4621 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4622 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4624 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4629 if (RHS.getOpcode() == ISD::FADD) {
4630 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4632 SDValue A = RHS.getOperand(0);
4633 if (A == RHS.getOperand(1)) {
4634 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4636 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4637 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4645 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4646 DAGCombinerInfo &DCI) const {
4647 SelectionDAG &DAG = DCI.DAG;
4650 SDValue LHS = N->getOperand(0);
4651 SDValue RHS = N->getOperand(1);
4652 EVT VT = LHS.getValueType();
4654 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4658 // Match isinf pattern
4659 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4660 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4661 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4662 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4666 const APFloat &APF = CRHS->getValueAPF();
4667 if (APF.isInfinity() && !APF.isNegative()) {
4668 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4669 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4670 DAG.getConstant(Mask, SL, MVT::i32));
4677 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4678 DAGCombinerInfo &DCI) const {
4679 SelectionDAG &DAG = DCI.DAG;
4681 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4683 SDValue Src = N->getOperand(0);
4684 SDValue Srl = N->getOperand(0);
4685 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4686 Srl = Srl.getOperand(0);
4688 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4689 if (Srl.getOpcode() == ISD::SRL) {
4690 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4691 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4692 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4694 if (const ConstantSDNode *C =
4695 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4696 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4699 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4700 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4701 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4707 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4709 APInt KnownZero, KnownOne;
4710 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4711 !DCI.isBeforeLegalizeOps());
4712 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4713 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
4714 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4715 DCI.CommitTargetLoweringOpt(TLO);
4721 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4722 DAGCombinerInfo &DCI) const {
4723 switch (N->getOpcode()) {
4725 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4727 return performFAddCombine(N, DCI);
4729 return performFSubCombine(N, DCI);
4731 return performSetCCCombine(N, DCI);
4738 case AMDGPUISD::FMIN_LEGACY:
4739 case AMDGPUISD::FMAX_LEGACY: {
4740 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4741 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4742 return performMinMaxCombine(N, DCI);
4747 case ISD::ATOMIC_LOAD:
4748 case ISD::ATOMIC_STORE:
4749 case ISD::ATOMIC_CMP_SWAP:
4750 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4751 case ISD::ATOMIC_SWAP:
4752 case ISD::ATOMIC_LOAD_ADD:
4753 case ISD::ATOMIC_LOAD_SUB:
4754 case ISD::ATOMIC_LOAD_AND:
4755 case ISD::ATOMIC_LOAD_OR:
4756 case ISD::ATOMIC_LOAD_XOR:
4757 case ISD::ATOMIC_LOAD_NAND:
4758 case ISD::ATOMIC_LOAD_MIN:
4759 case ISD::ATOMIC_LOAD_MAX:
4760 case ISD::ATOMIC_LOAD_UMIN:
4761 case ISD::ATOMIC_LOAD_UMAX:
4762 case AMDGPUISD::ATOMIC_INC:
4763 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4764 if (DCI.isBeforeLegalize())
4766 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4768 return performAndCombine(N, DCI);
4770 return performOrCombine(N, DCI);
4772 return performXorCombine(N, DCI);
4773 case ISD::ZERO_EXTEND:
4774 return performZeroExtendCombine(N, DCI);
4775 case AMDGPUISD::FP_CLASS:
4776 return performClassCombine(N, DCI);
4777 case ISD::FCANONICALIZE:
4778 return performFCanonicalizeCombine(N, DCI);
4779 case AMDGPUISD::FRACT:
4780 case AMDGPUISD::RCP:
4781 case AMDGPUISD::RSQ:
4782 case AMDGPUISD::RCP_LEGACY:
4783 case AMDGPUISD::RSQ_LEGACY:
4784 case AMDGPUISD::RSQ_CLAMP:
4785 case AMDGPUISD::LDEXP: {
4786 SDValue Src = N->getOperand(0);
4791 case ISD::SINT_TO_FP:
4792 case ISD::UINT_TO_FP:
4793 return performUCharToFloatCombine(N, DCI);
4794 case AMDGPUISD::CVT_F32_UBYTE0:
4795 case AMDGPUISD::CVT_F32_UBYTE1:
4796 case AMDGPUISD::CVT_F32_UBYTE2:
4797 case AMDGPUISD::CVT_F32_UBYTE3:
4798 return performCvtF32UByteNCombine(N, DCI);
4799 case AMDGPUISD::FMED3:
4800 return performFMed3Combine(N, DCI);
4801 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4802 return performCvtPkRTZCombine(N, DCI);
4803 case ISD::SCALAR_TO_VECTOR: {
4804 SelectionDAG &DAG = DCI.DAG;
4805 EVT VT = N->getValueType(0);
4807 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4808 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4810 SDValue Src = N->getOperand(0);
4811 EVT EltVT = Src.getValueType();
4812 if (EltVT == MVT::f16)
4813 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4815 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4816 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4822 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4825 /// \brief Helper function for adjustWritemask
4826 static unsigned SubIdx2Lane(unsigned Idx) {
4829 case AMDGPU::sub0: return 0;
4830 case AMDGPU::sub1: return 1;
4831 case AMDGPU::sub2: return 2;
4832 case AMDGPU::sub3: return 3;
4836 /// \brief Adjust the writemask of MIMG instructions
4837 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4838 SelectionDAG &DAG) const {
4839 SDNode *Users[4] = { };
4841 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4842 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4843 unsigned NewDmask = 0;
4845 // Try to figure out the used register components
4846 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4849 // Don't look at users of the chain.
4850 if (I.getUse().getResNo() != 0)
4853 // Abort if we can't understand the usage
4854 if (!I->isMachineOpcode() ||
4855 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4858 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4859 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4860 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4862 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4864 // Set which texture component corresponds to the lane.
4866 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4868 Comp = countTrailingZeros(Dmask);
4869 Dmask &= ~(1 << Comp);
4872 // Abort if we have more than one user per component
4877 NewDmask |= 1 << Comp;
4880 // Abort if there's no change
4881 if (NewDmask == OldDmask)
4884 // Adjust the writemask in the node
4885 std::vector<SDValue> Ops;
4886 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4887 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4888 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4889 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4891 // If we only got one lane, replace it with a copy
4892 // (if NewDmask has only one bit set...)
4893 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4894 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4896 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4897 SDLoc(), Users[Lane]->getValueType(0),
4898 SDValue(Node, 0), RC);
4899 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4903 // Update the users of the node with the new indices
4904 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4905 SDNode *User = Users[i];
4909 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4910 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4914 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4915 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4916 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4921 static bool isFrameIndexOp(SDValue Op) {
4922 if (Op.getOpcode() == ISD::AssertZext)
4923 Op = Op.getOperand(0);
4925 return isa<FrameIndexSDNode>(Op);
4928 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4929 /// with frame index operands.
4930 /// LLVM assumes that inputs are to these instructions are registers.
4931 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4932 SelectionDAG &DAG) const {
4933 if (Node->getOpcode() == ISD::CopyToReg) {
4934 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
4935 SDValue SrcVal = Node->getOperand(2);
4937 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
4938 // to try understanding copies to physical registers.
4939 if (SrcVal.getValueType() == MVT::i1 &&
4940 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
4942 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
4943 SDValue VReg = DAG.getRegister(
4944 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
4946 SDNode *Glued = Node->getGluedNode();
4948 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
4949 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
4951 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
4952 VReg, ToVReg.getValue(1));
4953 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
4954 DAG.RemoveDeadNode(Node);
4955 return ToResultReg.getNode();
4959 SmallVector<SDValue, 8> Ops;
4960 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4961 if (!isFrameIndexOp(Node->getOperand(i))) {
4962 Ops.push_back(Node->getOperand(i));
4967 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4968 Node->getOperand(i).getValueType(),
4969 Node->getOperand(i)), 0));
4972 DAG.UpdateNodeOperands(Node, Ops);
4976 /// \brief Fold the instructions after selecting them.
4977 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4978 SelectionDAG &DAG) const {
4979 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4980 unsigned Opcode = Node->getMachineOpcode();
4982 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4983 !TII->isGather4(Opcode))
4984 adjustWritemask(Node, DAG);
4986 if (Opcode == AMDGPU::INSERT_SUBREG ||
4987 Opcode == AMDGPU::REG_SEQUENCE) {
4988 legalizeTargetIndependentNode(Node, DAG);
4994 /// \brief Assign the register class depending on the number of
4995 /// bits set in the writemask
4996 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4997 SDNode *Node) const {
4998 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5000 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5002 if (TII->isVOP3(MI.getOpcode())) {
5003 // Make sure constant bus requirements are respected.
5004 TII->legalizeOperandsVOP3(MRI, MI);
5008 if (TII->isMIMG(MI)) {
5009 unsigned VReg = MI.getOperand(0).getReg();
5010 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
5011 // TODO: Need mapping tables to handle other cases (register classes).
5012 if (RC != &AMDGPU::VReg_128RegClass)
5015 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
5016 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
5017 unsigned BitsSet = 0;
5018 for (unsigned i = 0; i < 4; ++i)
5019 BitsSet += Writemask & (1 << i) ? 1 : 0;
5022 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
5023 case 2: RC = &AMDGPU::VReg_64RegClass; break;
5024 case 3: RC = &AMDGPU::VReg_96RegClass; break;
5027 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
5028 MI.setDesc(TII->get(NewOpcode));
5029 MRI.setRegClass(VReg, RC);
5033 // Replace unused atomics with the no return version.
5034 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
5035 if (NoRetAtomicOp != -1) {
5036 if (!Node->hasAnyUseOfValue(0)) {
5037 MI.setDesc(TII->get(NoRetAtomicOp));
5038 MI.RemoveOperand(0);
5042 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5043 // instruction, because the return type of these instructions is a vec2 of
5044 // the memory type, so it can be tied to the input operand.
5045 // This means these instructions always have a use, so we need to add a
5046 // special case to check if the atomic has only one extract_subreg use,
5047 // which itself has no uses.
5048 if ((Node->hasNUsesOfValue(1, 0) &&
5049 Node->use_begin()->isMachineOpcode() &&
5050 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5051 !Node->use_begin()->hasAnyUseOfValue(0))) {
5052 unsigned Def = MI.getOperand(0).getReg();
5054 // Change this into a noret atomic.
5055 MI.setDesc(TII->get(NoRetAtomicOp));
5056 MI.RemoveOperand(0);
5058 // If we only remove the def operand from the atomic instruction, the
5059 // extract_subreg will be left with a use of a vreg without a def.
5060 // So we need to insert an implicit_def to avoid machine verifier
5062 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5063 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5069 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5071 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5072 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5075 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5077 SDValue Ptr) const {
5078 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5080 // Build the half of the subregister with the constants before building the
5081 // full 128-bit register. If we are building multiple resource descriptors,
5082 // this will allow CSEing of the 2-component register.
5083 const SDValue Ops0[] = {
5084 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5085 buildSMovImm32(DAG, DL, 0),
5086 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5087 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5088 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5091 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5092 MVT::v2i32, Ops0), 0);
5094 // Combine the constants and the pointer.
5095 const SDValue Ops1[] = {
5096 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5098 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5100 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5103 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5106 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5107 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5108 /// of the resource descriptor) to create an offset, which is added to
5109 /// the resource pointer.
5110 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5111 SDValue Ptr, uint32_t RsrcDword1,
5112 uint64_t RsrcDword2And3) const {
5113 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5114 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5116 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5117 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5121 SDValue DataLo = buildSMovImm32(DAG, DL,
5122 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5123 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5125 const SDValue Ops[] = {
5126 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5128 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5130 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5132 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5134 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5137 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5140 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5141 const TargetRegisterClass *RC,
5142 unsigned Reg, EVT VT) const {
5143 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5145 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5146 cast<RegisterSDNode>(VReg)->getReg(), VT);
5149 //===----------------------------------------------------------------------===//
5150 // SI Inline Assembly Support
5151 //===----------------------------------------------------------------------===//
5153 std::pair<unsigned, const TargetRegisterClass *>
5154 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5155 StringRef Constraint,
5157 if (!isTypeLegal(VT))
5158 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5160 if (Constraint.size() == 1) {
5161 switch (Constraint[0]) {
5164 switch (VT.getSizeInBits()) {
5166 return std::make_pair(0U, nullptr);
5169 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5171 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5173 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5175 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5177 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5181 switch (VT.getSizeInBits()) {
5183 return std::make_pair(0U, nullptr);
5186 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5188 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5190 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5192 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5194 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5196 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5201 if (Constraint.size() > 1) {
5202 const TargetRegisterClass *RC = nullptr;
5203 if (Constraint[1] == 'v') {
5204 RC = &AMDGPU::VGPR_32RegClass;
5205 } else if (Constraint[1] == 's') {
5206 RC = &AMDGPU::SGPR_32RegClass;
5211 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5212 if (!Failed && Idx < RC->getNumRegs())
5213 return std::make_pair(RC->getRegister(Idx), RC);
5216 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5219 SITargetLowering::ConstraintType
5220 SITargetLowering::getConstraintType(StringRef Constraint) const {
5221 if (Constraint.size() == 1) {
5222 switch (Constraint[0]) {
5226 return C_RegisterClass;
5229 return TargetLowering::getConstraintType(Constraint);