1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "AMDGPUIntrinsicInfo.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIDefines.h"
25 #include "SIISelLowering.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/MachineValueType.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Target/TargetCallingConv.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include "llvm/Target/TargetRegisterInfo.h"
85 static cl::opt<bool> EnableVGPRIndexMode(
86 "amdgpu-vgpr-index-mode",
87 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
90 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
91 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
92 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
93 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
94 return AMDGPU::SGPR0 + Reg;
97 llvm_unreachable("Cannot allocate sgpr");
100 SITargetLowering::SITargetLowering(const TargetMachine &TM,
101 const SISubtarget &STI)
102 : AMDGPUTargetLowering(TM, STI) {
103 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
104 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
106 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
107 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
109 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
110 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
111 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
113 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
114 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
116 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
117 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
119 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
120 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
122 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
123 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
125 if (Subtarget->has16BitInsts()) {
126 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
127 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
130 if (Subtarget->hasVOP3PInsts()) {
131 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
132 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
135 computeRegisterProperties(STI.getRegisterInfo());
137 // We need to custom lower vector stores from local memory
138 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
139 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
140 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
141 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
142 setOperationAction(ISD::LOAD, MVT::i1, Custom);
144 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
145 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
146 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
147 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
148 setOperationAction(ISD::STORE, MVT::i1, Custom);
150 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
151 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
152 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
153 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
154 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
155 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
156 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
157 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
158 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
159 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
161 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
162 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
163 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
165 setOperationAction(ISD::SELECT, MVT::i1, Promote);
166 setOperationAction(ISD::SELECT, MVT::i64, Custom);
167 setOperationAction(ISD::SELECT, MVT::f64, Promote);
168 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
170 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
171 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
176 setOperationAction(ISD::SETCC, MVT::i1, Promote);
177 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
178 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
179 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
181 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
182 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
184 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
192 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
194 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
195 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
197 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
199 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
200 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
201 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
203 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
204 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
205 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
206 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
207 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
208 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
210 setOperationAction(ISD::UADDO, MVT::i32, Legal);
211 setOperationAction(ISD::USUBO, MVT::i32, Legal);
213 // We only support LOAD/STORE and vector manipulation ops for vectors
214 // with > 4 elements.
215 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
216 MVT::v2i64, MVT::v2f64}) {
217 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
221 case ISD::BUILD_VECTOR:
223 case ISD::EXTRACT_VECTOR_ELT:
224 case ISD::INSERT_VECTOR_ELT:
225 case ISD::INSERT_SUBVECTOR:
226 case ISD::EXTRACT_SUBVECTOR:
227 case ISD::SCALAR_TO_VECTOR:
229 case ISD::CONCAT_VECTORS:
230 setOperationAction(Op, VT, Custom);
233 setOperationAction(Op, VT, Expand);
239 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
240 // is expanded to avoid having two separate loops in case the index is a VGPR.
242 // Most operations are naturally 32-bit vector operations. We only support
243 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
244 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
245 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
246 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
248 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
249 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
251 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
252 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
254 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
255 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
258 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
259 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
260 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
261 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
263 // Avoid stack access for these.
264 // TODO: Generalize to more vector types.
265 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
266 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
267 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
270 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
271 // and output demarshalling
272 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
273 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
275 // We can't return success/failure, only the old value,
276 // let LLVM add the comparison
277 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
278 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
280 if (getSubtarget()->hasFlatAddressSpace()) {
281 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
282 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
285 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
286 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
288 // On SI this is s_memtime and s_memrealtime on VI.
289 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
290 setOperationAction(ISD::TRAP, MVT::Other, Legal);
291 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
293 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
294 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
296 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
297 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
298 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
299 setOperationAction(ISD::FRINT, MVT::f64, Legal);
302 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
304 setOperationAction(ISD::FSIN, MVT::f32, Custom);
305 setOperationAction(ISD::FCOS, MVT::f32, Custom);
306 setOperationAction(ISD::FDIV, MVT::f32, Custom);
307 setOperationAction(ISD::FDIV, MVT::f64, Custom);
309 if (Subtarget->has16BitInsts()) {
310 setOperationAction(ISD::Constant, MVT::i16, Legal);
312 setOperationAction(ISD::SMIN, MVT::i16, Legal);
313 setOperationAction(ISD::SMAX, MVT::i16, Legal);
315 setOperationAction(ISD::UMIN, MVT::i16, Legal);
316 setOperationAction(ISD::UMAX, MVT::i16, Legal);
318 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
319 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
321 setOperationAction(ISD::ROTR, MVT::i16, Promote);
322 setOperationAction(ISD::ROTL, MVT::i16, Promote);
324 setOperationAction(ISD::SDIV, MVT::i16, Promote);
325 setOperationAction(ISD::UDIV, MVT::i16, Promote);
326 setOperationAction(ISD::SREM, MVT::i16, Promote);
327 setOperationAction(ISD::UREM, MVT::i16, Promote);
329 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
330 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
332 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
334 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
335 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
337 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
339 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
341 setOperationAction(ISD::LOAD, MVT::i16, Custom);
343 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
345 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
346 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
347 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
348 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
350 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
351 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
352 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
353 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
355 // F16 - Constant Actions.
356 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
358 // F16 - Load/Store Actions.
359 setOperationAction(ISD::LOAD, MVT::f16, Promote);
360 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
361 setOperationAction(ISD::STORE, MVT::f16, Promote);
362 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
364 // F16 - VOP1 Actions.
365 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
366 setOperationAction(ISD::FCOS, MVT::f16, Promote);
367 setOperationAction(ISD::FSIN, MVT::f16, Promote);
368 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
369 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
370 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
371 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
372 setOperationAction(ISD::FROUND, MVT::f16, Custom);
374 // F16 - VOP2 Actions.
375 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
376 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
377 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
378 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
379 setOperationAction(ISD::FDIV, MVT::f16, Custom);
381 // F16 - VOP3 Actions.
382 setOperationAction(ISD::FMA, MVT::f16, Legal);
383 if (!Subtarget->hasFP16Denormals())
384 setOperationAction(ISD::FMAD, MVT::f16, Legal);
387 if (Subtarget->hasVOP3PInsts()) {
388 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
389 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
393 case ISD::BUILD_VECTOR:
395 case ISD::EXTRACT_VECTOR_ELT:
396 case ISD::INSERT_VECTOR_ELT:
397 case ISD::INSERT_SUBVECTOR:
398 case ISD::EXTRACT_SUBVECTOR:
399 case ISD::SCALAR_TO_VECTOR:
401 case ISD::CONCAT_VECTORS:
402 setOperationAction(Op, VT, Custom);
405 setOperationAction(Op, VT, Expand);
411 // XXX - Do these do anything? Vector constants turn into build_vector.
412 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
413 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
415 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
416 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
417 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
418 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
420 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
421 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
422 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
423 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
425 setOperationAction(ISD::AND, MVT::v2i16, Promote);
426 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
427 setOperationAction(ISD::OR, MVT::v2i16, Promote);
428 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
429 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
430 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
431 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
432 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
433 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
434 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
436 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
437 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
438 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
439 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
440 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
441 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
442 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
443 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
444 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
445 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
447 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
448 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
449 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
450 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
451 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
452 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
454 // This isn't really legal, but this avoids the legalizer unrolling it (and
455 // allows matching fneg (fabs x) patterns)
456 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
458 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
459 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
461 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
462 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
463 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
466 setTargetDAGCombine(ISD::FADD);
467 setTargetDAGCombine(ISD::FSUB);
468 setTargetDAGCombine(ISD::FMINNUM);
469 setTargetDAGCombine(ISD::FMAXNUM);
470 setTargetDAGCombine(ISD::SMIN);
471 setTargetDAGCombine(ISD::SMAX);
472 setTargetDAGCombine(ISD::UMIN);
473 setTargetDAGCombine(ISD::UMAX);
474 setTargetDAGCombine(ISD::SETCC);
475 setTargetDAGCombine(ISD::AND);
476 setTargetDAGCombine(ISD::OR);
477 setTargetDAGCombine(ISD::XOR);
478 setTargetDAGCombine(ISD::SINT_TO_FP);
479 setTargetDAGCombine(ISD::UINT_TO_FP);
480 setTargetDAGCombine(ISD::FCANONICALIZE);
481 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
482 setTargetDAGCombine(ISD::ZERO_EXTEND);
484 // All memory operations. Some folding on the pointer operand is done to help
485 // matching the constant offsets in the addressing modes.
486 setTargetDAGCombine(ISD::LOAD);
487 setTargetDAGCombine(ISD::STORE);
488 setTargetDAGCombine(ISD::ATOMIC_LOAD);
489 setTargetDAGCombine(ISD::ATOMIC_STORE);
490 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
491 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
492 setTargetDAGCombine(ISD::ATOMIC_SWAP);
493 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
494 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
495 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
496 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
497 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
498 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
499 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
500 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
501 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
502 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
504 setSchedulingPreference(Sched::RegPressure);
507 const SISubtarget *SITargetLowering::getSubtarget() const {
508 return static_cast<const SISubtarget *>(Subtarget);
511 //===----------------------------------------------------------------------===//
512 // TargetLowering queries
513 //===----------------------------------------------------------------------===//
515 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
517 // SI has some legal vector types, but no legal vector operations. Say no
518 // shuffles are legal in order to prefer scalarizing some vector operations.
522 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
524 unsigned IntrID) const {
526 case Intrinsic::amdgcn_atomic_inc:
527 case Intrinsic::amdgcn_atomic_dec: {
528 Info.opc = ISD::INTRINSIC_W_CHAIN;
529 Info.memVT = MVT::getVT(CI.getType());
530 Info.ptrVal = CI.getOperand(0);
533 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
534 Info.vol = !Vol || !Vol->isNullValue();
536 Info.writeMem = true;
544 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
545 SmallVectorImpl<Value*> &Ops,
546 Type *&AccessTy) const {
547 switch (II->getIntrinsicID()) {
548 case Intrinsic::amdgcn_atomic_inc:
549 case Intrinsic::amdgcn_atomic_dec: {
550 Value *Ptr = II->getArgOperand(0);
551 AccessTy = II->getType();
560 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
561 // Flat instructions do not have offsets, and only have the register
563 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
566 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
567 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
568 // additionally can do r + r + i with addr64. 32-bit has more addressing
569 // mode options. Depending on the resource constant, it can also do
570 // (i64 r0) + (i32 r1) * (i14 i).
572 // Private arrays end up using a scratch buffer most of the time, so also
573 // assume those use MUBUF instructions. Scratch loads / stores are currently
574 // implemented as mubuf instructions with offen bit set, so slightly
575 // different than the normal addr64.
576 if (!isUInt<12>(AM.BaseOffs))
579 // FIXME: Since we can split immediate into soffset and immediate offset,
580 // would it make sense to allow any immediate?
583 case 0: // r + i or just i, depending on HasBaseReg.
586 return true; // We have r + r or r + i.
593 // Allow 2 * r as r + r
594 // Or 2 * r + i is allowed as r + r + i.
596 default: // Don't allow n * r
601 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
602 const AddrMode &AM, Type *Ty,
604 // No global is ever allowed as a base.
608 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
609 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
610 // Assume the we will use FLAT for all global memory accesses
612 // FIXME: This assumption is currently wrong. On VI we still use
613 // MUBUF instructions for the r + i addressing mode. As currently
614 // implemented, the MUBUF instructions only work on buffer < 4GB.
615 // It may be possible to support > 4GB buffers with MUBUF instructions,
616 // by setting the stride value in the resource descriptor which would
617 // increase the size limit to (stride * 4GB). However, this is risky,
618 // because it has never been validated.
619 return isLegalFlatAddressingMode(AM);
622 return isLegalMUBUFAddressingMode(AM);
623 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
624 // If the offset isn't a multiple of 4, it probably isn't going to be
625 // correctly aligned.
626 // FIXME: Can we get the real alignment here?
627 if (AM.BaseOffs % 4 != 0)
628 return isLegalMUBUFAddressingMode(AM);
630 // There are no SMRD extloads, so if we have to do a small type access we
631 // will use a MUBUF load.
632 // FIXME?: We also need to do this if unaligned, but we don't know the
634 if (DL.getTypeStoreSize(Ty) < 4)
635 return isLegalMUBUFAddressingMode(AM);
637 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
638 // SMRD instructions have an 8-bit, dword offset on SI.
639 if (!isUInt<8>(AM.BaseOffs / 4))
641 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
642 // On CI+, this can also be a 32-bit literal constant offset. If it fits
643 // in 8-bits, it can use a smaller encoding.
644 if (!isUInt<32>(AM.BaseOffs / 4))
646 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
647 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
648 if (!isUInt<20>(AM.BaseOffs))
651 llvm_unreachable("unhandled generation");
653 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
656 if (AM.Scale == 1 && AM.HasBaseReg)
661 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
662 return isLegalMUBUFAddressingMode(AM);
663 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
664 AS == AMDGPUASI.REGION_ADDRESS) {
665 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
667 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
668 // an 8-bit dword offset but we don't know the alignment here.
669 if (!isUInt<16>(AM.BaseOffs))
672 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
675 if (AM.Scale == 1 && AM.HasBaseReg)
679 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
680 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
681 // For an unknown address space, this usually means that this is for some
682 // reason being used for pure arithmetic, and not based on some addressing
683 // computation. We don't have instructions that compute pointers with any
684 // addressing modes, so treat them as having no offset like flat
686 return isLegalFlatAddressingMode(AM);
688 llvm_unreachable("unhandled address space");
692 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
695 bool *IsFast) const {
699 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
700 // which isn't a simple VT.
701 // Until MVT is extended to handle this, simply check for the size and
702 // rely on the condition below: allow accesses if the size is a multiple of 4.
703 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
704 VT.getStoreSize() > 16)) {
708 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
709 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
710 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
711 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
712 // with adjacent offsets.
713 bool AlignedBy4 = (Align % 4 == 0);
715 *IsFast = AlignedBy4;
720 // FIXME: We have to be conservative here and assume that flat operations
721 // will access scratch. If we had access to the IR function, then we
722 // could determine if any private memory was used in the function.
723 if (!Subtarget->hasUnalignedScratchAccess() &&
724 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
725 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
729 if (Subtarget->hasUnalignedBufferAccess()) {
730 // If we have an uniform constant load, it still requires using a slow
731 // buffer instruction if unaligned.
733 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
734 (Align % 4 == 0) : true;
740 // Smaller than dword value must be aligned.
741 if (VT.bitsLT(MVT::i32))
744 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
745 // byte-address are ignored, thus forcing Dword alignment.
746 // This applies to private, global, and constant memory.
750 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
753 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
754 unsigned SrcAlign, bool IsMemset,
757 MachineFunction &MF) const {
758 // FIXME: Should account for address space here.
760 // The default fallback uses the private pointer size as a guess for a type to
761 // use. Make sure we switch these to 64-bit accesses.
763 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
766 if (Size >= 8 && DstAlign >= 4)
773 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
774 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
775 AS == AMDGPUASI.FLAT_ADDRESS ||
776 AS == AMDGPUASI.CONSTANT_ADDRESS;
779 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
780 unsigned DestAS) const {
781 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
782 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
785 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
786 const MemSDNode *MemNode = cast<MemSDNode>(N);
787 const Value *Ptr = MemNode->getMemOperand()->getValue();
788 const Instruction *I = dyn_cast<Instruction>(Ptr);
789 return I && I->getMetadata("amdgpu.noclobber");
792 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
793 unsigned DestAS) const {
794 // Flat -> private/local is a simple truncate.
795 // Flat -> global is no-op
796 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
799 return isNoopAddrSpaceCast(SrcAS, DestAS);
802 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
803 const MemSDNode *MemNode = cast<MemSDNode>(N);
805 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
808 TargetLoweringBase::LegalizeTypeAction
809 SITargetLowering::getPreferredVectorAction(EVT VT) const {
810 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
811 return TypeSplitVector;
813 return TargetLoweringBase::getPreferredVectorAction(VT);
816 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
818 // FIXME: Could be smarter if called for vector constants.
822 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
823 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
828 // These operations are done with 32-bit instructions anyway.
840 // SimplifySetCC uses this function to determine whether or not it should
841 // create setcc with i1 operands. We don't have instructions for i1 setcc.
842 if (VT == MVT::i1 && Op == ISD::SETCC)
845 return TargetLowering::isTypeDesirableForOp(Op, VT);
848 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
851 uint64_t Offset) const {
852 const DataLayout &DL = DAG.getDataLayout();
853 MachineFunction &MF = DAG.getMachineFunction();
854 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
855 unsigned InputPtrReg = TRI->getPreloadedValue(MF,
856 SIRegisterInfo::KERNARG_SEGMENT_PTR);
858 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
859 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
860 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
861 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
862 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
863 DAG.getConstant(Offset, SL, PtrVT));
866 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
867 const SDLoc &SL, SDValue Val,
869 const ISD::InputArg *Arg) const {
870 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
872 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
873 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
876 if (MemVT.isFloatingPoint())
877 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
879 Val = DAG.getSExtOrTrunc(Val, SL, VT);
881 Val = DAG.getZExtOrTrunc(Val, SL, VT);
886 SDValue SITargetLowering::lowerKernargMemParameter(
887 SelectionDAG &DAG, EVT VT, EVT MemVT,
888 const SDLoc &SL, SDValue Chain,
889 uint64_t Offset, bool Signed,
890 const ISD::InputArg *Arg) const {
891 const DataLayout &DL = DAG.getDataLayout();
892 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
893 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
894 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
896 unsigned Align = DL.getABITypeAlignment(Ty);
898 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
899 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
900 MachineMemOperand::MONonTemporal |
901 MachineMemOperand::MODereferenceable |
902 MachineMemOperand::MOInvariant);
904 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
905 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
908 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
909 CallingConv::ID CallConv,
910 ArrayRef<ISD::InputArg> Ins,
913 SIMachineFunctionInfo *Info) {
914 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
915 const ISD::InputArg &Arg = Ins[I];
917 // First check if it's a PS input addr.
918 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
919 !Arg.Flags.isByVal() && PSInputNum <= 15) {
921 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
922 // We can safely skip PS inputs.
928 Info->markPSInputAllocated(PSInputNum);
930 Info->markPSInputEnabled(PSInputNum);
935 // Second split vertices into their elements.
936 if (Arg.VT.isVector()) {
937 ISD::InputArg NewArg = Arg;
938 NewArg.Flags.setSplit();
939 NewArg.VT = Arg.VT.getVectorElementType();
941 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
942 // three or five element vertex only needs three or five registers,
943 // NOT four or eight.
944 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
945 unsigned NumElements = ParamType->getVectorNumElements();
947 for (unsigned J = 0; J != NumElements; ++J) {
948 Splits.push_back(NewArg);
949 NewArg.PartOffset += NewArg.VT.getStoreSize();
952 Splits.push_back(Arg);
957 // Allocate special inputs passed in VGPRs.
958 static void allocateSpecialInputVGPRs(CCState &CCInfo,
960 const SIRegisterInfo &TRI,
961 SIMachineFunctionInfo &Info) {
962 if (Info.hasWorkItemIDX()) {
963 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
964 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
965 CCInfo.AllocateReg(Reg);
968 if (Info.hasWorkItemIDY()) {
969 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
970 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
971 CCInfo.AllocateReg(Reg);
974 if (Info.hasWorkItemIDZ()) {
975 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
976 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
977 CCInfo.AllocateReg(Reg);
981 // Allocate special inputs passed in user SGPRs.
982 static void allocateHSAUserSGPRs(CCState &CCInfo,
984 const SIRegisterInfo &TRI,
985 SIMachineFunctionInfo &Info) {
986 if (Info.hasPrivateMemoryInputPtr()) {
987 unsigned PrivateMemoryPtrReg = Info.addPrivateMemoryPtr(TRI);
988 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SGPR_64RegClass);
989 CCInfo.AllocateReg(PrivateMemoryPtrReg);
992 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
993 if (Info.hasPrivateSegmentBuffer()) {
994 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
995 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
996 CCInfo.AllocateReg(PrivateSegmentBufferReg);
999 if (Info.hasDispatchPtr()) {
1000 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1001 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1002 CCInfo.AllocateReg(DispatchPtrReg);
1005 if (Info.hasQueuePtr()) {
1006 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1007 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1008 CCInfo.AllocateReg(QueuePtrReg);
1011 if (Info.hasKernargSegmentPtr()) {
1012 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1013 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1014 CCInfo.AllocateReg(InputPtrReg);
1017 if (Info.hasDispatchID()) {
1018 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1019 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1020 CCInfo.AllocateReg(DispatchIDReg);
1023 if (Info.hasFlatScratchInit()) {
1024 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1025 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1026 CCInfo.AllocateReg(FlatScratchInitReg);
1029 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1030 // these from the dispatch pointer.
1033 // Allocate special input registers that are initialized per-wave.
1034 static void allocateSystemSGPRs(CCState &CCInfo,
1035 MachineFunction &MF,
1036 SIMachineFunctionInfo &Info,
1038 if (Info.hasWorkGroupIDX()) {
1039 unsigned Reg = Info.addWorkGroupIDX();
1040 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1041 CCInfo.AllocateReg(Reg);
1044 if (Info.hasWorkGroupIDY()) {
1045 unsigned Reg = Info.addWorkGroupIDY();
1046 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1047 CCInfo.AllocateReg(Reg);
1050 if (Info.hasWorkGroupIDZ()) {
1051 unsigned Reg = Info.addWorkGroupIDZ();
1052 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1053 CCInfo.AllocateReg(Reg);
1056 if (Info.hasWorkGroupInfo()) {
1057 unsigned Reg = Info.addWorkGroupInfo();
1058 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1059 CCInfo.AllocateReg(Reg);
1062 if (Info.hasPrivateSegmentWaveByteOffset()) {
1063 // Scratch wave offset passed in system SGPR.
1064 unsigned PrivateSegmentWaveByteOffsetReg;
1067 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1068 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1070 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1072 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1073 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1077 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1078 MachineFunction &MF,
1079 const SIRegisterInfo &TRI,
1080 SIMachineFunctionInfo &Info) {
1081 // Now that we've figured out where the scratch register inputs are, see if
1082 // should reserve the arguments and use them directly.
1083 bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1085 // Record that we know we have non-spill stack objects so we don't need to
1086 // check all stack objects later.
1087 if (HasStackObjects)
1088 Info.setHasNonSpillStackObjects(true);
1090 // Everything live out of a block is spilled with fast regalloc, so it's
1091 // almost certain that spilling will be required.
1092 if (TM.getOptLevel() == CodeGenOpt::None)
1093 HasStackObjects = true;
1095 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1096 if (ST.isAmdCodeObjectV2(MF)) {
1097 if (HasStackObjects) {
1098 // If we have stack objects, we unquestionably need the private buffer
1099 // resource. For the Code Object V2 ABI, this will be the first 4 user
1100 // SGPR inputs. We can reserve those and use them directly.
1102 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue(
1103 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1104 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1106 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue(
1107 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1108 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1110 unsigned ReservedBufferReg
1111 = TRI.reservedPrivateSegmentBufferReg(MF);
1112 unsigned ReservedOffsetReg
1113 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1115 // We tentatively reserve the last registers (skipping the last two
1116 // which may contain VCC). After register allocation, we'll replace
1117 // these with the ones immediately after those which were really
1118 // allocated. In the prologue copies will be inserted from the argument
1119 // to these reserved registers.
1120 Info.setScratchRSrcReg(ReservedBufferReg);
1121 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1124 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1126 // Without HSA, relocations are used for the scratch pointer and the
1127 // buffer resource setup is always inserted in the prologue. Scratch wave
1128 // offset is still in an input SGPR.
1129 Info.setScratchRSrcReg(ReservedBufferReg);
1131 if (HasStackObjects) {
1132 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue(
1133 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1134 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1136 unsigned ReservedOffsetReg
1137 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1138 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1143 SDValue SITargetLowering::LowerFormalArguments(
1144 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1145 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1146 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1147 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1149 MachineFunction &MF = DAG.getMachineFunction();
1150 FunctionType *FType = MF.getFunction()->getFunctionType();
1151 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1152 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1154 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1155 const Function *Fn = MF.getFunction();
1156 DiagnosticInfoUnsupported NoGraphicsHSA(
1157 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1158 DAG.getContext()->diagnose(NoGraphicsHSA);
1159 return DAG.getEntryNode();
1162 // Create stack objects that are used for emitting debugger prologue if
1163 // "amdgpu-debugger-emit-prologue" attribute was specified.
1164 if (ST.debuggerEmitPrologue())
1165 createDebuggerPrologueStackObjects(MF);
1167 SmallVector<ISD::InputArg, 16> Splits;
1168 SmallVector<CCValAssign, 16> ArgLocs;
1169 BitVector Skipped(Ins.size());
1170 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1173 bool IsShader = AMDGPU::isShader(CallConv);
1174 bool IsKernel = AMDGPU::isKernel(CallConv);
1175 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1178 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1180 // At least one interpolation mode must be enabled or else the GPU will
1183 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1184 // set PSInputAddr, the user wants to enable some bits after the compilation
1185 // based on run-time states. Since we can't know what the final PSInputEna
1186 // will look like, so we shouldn't do anything here and the user should take
1187 // responsibility for the correct programming.
1189 // Otherwise, the following restrictions apply:
1190 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1191 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1193 if (CallConv == CallingConv::AMDGPU_PS &&
1194 ((Info->getPSInputAddr() & 0x7F) == 0 ||
1195 ((Info->getPSInputAddr() & 0xF) == 0 &&
1196 Info->isPSInputAllocated(11)))) {
1197 CCInfo.AllocateReg(AMDGPU::VGPR0);
1198 CCInfo.AllocateReg(AMDGPU::VGPR1);
1199 Info->markPSInputAllocated(0);
1200 Info->markPSInputEnabled(0);
1203 assert(!Info->hasDispatchPtr() &&
1204 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1205 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1206 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1207 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1208 !Info->hasWorkItemIDZ());
1210 assert(!IsKernel || (Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()));
1214 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1215 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1219 analyzeFormalArgumentsCompute(CCInfo, Ins);
1221 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1222 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1225 SmallVector<SDValue, 16> Chains;
1227 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1228 const ISD::InputArg &Arg = Ins[i];
1230 InVals.push_back(DAG.getUNDEF(Arg.VT));
1234 CCValAssign &VA = ArgLocs[ArgIdx++];
1235 MVT VT = VA.getLocVT();
1237 if (IsEntryFunc && VA.isMemLoc()) {
1239 EVT MemVT = VA.getLocVT();
1241 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1242 VA.getLocMemOffset();
1243 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1245 // The first 36 bytes of the input buffer contains information about
1246 // thread group and global sizes.
1247 SDValue Arg = lowerKernargMemParameter(
1248 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1249 Chains.push_back(Arg.getValue(1));
1252 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1253 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1254 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1255 // On SI local pointers are just offsets into LDS, so they are always
1256 // less than 16-bits. On CI and newer they could potentially be
1257 // real pointers, so we can't guarantee their size.
1258 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1259 DAG.getValueType(MVT::i16));
1262 InVals.push_back(Arg);
1267 report_fatal_error("memloc not supported with calling convention");
1269 assert(VA.isRegLoc() && "Parameter must be in a register!");
1271 unsigned Reg = VA.getLocReg();
1272 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1274 Reg = MF.addLiveIn(Reg, RC);
1275 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1277 if (Arg.VT.isVector()) {
1278 // Build a vector from the registers
1279 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1280 unsigned NumElements = ParamType->getVectorNumElements();
1282 SmallVector<SDValue, 4> Regs;
1283 Regs.push_back(Val);
1284 for (unsigned j = 1; j != NumElements; ++j) {
1285 Reg = ArgLocs[ArgIdx++].getLocReg();
1286 Reg = MF.addLiveIn(Reg, RC);
1288 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1289 Regs.push_back(Copy);
1292 // Fill up the missing vector elements
1293 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1294 Regs.append(NumElements, DAG.getUNDEF(VT));
1296 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1300 InVals.push_back(Val);
1303 // Start adding system SGPRs.
1305 allocateSystemSGPRs(CCInfo, MF, *Info, IsShader);
1307 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
1309 return Chains.empty() ? Chain :
1310 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1314 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1316 const SmallVectorImpl<ISD::OutputArg> &Outs,
1317 const SmallVectorImpl<SDValue> &OutVals,
1318 const SDLoc &DL, SelectionDAG &DAG) const {
1319 MachineFunction &MF = DAG.getMachineFunction();
1320 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1322 if (!AMDGPU::isShader(CallConv))
1323 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1326 Info->setIfReturnsVoid(Outs.size() == 0);
1328 SmallVector<ISD::OutputArg, 48> Splits;
1329 SmallVector<SDValue, 48> SplitVals;
1331 // Split vectors into their elements.
1332 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1333 const ISD::OutputArg &Out = Outs[i];
1335 if (Out.VT.isVector()) {
1336 MVT VT = Out.VT.getVectorElementType();
1337 ISD::OutputArg NewOut = Out;
1338 NewOut.Flags.setSplit();
1341 // We want the original number of vector elements here, e.g.
1342 // three or five, not four or eight.
1343 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1345 for (unsigned j = 0; j != NumElements; ++j) {
1346 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1347 DAG.getConstant(j, DL, MVT::i32));
1348 SplitVals.push_back(Elem);
1349 Splits.push_back(NewOut);
1350 NewOut.PartOffset += NewOut.VT.getStoreSize();
1353 SplitVals.push_back(OutVals[i]);
1354 Splits.push_back(Out);
1358 // CCValAssign - represent the assignment of the return value to a location.
1359 SmallVector<CCValAssign, 48> RVLocs;
1361 // CCState - Info about the registers and stack slots.
1362 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1365 // Analyze outgoing return values.
1366 AnalyzeReturn(CCInfo, Splits);
1369 SmallVector<SDValue, 48> RetOps;
1370 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1372 // Copy the result values into the output registers.
1373 for (unsigned i = 0, realRVLocIdx = 0;
1375 ++i, ++realRVLocIdx) {
1376 CCValAssign &VA = RVLocs[i];
1377 assert(VA.isRegLoc() && "Can only return in registers!");
1379 SDValue Arg = SplitVals[realRVLocIdx];
1381 // Copied from other backends.
1382 switch (VA.getLocInfo()) {
1383 default: llvm_unreachable("Unknown loc info!");
1384 case CCValAssign::Full:
1386 case CCValAssign::BCvt:
1387 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1391 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1392 Flag = Chain.getValue(1);
1393 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1396 // Update chain and glue.
1399 RetOps.push_back(Flag);
1401 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN_TO_EPILOG;
1402 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1405 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1406 SelectionDAG &DAG) const {
1407 unsigned Reg = StringSwitch<unsigned>(RegName)
1408 .Case("m0", AMDGPU::M0)
1409 .Case("exec", AMDGPU::EXEC)
1410 .Case("exec_lo", AMDGPU::EXEC_LO)
1411 .Case("exec_hi", AMDGPU::EXEC_HI)
1412 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1413 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1414 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1415 .Default(AMDGPU::NoRegister);
1417 if (Reg == AMDGPU::NoRegister) {
1418 report_fatal_error(Twine("invalid register name \""
1419 + StringRef(RegName) + "\"."));
1423 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1424 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1425 report_fatal_error(Twine("invalid register \""
1426 + StringRef(RegName) + "\" for subtarget."));
1431 case AMDGPU::EXEC_LO:
1432 case AMDGPU::EXEC_HI:
1433 case AMDGPU::FLAT_SCR_LO:
1434 case AMDGPU::FLAT_SCR_HI:
1435 if (VT.getSizeInBits() == 32)
1439 case AMDGPU::FLAT_SCR:
1440 if (VT.getSizeInBits() == 64)
1444 llvm_unreachable("missing register type checking");
1447 report_fatal_error(Twine("invalid type for register \""
1448 + StringRef(RegName) + "\"."));
1451 // If kill is not the last instruction, split the block so kill is always a
1452 // proper terminator.
1453 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1454 MachineBasicBlock *BB) const {
1455 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1457 MachineBasicBlock::iterator SplitPoint(&MI);
1460 if (SplitPoint == BB->end()) {
1461 // Don't bother with a new block.
1462 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1466 MachineFunction *MF = BB->getParent();
1467 MachineBasicBlock *SplitBB
1468 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1470 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1471 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1473 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1474 BB->addSuccessor(SplitBB);
1476 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1480 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1481 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1482 // will only do one iteration. In the worst case, this will loop 64 times.
1484 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1485 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1486 const SIInstrInfo *TII,
1487 MachineRegisterInfo &MRI,
1488 MachineBasicBlock &OrigBB,
1489 MachineBasicBlock &LoopBB,
1491 const MachineOperand &IdxReg,
1495 unsigned InitSaveExecReg,
1497 bool UseGPRIdxMode) {
1498 MachineBasicBlock::iterator I = LoopBB.begin();
1500 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1501 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1502 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1503 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1505 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1511 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1512 .addReg(InitSaveExecReg)
1517 // Read the next variant <- also loop target.
1518 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1519 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1521 // Compare the just read M0 value to all possible Idx values.
1522 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1523 .addReg(CurrentIdxReg)
1524 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1526 if (UseGPRIdxMode) {
1529 IdxReg = CurrentIdxReg;
1531 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1532 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1533 .addReg(CurrentIdxReg, RegState::Kill)
1537 MachineInstr *SetIdx =
1538 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1539 .addReg(IdxReg, RegState::Kill);
1540 SetIdx->getOperand(2).setIsUndef();
1542 // Move index from VCC into M0
1544 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1545 .addReg(CurrentIdxReg, RegState::Kill);
1547 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1548 .addReg(CurrentIdxReg, RegState::Kill)
1553 // Update EXEC, save the original EXEC value to VCC.
1554 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1555 .addReg(CondReg, RegState::Kill);
1557 MRI.setSimpleHint(NewExec, CondReg);
1559 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1560 MachineInstr *InsertPt =
1561 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1562 .addReg(AMDGPU::EXEC)
1565 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1568 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1569 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1572 return InsertPt->getIterator();
1575 // This has slightly sub-optimal regalloc when the source vector is killed by
1576 // the read. The register allocator does not understand that the kill is
1577 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1578 // subregister from it, using 1 more VGPR than necessary. This was saved when
1579 // this was expanded after register allocation.
1580 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1581 MachineBasicBlock &MBB,
1583 unsigned InitResultReg,
1586 bool UseGPRIdxMode) {
1587 MachineFunction *MF = MBB.getParent();
1588 MachineRegisterInfo &MRI = MF->getRegInfo();
1589 const DebugLoc &DL = MI.getDebugLoc();
1590 MachineBasicBlock::iterator I(&MI);
1592 unsigned DstReg = MI.getOperand(0).getReg();
1593 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1594 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1596 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1598 // Save the EXEC mask
1599 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1600 .addReg(AMDGPU::EXEC);
1602 // To insert the loop we need to split the block. Move everything after this
1603 // point to a new block, and insert a new empty block between the two.
1604 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1605 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1606 MachineFunction::iterator MBBI(MBB);
1609 MF->insert(MBBI, LoopBB);
1610 MF->insert(MBBI, RemainderBB);
1612 LoopBB->addSuccessor(LoopBB);
1613 LoopBB->addSuccessor(RemainderBB);
1615 // Move the rest of the block into a new block.
1616 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1617 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1619 MBB.addSuccessor(LoopBB);
1621 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1623 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1624 InitResultReg, DstReg, PhiReg, TmpExec,
1625 Offset, UseGPRIdxMode);
1627 MachineBasicBlock::iterator First = RemainderBB->begin();
1628 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1634 // Returns subreg index, offset
1635 static std::pair<unsigned, int>
1636 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1637 const TargetRegisterClass *SuperRC,
1640 int NumElts = SuperRC->getSize() / 4;
1642 // Skip out of bounds offsets, or else we would end up using an undefined
1644 if (Offset >= NumElts || Offset < 0)
1645 return std::make_pair(AMDGPU::sub0, Offset);
1647 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1650 // Return true if the index is an SGPR and was set.
1651 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1652 MachineRegisterInfo &MRI,
1656 bool IsIndirectSrc) {
1657 MachineBasicBlock *MBB = MI.getParent();
1658 const DebugLoc &DL = MI.getDebugLoc();
1659 MachineBasicBlock::iterator I(&MI);
1661 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1662 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1664 assert(Idx->getReg() != AMDGPU::NoRegister);
1666 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1669 if (UseGPRIdxMode) {
1670 unsigned IdxMode = IsIndirectSrc ?
1671 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1673 MachineInstr *SetOn =
1674 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1678 SetOn->getOperand(3).setIsUndef();
1680 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1681 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1684 MachineInstr *SetOn =
1685 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1686 .addReg(Tmp, RegState::Kill)
1689 SetOn->getOperand(3).setIsUndef();
1696 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1699 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1707 // Control flow needs to be inserted if indexing with a VGPR.
1708 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1709 MachineBasicBlock &MBB,
1710 const SISubtarget &ST) {
1711 const SIInstrInfo *TII = ST.getInstrInfo();
1712 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1713 MachineFunction *MF = MBB.getParent();
1714 MachineRegisterInfo &MRI = MF->getRegInfo();
1716 unsigned Dst = MI.getOperand(0).getReg();
1717 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1718 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1720 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1723 std::tie(SubReg, Offset)
1724 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1726 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1728 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1729 MachineBasicBlock::iterator I(&MI);
1730 const DebugLoc &DL = MI.getDebugLoc();
1732 if (UseGPRIdxMode) {
1733 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1734 // to avoid interfering with other uses, so probably requires a new
1735 // optimization pass.
1736 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1737 .addReg(SrcReg, RegState::Undef, SubReg)
1738 .addReg(SrcReg, RegState::Implicit)
1739 .addReg(AMDGPU::M0, RegState::Implicit);
1740 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1742 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1743 .addReg(SrcReg, RegState::Undef, SubReg)
1744 .addReg(SrcReg, RegState::Implicit);
1747 MI.eraseFromParent();
1752 const DebugLoc &DL = MI.getDebugLoc();
1753 MachineBasicBlock::iterator I(&MI);
1755 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1756 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1758 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1760 if (UseGPRIdxMode) {
1761 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1762 .addImm(0) // Reset inside loop.
1763 .addImm(VGPRIndexMode::SRC0_ENABLE);
1764 SetOn->getOperand(3).setIsUndef();
1766 // Disable again after the loop.
1767 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1770 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1771 MachineBasicBlock *LoopBB = InsPt->getParent();
1773 if (UseGPRIdxMode) {
1774 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1775 .addReg(SrcReg, RegState::Undef, SubReg)
1776 .addReg(SrcReg, RegState::Implicit)
1777 .addReg(AMDGPU::M0, RegState::Implicit);
1779 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1780 .addReg(SrcReg, RegState::Undef, SubReg)
1781 .addReg(SrcReg, RegState::Implicit);
1784 MI.eraseFromParent();
1789 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1790 switch (VecRC->getSize()) {
1792 return AMDGPU::V_MOVRELD_B32_V1;
1794 return AMDGPU::V_MOVRELD_B32_V2;
1796 return AMDGPU::V_MOVRELD_B32_V4;
1798 return AMDGPU::V_MOVRELD_B32_V8;
1800 return AMDGPU::V_MOVRELD_B32_V16;
1802 llvm_unreachable("unsupported size for MOVRELD pseudos");
1806 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1807 MachineBasicBlock &MBB,
1808 const SISubtarget &ST) {
1809 const SIInstrInfo *TII = ST.getInstrInfo();
1810 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1811 MachineFunction *MF = MBB.getParent();
1812 MachineRegisterInfo &MRI = MF->getRegInfo();
1814 unsigned Dst = MI.getOperand(0).getReg();
1815 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1816 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1817 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1818 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1819 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1821 // This can be an immediate, but will be folded later.
1822 assert(Val->getReg());
1825 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1828 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1830 if (Idx->getReg() == AMDGPU::NoRegister) {
1831 MachineBasicBlock::iterator I(&MI);
1832 const DebugLoc &DL = MI.getDebugLoc();
1834 assert(Offset == 0);
1836 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1841 MI.eraseFromParent();
1845 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1846 MachineBasicBlock::iterator I(&MI);
1847 const DebugLoc &DL = MI.getDebugLoc();
1849 if (UseGPRIdxMode) {
1850 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1851 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1853 .addReg(Dst, RegState::ImplicitDefine)
1854 .addReg(SrcVec->getReg(), RegState::Implicit)
1855 .addReg(AMDGPU::M0, RegState::Implicit);
1857 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1859 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1861 BuildMI(MBB, I, DL, MovRelDesc)
1862 .addReg(Dst, RegState::Define)
1863 .addReg(SrcVec->getReg())
1865 .addImm(SubReg - AMDGPU::sub0);
1868 MI.eraseFromParent();
1873 MRI.clearKillFlags(Val->getReg());
1875 const DebugLoc &DL = MI.getDebugLoc();
1877 if (UseGPRIdxMode) {
1878 MachineBasicBlock::iterator I(&MI);
1880 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1881 .addImm(0) // Reset inside loop.
1882 .addImm(VGPRIndexMode::DST_ENABLE);
1883 SetOn->getOperand(3).setIsUndef();
1885 // Disable again after the loop.
1886 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1889 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1891 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1892 Offset, UseGPRIdxMode);
1893 MachineBasicBlock *LoopBB = InsPt->getParent();
1895 if (UseGPRIdxMode) {
1896 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1897 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1899 .addReg(Dst, RegState::ImplicitDefine)
1900 .addReg(PhiReg, RegState::Implicit)
1901 .addReg(AMDGPU::M0, RegState::Implicit);
1903 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1905 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1906 .addReg(Dst, RegState::Define)
1909 .addImm(SubReg - AMDGPU::sub0);
1912 MI.eraseFromParent();
1917 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1918 MachineInstr &MI, MachineBasicBlock *BB) const {
1920 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1921 MachineFunction *MF = BB->getParent();
1922 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1924 if (TII->isMIMG(MI)) {
1925 if (!MI.memoperands_empty())
1927 // Add a memoperand for mimg instructions so that they aren't assumed to
1928 // be ordered memory instuctions.
1930 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1931 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1933 Flags |= MachineMemOperand::MOStore;
1936 Flags |= MachineMemOperand::MOLoad;
1938 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1939 MI.addMemOperand(*MF, MMO);
1943 switch (MI.getOpcode()) {
1944 case AMDGPU::S_TRAP_PSEUDO: {
1945 const DebugLoc &DL = MI.getDebugLoc();
1946 const int TrapType = MI.getOperand(0).getImm();
1948 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
1949 Subtarget->isTrapHandlerEnabled()) {
1951 MachineFunction *MF = BB->getParent();
1952 SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1953 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
1954 assert(UserSGPR != AMDGPU::NoRegister);
1956 if (!BB->isLiveIn(UserSGPR))
1957 BB->addLiveIn(UserSGPR);
1959 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), AMDGPU::SGPR0_SGPR1)
1961 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_TRAP))
1963 .addReg(AMDGPU::SGPR0_SGPR1, RegState::Implicit);
1966 case SISubtarget::TrapIDLLVMTrap:
1967 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_ENDPGM));
1969 case SISubtarget::TrapIDLLVMDebugTrap: {
1970 DiagnosticInfoUnsupported NoTrap(*MF->getFunction(),
1971 "debugtrap handler not supported",
1974 LLVMContext &C = MF->getFunction()->getContext();
1976 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_NOP))
1981 llvm_unreachable("unsupported trap handler type!");
1985 MI.eraseFromParent();
1988 case AMDGPU::SI_INIT_M0:
1989 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1990 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1991 .add(MI.getOperand(0));
1992 MI.eraseFromParent();
1995 case AMDGPU::GET_GROUPSTATICSIZE: {
1996 DebugLoc DL = MI.getDebugLoc();
1997 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1998 .add(MI.getOperand(0))
1999 .addImm(MFI->getLDSSize());
2000 MI.eraseFromParent();
2003 case AMDGPU::SI_INDIRECT_SRC_V1:
2004 case AMDGPU::SI_INDIRECT_SRC_V2:
2005 case AMDGPU::SI_INDIRECT_SRC_V4:
2006 case AMDGPU::SI_INDIRECT_SRC_V8:
2007 case AMDGPU::SI_INDIRECT_SRC_V16:
2008 return emitIndirectSrc(MI, *BB, *getSubtarget());
2009 case AMDGPU::SI_INDIRECT_DST_V1:
2010 case AMDGPU::SI_INDIRECT_DST_V2:
2011 case AMDGPU::SI_INDIRECT_DST_V4:
2012 case AMDGPU::SI_INDIRECT_DST_V8:
2013 case AMDGPU::SI_INDIRECT_DST_V16:
2014 return emitIndirectDst(MI, *BB, *getSubtarget());
2015 case AMDGPU::SI_KILL:
2016 return splitKillBlock(MI, BB);
2017 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
2018 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2020 unsigned Dst = MI.getOperand(0).getReg();
2021 unsigned Src0 = MI.getOperand(1).getReg();
2022 unsigned Src1 = MI.getOperand(2).getReg();
2023 const DebugLoc &DL = MI.getDebugLoc();
2024 unsigned SrcCond = MI.getOperand(3).getReg();
2026 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2027 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2029 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
2030 .addReg(Src0, 0, AMDGPU::sub0)
2031 .addReg(Src1, 0, AMDGPU::sub0)
2033 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
2034 .addReg(Src0, 0, AMDGPU::sub1)
2035 .addReg(Src1, 0, AMDGPU::sub1)
2038 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2040 .addImm(AMDGPU::sub0)
2042 .addImm(AMDGPU::sub1);
2043 MI.eraseFromParent();
2046 case AMDGPU::SI_BR_UNDEF: {
2047 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2048 const DebugLoc &DL = MI.getDebugLoc();
2049 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2050 .add(MI.getOperand(0));
2051 Br->getOperand(1).setIsUndef(true); // read undef SCC
2052 MI.eraseFromParent();
2056 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2060 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2061 // This currently forces unfolding various combinations of fsub into fma with
2062 // free fneg'd operands. As long as we have fast FMA (controlled by
2063 // isFMAFasterThanFMulAndFAdd), we should perform these.
2065 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2066 // most of these combines appear to be cycle neutral but save on instruction
2067 // count / code size.
2071 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2073 if (!VT.isVector()) {
2076 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2079 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2080 // TODO: Should i16 be used always if legal? For now it would force VALU
2082 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2085 // Answering this is somewhat tricky and depends on the specific device which
2086 // have different rates for fma or all f64 operations.
2088 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2089 // regardless of which device (although the number of cycles differs between
2090 // devices), so it is always profitable for f64.
2092 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2093 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2094 // which we can always do even without fused FP ops since it returns the same
2095 // result as the separate operations and since it is always full
2096 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2097 // however does not support denormals, so we do report fma as faster if we have
2098 // a fast fma device and require denormals.
2100 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2101 VT = VT.getScalarType();
2103 switch (VT.getSimpleVT().SimpleTy) {
2105 // This is as fast on some subtargets. However, we always have full rate f32
2106 // mad available which returns the same result as the separate operations
2107 // which we should prefer over fma. We can't use this if we want to support
2108 // denormals, so only report this in these cases.
2109 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2113 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2121 //===----------------------------------------------------------------------===//
2122 // Custom DAG Lowering Operations
2123 //===----------------------------------------------------------------------===//
2125 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2126 switch (Op.getOpcode()) {
2127 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2128 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2130 SDValue Result = LowerLOAD(Op, DAG);
2131 assert((!Result.getNode() ||
2132 Result.getNode()->getNumValues() == 2) &&
2133 "Load should return a value and a chain");
2139 return LowerTrig(Op, DAG);
2140 case ISD::SELECT: return LowerSELECT(Op, DAG);
2141 case ISD::FDIV: return LowerFDIV(Op, DAG);
2142 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2143 case ISD::STORE: return LowerSTORE(Op, DAG);
2144 case ISD::GlobalAddress: {
2145 MachineFunction &MF = DAG.getMachineFunction();
2146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2147 return LowerGlobalAddress(MFI, Op, DAG);
2149 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2150 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2151 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2152 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2153 case ISD::INSERT_VECTOR_ELT:
2154 return lowerINSERT_VECTOR_ELT(Op, DAG);
2155 case ISD::EXTRACT_VECTOR_ELT:
2156 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2158 return lowerFP_ROUND(Op, DAG);
2163 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2164 SmallVectorImpl<SDValue> &Results,
2165 SelectionDAG &DAG) const {
2166 switch (N->getOpcode()) {
2167 case ISD::INSERT_VECTOR_ELT: {
2168 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2169 Results.push_back(Res);
2172 case ISD::EXTRACT_VECTOR_ELT: {
2173 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2174 Results.push_back(Res);
2177 case ISD::INTRINSIC_WO_CHAIN: {
2178 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2180 case Intrinsic::amdgcn_cvt_pkrtz: {
2181 SDValue Src0 = N->getOperand(1);
2182 SDValue Src1 = N->getOperand(2);
2184 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2187 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2199 /// \brief Helper function for LowerBRCOND
2200 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2202 SDNode *Parent = Value.getNode();
2203 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2206 if (I.getUse().get() != Value)
2209 if (I->getOpcode() == Opcode)
2215 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2216 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2217 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2218 case Intrinsic::amdgcn_if:
2219 return AMDGPUISD::IF;
2220 case Intrinsic::amdgcn_else:
2221 return AMDGPUISD::ELSE;
2222 case Intrinsic::amdgcn_loop:
2223 return AMDGPUISD::LOOP;
2224 case Intrinsic::amdgcn_end_cf:
2225 llvm_unreachable("should not occur");
2231 // break, if_break, else_break are all only used as inputs to loop, not
2232 // directly as branch conditions.
2236 void SITargetLowering::createDebuggerPrologueStackObjects(
2237 MachineFunction &MF) const {
2238 // Create stack objects that are used for emitting debugger prologue.
2240 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2241 // at fixed location in the following format:
2242 // offset 0: work group ID x
2243 // offset 4: work group ID y
2244 // offset 8: work group ID z
2245 // offset 16: work item ID x
2246 // offset 20: work item ID y
2247 // offset 24: work item ID z
2248 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2251 // For each dimension:
2252 for (unsigned i = 0; i < 3; ++i) {
2253 // Create fixed stack object for work group ID.
2254 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2255 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2256 // Create fixed stack object for work item ID.
2257 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2258 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2262 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2263 const Triple &TT = getTargetMachine().getTargetTriple();
2264 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2265 AMDGPU::shouldEmitConstantsToTextSection(TT);
2268 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2269 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2270 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2271 !shouldEmitFixup(GV) &&
2272 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2275 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2276 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2279 /// This transforms the control flow intrinsics to get the branch destination as
2280 /// last parameter, also switches branch target with BR if the need arise
2281 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2282 SelectionDAG &DAG) const {
2285 SDNode *Intr = BRCOND.getOperand(1).getNode();
2286 SDValue Target = BRCOND.getOperand(2);
2287 SDNode *BR = nullptr;
2288 SDNode *SetCC = nullptr;
2290 if (Intr->getOpcode() == ISD::SETCC) {
2291 // As long as we negate the condition everything is fine
2293 Intr = SetCC->getOperand(0).getNode();
2296 // Get the target from BR if we don't negate the condition
2297 BR = findUser(BRCOND, ISD::BR);
2298 Target = BR->getOperand(1);
2301 // FIXME: This changes the types of the intrinsics instead of introducing new
2302 // nodes with the correct types.
2303 // e.g. llvm.amdgcn.loop
2305 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2306 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2308 unsigned CFNode = isCFIntrinsic(Intr);
2310 // This is a uniform branch so we don't need to legalize.
2314 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2315 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2318 (SetCC->getConstantOperandVal(1) == 1 &&
2319 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2322 // operands of the new intrinsic call
2323 SmallVector<SDValue, 4> Ops;
2325 Ops.push_back(BRCOND.getOperand(0));
2327 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2328 Ops.push_back(Target);
2330 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2332 // build the new intrinsic call
2333 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2338 BRCOND.getOperand(0)
2341 Result = DAG.getMergeValues(Ops, DL).getNode();
2345 // Give the branch instruction our target
2348 BRCOND.getOperand(2)
2350 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2351 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2352 BR = NewBR.getNode();
2355 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2357 // Copy the intrinsic results to registers
2358 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2359 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2363 Chain = DAG.getCopyToReg(
2365 CopyToReg->getOperand(1),
2366 SDValue(Result, i - 1),
2369 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2372 // Remove the old intrinsic from the chain
2373 DAG.ReplaceAllUsesOfValueWith(
2374 SDValue(Intr, Intr->getNumValues() - 1),
2375 Intr->getOperand(0));
2380 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2384 return Op.getValueType().bitsLE(VT) ?
2385 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2386 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2389 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2390 assert(Op.getValueType() == MVT::f16 &&
2391 "Do not know how to custom lower FP_ROUND for non-f16 type");
2393 SDValue Src = Op.getOperand(0);
2394 EVT SrcVT = Src.getValueType();
2395 if (SrcVT != MVT::f64)
2400 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2401 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2402 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2405 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2406 SelectionDAG &DAG) const {
2407 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2408 if (Subtarget->hasApertureRegs()) {
2409 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2410 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2411 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2412 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2413 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2414 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2416 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2417 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2418 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2420 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2421 SDValue ApertureReg = SDValue(
2422 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2423 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2424 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2427 MachineFunction &MF = DAG.getMachineFunction();
2428 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2429 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2430 assert(UserSGPR != AMDGPU::NoRegister);
2432 SDValue QueuePtr = CreateLiveInRegister(
2433 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2435 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2436 // private_segment_aperture_base_hi.
2437 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2439 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2440 DAG.getConstant(StructOffset, DL, MVT::i64));
2442 // TODO: Use custom target PseudoSourceValue.
2443 // TODO: We should use the value from the IR intrinsic call, but it might not
2444 // be available and how do we get it?
2445 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2446 AMDGPUASI.CONSTANT_ADDRESS));
2448 MachinePointerInfo PtrInfo(V, StructOffset);
2449 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2450 MinAlign(64, StructOffset),
2451 MachineMemOperand::MODereferenceable |
2452 MachineMemOperand::MOInvariant);
2455 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2456 SelectionDAG &DAG) const {
2458 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2460 SDValue Src = ASC->getOperand(0);
2461 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2463 const AMDGPUTargetMachine &TM =
2464 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2466 // flat -> local/private
2467 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2468 unsigned DestAS = ASC->getDestAddressSpace();
2470 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2471 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2472 unsigned NullVal = TM.getNullPointerValue(DestAS);
2473 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2474 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2475 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2477 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2478 NonNull, Ptr, SegmentNullPtr);
2482 // local/private -> flat
2483 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2484 unsigned SrcAS = ASC->getSrcAddressSpace();
2486 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2487 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2488 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2489 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2492 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2494 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2496 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2498 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2499 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2504 // global <-> flat are no-ops and never emitted.
2506 const MachineFunction &MF = DAG.getMachineFunction();
2507 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2508 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2509 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2511 return DAG.getUNDEF(ASC->getValueType(0));
2514 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2515 SelectionDAG &DAG) const {
2516 SDValue Idx = Op.getOperand(2);
2517 if (isa<ConstantSDNode>(Idx))
2520 // Avoid stack access for dynamic indexing.
2522 SDValue Vec = Op.getOperand(0);
2523 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2525 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2526 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2528 // Convert vector index to bit-index.
2529 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2530 DAG.getConstant(16, SL, MVT::i32));
2532 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2534 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2535 DAG.getConstant(0xffff, SL, MVT::i32),
2538 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2539 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2540 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2542 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2543 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2546 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2547 SelectionDAG &DAG) const {
2550 EVT ResultVT = Op.getValueType();
2551 SDValue Vec = Op.getOperand(0);
2552 SDValue Idx = Op.getOperand(1);
2554 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2555 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2557 if (CIdx->getZExtValue() == 1) {
2558 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2559 DAG.getConstant(16, SL, MVT::i32));
2561 assert(CIdx->getZExtValue() == 0);
2564 if (ResultVT.bitsLT(MVT::i32))
2565 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2566 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2569 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2571 // Convert vector index to bit-index.
2572 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2574 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2575 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2577 SDValue Result = Elt;
2578 if (ResultVT.bitsLT(MVT::i32))
2579 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2581 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2585 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2586 // We can fold offsets for anything that doesn't require a GOT relocation.
2587 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2588 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2589 !shouldEmitGOTReloc(GA->getGlobal());
2593 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2594 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2595 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2596 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2597 // lowered to the following code sequence:
2599 // For constant address space:
2600 // s_getpc_b64 s[0:1]
2601 // s_add_u32 s0, s0, $symbol
2602 // s_addc_u32 s1, s1, 0
2604 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2605 // a fixup or relocation is emitted to replace $symbol with a literal
2606 // constant, which is a pc-relative offset from the encoding of the $symbol
2607 // operand to the global variable.
2609 // For global address space:
2610 // s_getpc_b64 s[0:1]
2611 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2612 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2614 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2615 // fixups or relocations are emitted to replace $symbol@*@lo and
2616 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2617 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2618 // operand to the global variable.
2620 // What we want here is an offset from the value returned by s_getpc
2621 // (which is the address of the s_add_u32 instruction) to the global
2622 // variable, but since the encoding of $symbol starts 4 bytes after the start
2623 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2624 // small. This requires us to add 4 to the global variable offset in order to
2625 // compute the correct address.
2626 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2628 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2629 GAFlags == SIInstrInfo::MO_NONE ?
2630 GAFlags : GAFlags + 1);
2631 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2634 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2636 SelectionDAG &DAG) const {
2637 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2639 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2640 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2641 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2644 const GlobalValue *GV = GSD->getGlobal();
2645 EVT PtrVT = Op.getValueType();
2647 if (shouldEmitFixup(GV))
2648 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2649 else if (shouldEmitPCReloc(GV))
2650 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2651 SIInstrInfo::MO_REL32);
2653 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2654 SIInstrInfo::MO_GOTPCREL32);
2656 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2657 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2658 const DataLayout &DataLayout = DAG.getDataLayout();
2659 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2660 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2661 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2663 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2664 MachineMemOperand::MODereferenceable |
2665 MachineMemOperand::MOInvariant);
2668 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2669 const SDLoc &DL, SDValue V) const {
2670 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2671 // the destination register.
2673 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2674 // so we will end up with redundant moves to m0.
2676 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2678 // A Null SDValue creates a glue result.
2679 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2681 return SDValue(M0, 0);
2684 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2687 unsigned Offset) const {
2689 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2690 DAG.getEntryNode(), Offset, false);
2691 // The local size values will have the hi 16-bits as zero.
2692 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2693 DAG.getValueType(VT));
2696 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2698 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2699 "non-hsa intrinsic with hsa target",
2701 DAG.getContext()->diagnose(BadIntrin);
2702 return DAG.getUNDEF(VT);
2705 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2707 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2708 "intrinsic not supported on subtarget",
2710 DAG.getContext()->diagnose(BadIntrin);
2711 return DAG.getUNDEF(VT);
2714 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2715 SelectionDAG &DAG) const {
2716 MachineFunction &MF = DAG.getMachineFunction();
2717 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2718 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2720 EVT VT = Op.getValueType();
2722 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2724 // TODO: Should this propagate fast-math-flags?
2726 switch (IntrinsicID) {
2727 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2728 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2729 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2731 case Intrinsic::amdgcn_dispatch_ptr:
2732 case Intrinsic::amdgcn_queue_ptr: {
2733 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2734 DiagnosticInfoUnsupported BadIntrin(
2735 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2737 DAG.getContext()->diagnose(BadIntrin);
2738 return DAG.getUNDEF(VT);
2741 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2742 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2743 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2744 TRI->getPreloadedValue(MF, Reg), VT);
2746 case Intrinsic::amdgcn_implicitarg_ptr: {
2747 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2748 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2750 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2752 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2753 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2755 case Intrinsic::amdgcn_dispatch_id: {
2756 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2757 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2759 case Intrinsic::amdgcn_rcp:
2760 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2761 case Intrinsic::amdgcn_rsq:
2762 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2763 case Intrinsic::amdgcn_rsq_legacy:
2764 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2765 return emitRemovedIntrinsicError(DAG, DL, VT);
2767 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2768 case Intrinsic::amdgcn_rcp_legacy:
2769 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2770 return emitRemovedIntrinsicError(DAG, DL, VT);
2771 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2772 case Intrinsic::amdgcn_rsq_clamp: {
2773 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2774 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2776 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2777 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2778 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2780 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2781 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2782 DAG.getConstantFP(Max, DL, VT));
2783 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2784 DAG.getConstantFP(Min, DL, VT));
2786 case Intrinsic::r600_read_ngroups_x:
2787 if (Subtarget->isAmdHsaOS())
2788 return emitNonHSAIntrinsicError(DAG, DL, VT);
2790 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2791 SI::KernelInputOffsets::NGROUPS_X, false);
2792 case Intrinsic::r600_read_ngroups_y:
2793 if (Subtarget->isAmdHsaOS())
2794 return emitNonHSAIntrinsicError(DAG, DL, VT);
2796 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2797 SI::KernelInputOffsets::NGROUPS_Y, false);
2798 case Intrinsic::r600_read_ngroups_z:
2799 if (Subtarget->isAmdHsaOS())
2800 return emitNonHSAIntrinsicError(DAG, DL, VT);
2802 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2803 SI::KernelInputOffsets::NGROUPS_Z, false);
2804 case Intrinsic::r600_read_global_size_x:
2805 if (Subtarget->isAmdHsaOS())
2806 return emitNonHSAIntrinsicError(DAG, DL, VT);
2808 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2809 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2810 case Intrinsic::r600_read_global_size_y:
2811 if (Subtarget->isAmdHsaOS())
2812 return emitNonHSAIntrinsicError(DAG, DL, VT);
2814 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2815 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2816 case Intrinsic::r600_read_global_size_z:
2817 if (Subtarget->isAmdHsaOS())
2818 return emitNonHSAIntrinsicError(DAG, DL, VT);
2820 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2821 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2822 case Intrinsic::r600_read_local_size_x:
2823 if (Subtarget->isAmdHsaOS())
2824 return emitNonHSAIntrinsicError(DAG, DL, VT);
2826 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2827 SI::KernelInputOffsets::LOCAL_SIZE_X);
2828 case Intrinsic::r600_read_local_size_y:
2829 if (Subtarget->isAmdHsaOS())
2830 return emitNonHSAIntrinsicError(DAG, DL, VT);
2832 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2833 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2834 case Intrinsic::r600_read_local_size_z:
2835 if (Subtarget->isAmdHsaOS())
2836 return emitNonHSAIntrinsicError(DAG, DL, VT);
2838 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2839 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2840 case Intrinsic::amdgcn_workgroup_id_x:
2841 case Intrinsic::r600_read_tgid_x:
2842 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2843 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2844 case Intrinsic::amdgcn_workgroup_id_y:
2845 case Intrinsic::r600_read_tgid_y:
2846 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2847 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2848 case Intrinsic::amdgcn_workgroup_id_z:
2849 case Intrinsic::r600_read_tgid_z:
2850 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2851 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2852 case Intrinsic::amdgcn_workitem_id_x:
2853 case Intrinsic::r600_read_tidig_x:
2854 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2855 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2856 case Intrinsic::amdgcn_workitem_id_y:
2857 case Intrinsic::r600_read_tidig_y:
2858 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2859 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2860 case Intrinsic::amdgcn_workitem_id_z:
2861 case Intrinsic::r600_read_tidig_z:
2862 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2863 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2864 case AMDGPUIntrinsic::SI_load_const: {
2870 MachineMemOperand *MMO = MF.getMachineMemOperand(
2871 MachinePointerInfo(),
2872 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2873 MachineMemOperand::MOInvariant,
2874 VT.getStoreSize(), 4);
2875 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2876 Op->getVTList(), Ops, VT, MMO);
2878 case Intrinsic::amdgcn_fdiv_fast:
2879 return lowerFDIV_FAST(Op, DAG);
2880 case Intrinsic::amdgcn_interp_mov: {
2881 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2882 SDValue Glue = M0.getValue(1);
2883 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2884 Op.getOperand(2), Op.getOperand(3), Glue);
2886 case Intrinsic::amdgcn_interp_p1: {
2887 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2888 SDValue Glue = M0.getValue(1);
2889 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2890 Op.getOperand(2), Op.getOperand(3), Glue);
2892 case Intrinsic::amdgcn_interp_p2: {
2893 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2894 SDValue Glue = SDValue(M0.getNode(), 1);
2895 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2896 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2899 case Intrinsic::amdgcn_sin:
2900 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2902 case Intrinsic::amdgcn_cos:
2903 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2905 case Intrinsic::amdgcn_log_clamp: {
2906 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2909 DiagnosticInfoUnsupported BadIntrin(
2910 *MF.getFunction(), "intrinsic not supported on subtarget",
2912 DAG.getContext()->diagnose(BadIntrin);
2913 return DAG.getUNDEF(VT);
2915 case Intrinsic::amdgcn_ldexp:
2916 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2917 Op.getOperand(1), Op.getOperand(2));
2919 case Intrinsic::amdgcn_fract:
2920 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2922 case Intrinsic::amdgcn_class:
2923 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2924 Op.getOperand(1), Op.getOperand(2));
2925 case Intrinsic::amdgcn_div_fmas:
2926 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2927 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2930 case Intrinsic::amdgcn_div_fixup:
2931 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2932 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2934 case Intrinsic::amdgcn_trig_preop:
2935 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2936 Op.getOperand(1), Op.getOperand(2));
2937 case Intrinsic::amdgcn_div_scale: {
2938 // 3rd parameter required to be a constant.
2939 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2941 return DAG.getUNDEF(VT);
2943 // Translate to the operands expected by the machine instruction. The
2944 // first parameter must be the same as the first instruction.
2945 SDValue Numerator = Op.getOperand(1);
2946 SDValue Denominator = Op.getOperand(2);
2948 // Note this order is opposite of the machine instruction's operations,
2949 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2950 // intrinsic has the numerator as the first operand to match a normal
2951 // division operation.
2953 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2955 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2956 Denominator, Numerator);
2958 case Intrinsic::amdgcn_icmp: {
2959 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2961 return DAG.getUNDEF(VT);
2963 int CondCode = CD->getSExtValue();
2964 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2965 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
2966 return DAG.getUNDEF(VT);
2968 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2969 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2970 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2971 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2973 case Intrinsic::amdgcn_fcmp: {
2974 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2976 return DAG.getUNDEF(VT);
2978 int CondCode = CD->getSExtValue();
2979 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
2980 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
2981 return DAG.getUNDEF(VT);
2983 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2984 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2985 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2986 Op.getOperand(2), DAG.getCondCode(CCOpcode));
2988 case Intrinsic::amdgcn_fmed3:
2989 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
2990 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2991 case Intrinsic::amdgcn_fmul_legacy:
2992 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2993 Op.getOperand(1), Op.getOperand(2));
2994 case Intrinsic::amdgcn_sffbh:
2995 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2996 case Intrinsic::amdgcn_sbfe:
2997 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
2998 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2999 case Intrinsic::amdgcn_ubfe:
3000 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3001 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3002 case Intrinsic::amdgcn_cvt_pkrtz: {
3003 // FIXME: Stop adding cast if v2f16 legal.
3004 EVT VT = Op.getValueType();
3005 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3006 Op.getOperand(1), Op.getOperand(2));
3007 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3014 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3015 SelectionDAG &DAG) const {
3016 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3019 case Intrinsic::amdgcn_atomic_inc:
3020 case Intrinsic::amdgcn_atomic_dec: {
3021 MemSDNode *M = cast<MemSDNode>(Op);
3022 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3023 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3025 M->getOperand(0), // Chain
3026 M->getOperand(2), // Ptr
3027 M->getOperand(3) // Value
3030 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3031 M->getMemoryVT(), M->getMemOperand());
3033 case Intrinsic::amdgcn_buffer_load:
3034 case Intrinsic::amdgcn_buffer_load_format: {
3036 Op.getOperand(0), // Chain
3037 Op.getOperand(2), // rsrc
3038 Op.getOperand(3), // vindex
3039 Op.getOperand(4), // offset
3040 Op.getOperand(5), // glc
3041 Op.getOperand(6) // slc
3043 MachineFunction &MF = DAG.getMachineFunction();
3044 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3046 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3047 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3048 EVT VT = Op.getValueType();
3049 EVT IntVT = VT.changeTypeToInteger();
3051 MachineMemOperand *MMO = MF.getMachineMemOperand(
3052 MachinePointerInfo(MFI->getBufferPSV()),
3053 MachineMemOperand::MOLoad,
3054 VT.getStoreSize(), VT.getStoreSize());
3056 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3059 case Intrinsic::amdgcn_image_sample:
3060 case Intrinsic::amdgcn_image_sample_cl:
3061 case Intrinsic::amdgcn_image_sample_d:
3062 case Intrinsic::amdgcn_image_sample_d_cl:
3063 case Intrinsic::amdgcn_image_sample_l:
3064 case Intrinsic::amdgcn_image_sample_b:
3065 case Intrinsic::amdgcn_image_sample_b_cl:
3066 case Intrinsic::amdgcn_image_sample_lz:
3067 case Intrinsic::amdgcn_image_sample_cd:
3068 case Intrinsic::amdgcn_image_sample_cd_cl:
3070 // Sample with comparison.
3071 case Intrinsic::amdgcn_image_sample_c:
3072 case Intrinsic::amdgcn_image_sample_c_cl:
3073 case Intrinsic::amdgcn_image_sample_c_d:
3074 case Intrinsic::amdgcn_image_sample_c_d_cl:
3075 case Intrinsic::amdgcn_image_sample_c_l:
3076 case Intrinsic::amdgcn_image_sample_c_b:
3077 case Intrinsic::amdgcn_image_sample_c_b_cl:
3078 case Intrinsic::amdgcn_image_sample_c_lz:
3079 case Intrinsic::amdgcn_image_sample_c_cd:
3080 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3082 // Sample with offsets.
3083 case Intrinsic::amdgcn_image_sample_o:
3084 case Intrinsic::amdgcn_image_sample_cl_o:
3085 case Intrinsic::amdgcn_image_sample_d_o:
3086 case Intrinsic::amdgcn_image_sample_d_cl_o:
3087 case Intrinsic::amdgcn_image_sample_l_o:
3088 case Intrinsic::amdgcn_image_sample_b_o:
3089 case Intrinsic::amdgcn_image_sample_b_cl_o:
3090 case Intrinsic::amdgcn_image_sample_lz_o:
3091 case Intrinsic::amdgcn_image_sample_cd_o:
3092 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3094 // Sample with comparison and offsets.
3095 case Intrinsic::amdgcn_image_sample_c_o:
3096 case Intrinsic::amdgcn_image_sample_c_cl_o:
3097 case Intrinsic::amdgcn_image_sample_c_d_o:
3098 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3099 case Intrinsic::amdgcn_image_sample_c_l_o:
3100 case Intrinsic::amdgcn_image_sample_c_b_o:
3101 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3102 case Intrinsic::amdgcn_image_sample_c_lz_o:
3103 case Intrinsic::amdgcn_image_sample_c_cd_o:
3104 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3106 case Intrinsic::amdgcn_image_getlod: {
3107 // Replace dmask with everything disabled with undef.
3108 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3109 if (!DMask || DMask->isNullValue()) {
3110 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3111 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3121 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3122 SelectionDAG &DAG) const {
3123 MachineFunction &MF = DAG.getMachineFunction();
3125 SDValue Chain = Op.getOperand(0);
3126 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3128 switch (IntrinsicID) {
3129 case Intrinsic::amdgcn_exp: {
3130 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3131 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3132 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3133 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3135 const SDValue Ops[] = {
3137 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3138 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3139 Op.getOperand(4), // src0
3140 Op.getOperand(5), // src1
3141 Op.getOperand(6), // src2
3142 Op.getOperand(7), // src3
3143 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3144 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3147 unsigned Opc = Done->isNullValue() ?
3148 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3149 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3151 case Intrinsic::amdgcn_exp_compr: {
3152 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3153 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3154 SDValue Src0 = Op.getOperand(4);
3155 SDValue Src1 = Op.getOperand(5);
3156 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3157 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3159 SDValue Undef = DAG.getUNDEF(MVT::f32);
3160 const SDValue Ops[] = {
3162 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3163 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3164 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3165 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3168 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3169 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3172 unsigned Opc = Done->isNullValue() ?
3173 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3174 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3176 case Intrinsic::amdgcn_s_sendmsg:
3177 case Intrinsic::amdgcn_s_sendmsghalt: {
3178 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3179 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3180 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3181 SDValue Glue = Chain.getValue(1);
3182 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3183 Op.getOperand(2), Glue);
3185 case AMDGPUIntrinsic::SI_tbuffer_store: {
3203 EVT VT = Op.getOperand(3).getValueType();
3205 MachineMemOperand *MMO = MF.getMachineMemOperand(
3206 MachinePointerInfo(),
3207 MachineMemOperand::MOStore,
3208 VT.getStoreSize(), 4);
3209 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3210 Op->getVTList(), Ops, VT, MMO);
3212 case AMDGPUIntrinsic::AMDGPU_kill: {
3213 SDValue Src = Op.getOperand(2);
3214 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3215 if (!K->isNegative())
3218 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3219 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3222 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3223 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3225 case Intrinsic::amdgcn_s_barrier: {
3226 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3227 const MachineFunction &MF = DAG.getMachineFunction();
3228 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3229 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3230 if (WGSize <= ST.getWavefrontSize())
3231 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3232 Op.getOperand(0)), 0);
3241 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3243 LoadSDNode *Load = cast<LoadSDNode>(Op);
3244 ISD::LoadExtType ExtType = Load->getExtensionType();
3245 EVT MemVT = Load->getMemoryVT();
3247 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3248 // FIXME: Copied from PPC
3249 // First, load into 32 bits, then truncate to 1 bit.
3251 SDValue Chain = Load->getChain();
3252 SDValue BasePtr = Load->getBasePtr();
3253 MachineMemOperand *MMO = Load->getMemOperand();
3255 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3257 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3258 BasePtr, RealMemVT, MMO);
3261 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3265 return DAG.getMergeValues(Ops, DL);
3268 if (!MemVT.isVector())
3271 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3272 "Custom lowering for non-i32 vectors hasn't been implemented.");
3274 unsigned AS = Load->getAddressSpace();
3275 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3276 AS, Load->getAlignment())) {
3278 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3279 return DAG.getMergeValues(Ops, DL);
3282 MachineFunction &MF = DAG.getMachineFunction();
3283 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3284 // If there is a possibilty that flat instruction access scratch memory
3285 // then we need to use the same legalization rules we use for private.
3286 if (AS == AMDGPUASI.FLAT_ADDRESS)
3287 AS = MFI->hasFlatScratchInit() ?
3288 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3290 unsigned NumElements = MemVT.getVectorNumElements();
3291 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3292 if (isMemOpUniform(Load))
3294 // Non-uniform loads will be selected to MUBUF instructions, so they
3295 // have the same legalization requirements as global and private
3299 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3300 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3301 isMemOpHasNoClobberedMemOperand(Load))
3303 // Non-uniform loads will be selected to MUBUF instructions, so they
3304 // have the same legalization requirements as global and private
3308 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3309 AS == AMDGPUASI.FLAT_ADDRESS) {
3310 if (NumElements > 4)
3311 return SplitVectorLoad(Op, DAG);
3312 // v4 loads are supported for private and global memory.
3315 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3316 // Depending on the setting of the private_element_size field in the
3317 // resource descriptor, we can only make private accesses up to a certain
3319 switch (Subtarget->getMaxPrivateElementSize()) {
3321 return scalarizeVectorLoad(Load, DAG);
3323 if (NumElements > 2)
3324 return SplitVectorLoad(Op, DAG);
3327 // Same as global/flat
3328 if (NumElements > 4)
3329 return SplitVectorLoad(Op, DAG);
3332 llvm_unreachable("unsupported private_element_size");
3334 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3335 if (NumElements > 2)
3336 return SplitVectorLoad(Op, DAG);
3338 if (NumElements == 2)
3341 // If properly aligned, if we split we might be able to use ds_read_b64.
3342 return SplitVectorLoad(Op, DAG);
3347 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3348 if (Op.getValueType() != MVT::i64)
3352 SDValue Cond = Op.getOperand(0);
3354 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3355 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3357 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3358 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3360 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3361 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3363 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3365 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3366 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3368 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3370 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3371 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3374 // Catch division cases where we can use shortcuts with rcp and rsq
3376 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3377 SelectionDAG &DAG) const {
3379 SDValue LHS = Op.getOperand(0);
3380 SDValue RHS = Op.getOperand(1);
3381 EVT VT = Op.getValueType();
3382 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3384 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3385 if (Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
3387 if (CLHS->isExactlyValue(1.0)) {
3388 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3389 // the CI documentation has a worst case error of 1 ulp.
3390 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3391 // use it as long as we aren't trying to use denormals.
3393 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3395 // 1.0 / sqrt(x) -> rsq(x)
3397 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3398 // error seems really high at 2^29 ULP.
3399 if (RHS.getOpcode() == ISD::FSQRT)
3400 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3402 // 1.0 / x -> rcp(x)
3403 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3406 // Same as for 1.0, but expand the sign out of the constant.
3407 if (CLHS->isExactlyValue(-1.0)) {
3408 // -1.0 / x -> rcp (fneg x)
3409 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3410 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3415 const SDNodeFlags *Flags = Op->getFlags();
3417 if (Unsafe || Flags->hasAllowReciprocal()) {
3418 // Turn into multiply by the reciprocal.
3419 // x / y -> x * (1.0 / y)
3421 Flags.setUnsafeAlgebra(true);
3422 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3423 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
3429 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3430 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3431 if (GlueChain->getNumValues() <= 1) {
3432 return DAG.getNode(Opcode, SL, VT, A, B);
3435 assert(GlueChain->getNumValues() == 3);
3437 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3439 default: llvm_unreachable("no chain equivalent for opcode");
3441 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3445 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3446 GlueChain.getValue(2));
3449 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3450 EVT VT, SDValue A, SDValue B, SDValue C,
3451 SDValue GlueChain) {
3452 if (GlueChain->getNumValues() <= 1) {
3453 return DAG.getNode(Opcode, SL, VT, A, B, C);
3456 assert(GlueChain->getNumValues() == 3);
3458 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3460 default: llvm_unreachable("no chain equivalent for opcode");
3462 Opcode = AMDGPUISD::FMA_W_CHAIN;
3466 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3467 GlueChain.getValue(2));
3470 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3471 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3475 SDValue Src0 = Op.getOperand(0);
3476 SDValue Src1 = Op.getOperand(1);
3478 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3479 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3481 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3482 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3484 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3485 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3487 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3490 // Faster 2.5 ULP division that does not support denormals.
3491 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3493 SDValue LHS = Op.getOperand(1);
3494 SDValue RHS = Op.getOperand(2);
3496 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3498 const APFloat K0Val(BitsToFloat(0x6f800000));
3499 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3501 const APFloat K1Val(BitsToFloat(0x2f800000));
3502 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3504 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3507 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3509 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3511 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3513 // TODO: Should this propagate fast-math-flags?
3514 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3516 // rcp does not support denormals.
3517 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3519 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3521 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3524 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3525 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3529 SDValue LHS = Op.getOperand(0);
3530 SDValue RHS = Op.getOperand(1);
3532 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3534 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3536 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3538 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3541 // Denominator is scaled to not be denormal, so using rcp is ok.
3542 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3544 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3547 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3548 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3549 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3551 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3553 if (!Subtarget->hasFP32Denormals()) {
3554 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3555 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3557 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3559 EnableDenormValue, BitField);
3562 EnableDenorm.getValue(0),
3563 EnableDenorm.getValue(1)
3566 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3569 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3570 ApproxRcp, One, NegDivScale0);
3572 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3575 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3578 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3579 NumeratorScaled, Mul);
3581 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3583 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3584 NumeratorScaled, Fma3);
3586 if (!Subtarget->hasFP32Denormals()) {
3587 const SDValue DisableDenormValue =
3588 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3589 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3595 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3596 DisableDenorm, DAG.getRoot());
3597 DAG.setRoot(OutputChain);
3600 SDValue Scale = NumeratorScaled.getValue(1);
3601 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3602 Fma4, Fma1, Fma3, Scale);
3604 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3607 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3608 if (DAG.getTarget().Options.UnsafeFPMath)
3609 return lowerFastUnsafeFDIV(Op, DAG);
3612 SDValue X = Op.getOperand(0);
3613 SDValue Y = Op.getOperand(1);
3615 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3617 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3619 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3621 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3623 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3625 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3627 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3629 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3631 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3633 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3634 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3636 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3637 NegDivScale0, Mul, DivScale1);
3641 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3642 // Workaround a hardware bug on SI where the condition output from div_scale
3645 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3647 // Figure out if the scale to use for div_fmas.
3648 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3649 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3650 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3651 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3653 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3654 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3657 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3659 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3661 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3662 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3663 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3665 Scale = DivScale1.getValue(1);
3668 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3669 Fma4, Fma3, Mul, Scale);
3671 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3674 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3675 EVT VT = Op.getValueType();
3678 return LowerFDIV32(Op, DAG);
3681 return LowerFDIV64(Op, DAG);
3684 return LowerFDIV16(Op, DAG);
3686 llvm_unreachable("Unexpected type for fdiv");
3689 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3691 StoreSDNode *Store = cast<StoreSDNode>(Op);
3692 EVT VT = Store->getMemoryVT();
3694 if (VT == MVT::i1) {
3695 return DAG.getTruncStore(Store->getChain(), DL,
3696 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3697 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3700 assert(VT.isVector() &&
3701 Store->getValue().getValueType().getScalarType() == MVT::i32);
3703 unsigned AS = Store->getAddressSpace();
3704 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3705 AS, Store->getAlignment())) {
3706 return expandUnalignedStore(Store, DAG);
3709 MachineFunction &MF = DAG.getMachineFunction();
3710 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3711 // If there is a possibilty that flat instruction access scratch memory
3712 // then we need to use the same legalization rules we use for private.
3713 if (AS == AMDGPUASI.FLAT_ADDRESS)
3714 AS = MFI->hasFlatScratchInit() ?
3715 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3717 unsigned NumElements = VT.getVectorNumElements();
3718 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3719 AS == AMDGPUASI.FLAT_ADDRESS) {
3720 if (NumElements > 4)
3721 return SplitVectorStore(Op, DAG);
3723 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3724 switch (Subtarget->getMaxPrivateElementSize()) {
3726 return scalarizeVectorStore(Store, DAG);
3728 if (NumElements > 2)
3729 return SplitVectorStore(Op, DAG);
3732 if (NumElements > 4)
3733 return SplitVectorStore(Op, DAG);
3736 llvm_unreachable("unsupported private_element_size");
3738 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3739 if (NumElements > 2)
3740 return SplitVectorStore(Op, DAG);
3742 if (NumElements == 2)
3745 // If properly aligned, if we split we might be able to use ds_write_b64.
3746 return SplitVectorStore(Op, DAG);
3748 llvm_unreachable("unhandled address space");
3752 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3754 EVT VT = Op.getValueType();
3755 SDValue Arg = Op.getOperand(0);
3756 // TODO: Should this propagate fast-math-flags?
3757 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3758 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3759 DAG.getConstantFP(0.5/M_PI, DL,
3762 switch (Op.getOpcode()) {
3764 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3766 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3768 llvm_unreachable("Wrong trig opcode");
3772 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3773 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3774 assert(AtomicNode->isCompareAndSwap());
3775 unsigned AS = AtomicNode->getAddressSpace();
3777 // No custom lowering required for local address space
3778 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
3781 // Non-local address space requires custom lowering for atomic compare
3782 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3784 SDValue ChainIn = Op.getOperand(0);
3785 SDValue Addr = Op.getOperand(1);
3786 SDValue Old = Op.getOperand(2);
3787 SDValue New = Op.getOperand(3);
3788 EVT VT = Op.getValueType();
3789 MVT SimpleVT = VT.getSimpleVT();
3790 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3792 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3793 SDValue Ops[] = { ChainIn, Addr, NewOld };
3795 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3796 Ops, VT, AtomicNode->getMemOperand());
3799 //===----------------------------------------------------------------------===//
3800 // Custom DAG optimizations
3801 //===----------------------------------------------------------------------===//
3803 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3804 DAGCombinerInfo &DCI) const {
3805 EVT VT = N->getValueType(0);
3806 EVT ScalarVT = VT.getScalarType();
3807 if (ScalarVT != MVT::f32)
3810 SelectionDAG &DAG = DCI.DAG;
3813 SDValue Src = N->getOperand(0);
3814 EVT SrcVT = Src.getValueType();
3816 // TODO: We could try to match extracting the higher bytes, which would be
3817 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3818 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3819 // about in practice.
3820 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3821 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3822 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3823 DCI.AddToWorklist(Cvt.getNode());
3831 /// \brief Return true if the given offset Size in bytes can be folded into
3832 /// the immediate offsets of a memory instruction for the given address space.
3833 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3834 const SISubtarget &STI) {
3835 auto AMDGPUASI = STI.getAMDGPUAS();
3836 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
3837 // MUBUF instructions a 12-bit offset in bytes.
3838 return isUInt<12>(OffsetSize);
3840 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3841 // SMRD instructions have an 8-bit offset in dwords on SI and
3842 // a 20-bit offset in bytes on VI.
3843 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3844 return isUInt<20>(OffsetSize);
3846 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3848 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
3849 AS == AMDGPUASI.REGION_ADDRESS) {
3850 // The single offset versions have a 16-bit offset in bytes.
3851 return isUInt<16>(OffsetSize);
3853 // Indirect register addressing does not use any offsets.
3857 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3859 // This is a variant of
3860 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3862 // The normal DAG combiner will do this, but only if the add has one use since
3863 // that would increase the number of instructions.
3865 // This prevents us from seeing a constant offset that can be folded into a
3866 // memory instruction's addressing mode. If we know the resulting add offset of
3867 // a pointer can be folded into an addressing offset, we can replace the pointer
3868 // operand with the add of new constant offset. This eliminates one of the uses,
3869 // and may allow the remaining use to also be simplified.
3871 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3873 DAGCombinerInfo &DCI) const {
3874 SDValue N0 = N->getOperand(0);
3875 SDValue N1 = N->getOperand(1);
3877 if (N0.getOpcode() != ISD::ADD)
3880 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3884 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3888 // If the resulting offset is too large, we can't fold it into the addressing
3890 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3891 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3894 SelectionDAG &DAG = DCI.DAG;
3896 EVT VT = N->getValueType(0);
3898 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3899 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3901 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3904 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
3905 DAGCombinerInfo &DCI) const {
3906 SDValue Ptr = N->getBasePtr();
3907 SelectionDAG &DAG = DCI.DAG;
3910 // TODO: We could also do this for multiplies.
3911 unsigned AS = N->getAddressSpace();
3912 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
3913 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3915 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
3917 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3918 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
3925 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3926 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3927 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3928 (Opc == ISD::XOR && Val == 0);
3931 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3932 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3933 // integer combine opportunities since most 64-bit operations are decomposed
3934 // this way. TODO: We won't want this for SALU especially if it is an inline
3936 SDValue SITargetLowering::splitBinaryBitConstantOp(
3937 DAGCombinerInfo &DCI,
3939 unsigned Opc, SDValue LHS,
3940 const ConstantSDNode *CRHS) const {
3941 uint64_t Val = CRHS->getZExtValue();
3942 uint32_t ValLo = Lo_32(Val);
3943 uint32_t ValHi = Hi_32(Val);
3944 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3946 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3947 bitOpWithConstantIsReducible(Opc, ValHi)) ||
3948 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3949 // If we need to materialize a 64-bit immediate, it will be split up later
3950 // anyway. Avoid creating the harder to understand 64-bit immediate
3952 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3958 SDValue SITargetLowering::performAndCombine(SDNode *N,
3959 DAGCombinerInfo &DCI) const {
3960 if (DCI.isBeforeLegalize())
3963 SelectionDAG &DAG = DCI.DAG;
3964 EVT VT = N->getValueType(0);
3965 SDValue LHS = N->getOperand(0);
3966 SDValue RHS = N->getOperand(1);
3969 if (VT == MVT::i64) {
3970 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3973 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3978 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3979 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3980 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3981 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3982 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3984 SDValue X = LHS.getOperand(0);
3985 SDValue Y = RHS.getOperand(0);
3986 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3989 if (LCC == ISD::SETO) {
3990 if (X != LHS.getOperand(1))
3993 if (RCC == ISD::SETUNE) {
3994 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3995 if (!C1 || !C1->isInfinity() || C1->isNegative())
3998 const uint32_t Mask = SIInstrFlags::N_NORMAL |
3999 SIInstrFlags::N_SUBNORMAL |
4000 SIInstrFlags::N_ZERO |
4001 SIInstrFlags::P_ZERO |
4002 SIInstrFlags::P_SUBNORMAL |
4003 SIInstrFlags::P_NORMAL;
4005 static_assert(((~(SIInstrFlags::S_NAN |
4006 SIInstrFlags::Q_NAN |
4007 SIInstrFlags::N_INFINITY |
4008 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4012 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4013 X, DAG.getConstant(Mask, DL, MVT::i32));
4021 SDValue SITargetLowering::performOrCombine(SDNode *N,
4022 DAGCombinerInfo &DCI) const {
4023 SelectionDAG &DAG = DCI.DAG;
4024 SDValue LHS = N->getOperand(0);
4025 SDValue RHS = N->getOperand(1);
4027 EVT VT = N->getValueType(0);
4028 if (VT == MVT::i1) {
4029 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4030 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4031 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4032 SDValue Src = LHS.getOperand(0);
4033 if (Src != RHS.getOperand(0))
4036 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4037 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4041 // Only 10 bits are used.
4042 static const uint32_t MaxMask = 0x3ff;
4044 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4046 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4047 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4056 // TODO: This could be a generic combine with a predicate for extracting the
4057 // high half of an integer being free.
4059 // (or i64:x, (zero_extend i32:y)) ->
4060 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4061 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4062 RHS.getOpcode() != ISD::ZERO_EXTEND)
4063 std::swap(LHS, RHS);
4065 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4066 SDValue ExtSrc = RHS.getOperand(0);
4067 EVT SrcVT = ExtSrc.getValueType();
4068 if (SrcVT == MVT::i32) {
4070 SDValue LowLHS, HiBits;
4071 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4072 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4074 DCI.AddToWorklist(LowOr.getNode());
4075 DCI.AddToWorklist(HiBits.getNode());
4077 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4079 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4083 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4086 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4093 SDValue SITargetLowering::performXorCombine(SDNode *N,
4094 DAGCombinerInfo &DCI) const {
4095 EVT VT = N->getValueType(0);
4099 SDValue LHS = N->getOperand(0);
4100 SDValue RHS = N->getOperand(1);
4102 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4105 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4112 // Instructions that will be lowered with a final instruction that zeros the
4113 // high result bits.
4114 // XXX - probably only need to list legal operations.
4115 static bool fp16SrcZerosHighBits(unsigned Opc) {
4124 case ISD::FCANONICALIZE:
4126 case ISD::UINT_TO_FP:
4127 case ISD::SINT_TO_FP:
4129 // Fabs is lowered to a bit operation, but it's an and which will clear the
4130 // high bits anyway.
4144 case ISD::FNEARBYINT:
4149 case AMDGPUISD::FRACT:
4150 case AMDGPUISD::CLAMP:
4151 case AMDGPUISD::COS_HW:
4152 case AMDGPUISD::SIN_HW:
4153 case AMDGPUISD::FMIN3:
4154 case AMDGPUISD::FMAX3:
4155 case AMDGPUISD::FMED3:
4156 case AMDGPUISD::FMAD_FTZ:
4157 case AMDGPUISD::RCP:
4158 case AMDGPUISD::RSQ:
4159 case AMDGPUISD::LDEXP:
4162 // fcopysign, select and others may be lowered to 32-bit bit operations
4163 // which don't zero the high bits.
4168 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4169 DAGCombinerInfo &DCI) const {
4170 if (!Subtarget->has16BitInsts() ||
4171 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4174 EVT VT = N->getValueType(0);
4178 SDValue Src = N->getOperand(0);
4179 if (Src.getValueType() != MVT::i16)
4182 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4183 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4184 if (Src.getOpcode() == ISD::BITCAST) {
4185 SDValue BCSrc = Src.getOperand(0);
4186 if (BCSrc.getValueType() == MVT::f16 &&
4187 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4188 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4194 SDValue SITargetLowering::performClassCombine(SDNode *N,
4195 DAGCombinerInfo &DCI) const {
4196 SelectionDAG &DAG = DCI.DAG;
4197 SDValue Mask = N->getOperand(1);
4199 // fp_class x, 0 -> false
4200 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4201 if (CMask->isNullValue())
4202 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4205 if (N->getOperand(0).isUndef())
4206 return DAG.getUNDEF(MVT::i1);
4211 // Constant fold canonicalize.
4212 SDValue SITargetLowering::performFCanonicalizeCombine(
4214 DAGCombinerInfo &DCI) const {
4215 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4219 SelectionDAG &DAG = DCI.DAG;
4220 const APFloat &C = CFP->getValueAPF();
4222 // Flush denormals to 0 if not enabled.
4223 if (C.isDenormal()) {
4224 EVT VT = N->getValueType(0);
4225 EVT SVT = VT.getScalarType();
4226 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4227 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4229 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4230 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4232 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4233 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4237 EVT VT = N->getValueType(0);
4238 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4239 if (C.isSignaling()) {
4240 // Quiet a signaling NaN.
4241 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4244 // Make sure it is the canonical NaN bitpattern.
4246 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4248 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4249 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4252 return N->getOperand(0);
4255 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4258 return AMDGPUISD::FMAX3;
4260 return AMDGPUISD::SMAX3;
4262 return AMDGPUISD::UMAX3;
4264 return AMDGPUISD::FMIN3;
4266 return AMDGPUISD::SMIN3;
4268 return AMDGPUISD::UMIN3;
4270 llvm_unreachable("Not a min/max opcode");
4274 SDValue SITargetLowering::performIntMed3ImmCombine(
4275 SelectionDAG &DAG, const SDLoc &SL,
4276 SDValue Op0, SDValue Op1, bool Signed) const {
4277 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4281 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4286 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4289 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4293 EVT VT = K0->getValueType(0);
4294 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4295 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4296 return DAG.getNode(Med3Opc, SL, VT,
4297 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4300 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4302 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4304 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4305 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4306 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4308 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4309 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4312 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4313 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4316 return DAG.isKnownNeverNaN(Op);
4319 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4322 SDValue Op1) const {
4323 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4327 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4331 // Ordered >= (although NaN inputs should have folded away by now).
4332 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4333 if (Cmp == APFloat::cmpGreaterThan)
4336 // TODO: Check IEEE bit enabled?
4337 EVT VT = K0->getValueType(0);
4338 if (Subtarget->enableDX10Clamp()) {
4339 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4340 // hardware fmed3 behavior converting to a min.
4341 // FIXME: Should this be allowing -0.0?
4342 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4343 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4346 // med3 for f16 is only available on gfx9+.
4347 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4350 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4351 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4352 // give the other result, which is different from med3 with a NaN input.
4353 SDValue Var = Op0.getOperand(0);
4354 if (!isKnownNeverSNan(DAG, Var))
4357 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4358 Var, SDValue(K0, 0), SDValue(K1, 0));
4361 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4362 DAGCombinerInfo &DCI) const {
4363 SelectionDAG &DAG = DCI.DAG;
4365 EVT VT = N->getValueType(0);
4366 unsigned Opc = N->getOpcode();
4367 SDValue Op0 = N->getOperand(0);
4368 SDValue Op1 = N->getOperand(1);
4370 // Only do this if the inner op has one use since this will just increases
4371 // register pressure for no benefit.
4374 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4376 // max(max(a, b), c) -> max3(a, b, c)
4377 // min(min(a, b), c) -> min3(a, b, c)
4378 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4380 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4389 // max(a, max(b, c)) -> max3(a, b, c)
4390 // min(a, min(b, c)) -> min3(a, b, c)
4391 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4393 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4402 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4403 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4404 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4408 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4409 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4413 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4414 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4415 (Opc == AMDGPUISD::FMIN_LEGACY &&
4416 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4417 (VT == MVT::f32 || VT == MVT::f64 ||
4418 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4420 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4427 static bool isClampZeroToOne(SDValue A, SDValue B) {
4428 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4429 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4430 // FIXME: Should this be allowing -0.0?
4431 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4432 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4439 // FIXME: Should only worry about snans for version with chain.
4440 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4441 DAGCombinerInfo &DCI) const {
4442 EVT VT = N->getValueType(0);
4443 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4444 // NaNs. With a NaN input, the order of the operands may change the result.
4446 SelectionDAG &DAG = DCI.DAG;
4449 SDValue Src0 = N->getOperand(0);
4450 SDValue Src1 = N->getOperand(1);
4451 SDValue Src2 = N->getOperand(2);
4453 if (isClampZeroToOne(Src0, Src1)) {
4454 // const_a, const_b, x -> clamp is safe in all cases including signaling
4456 // FIXME: Should this be allowing -0.0?
4457 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4460 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4461 // handling no dx10-clamp?
4462 if (Subtarget->enableDX10Clamp()) {
4463 // If NaNs is clamped to 0, we are free to reorder the inputs.
4465 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4466 std::swap(Src0, Src1);
4468 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4469 std::swap(Src1, Src2);
4471 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4472 std::swap(Src0, Src1);
4474 if (isClampZeroToOne(Src1, Src2))
4475 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4481 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4482 DAGCombinerInfo &DCI) const {
4483 SDValue Src0 = N->getOperand(0);
4484 SDValue Src1 = N->getOperand(1);
4485 if (Src0.isUndef() && Src1.isUndef())
4486 return DCI.DAG.getUNDEF(N->getValueType(0));
4490 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4492 const SDNode *N1) const {
4493 EVT VT = N0->getValueType(0);
4495 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4496 // support denormals ever.
4497 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4498 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4501 const TargetOptions &Options = DAG.getTarget().Options;
4502 if ((Options.AllowFPOpFusion == FPOpFusion::Fast ||
4503 Options.UnsafeFPMath ||
4504 (cast<BinaryWithFlagsSDNode>(N0)->Flags.hasUnsafeAlgebra() &&
4505 cast<BinaryWithFlagsSDNode>(N1)->Flags.hasUnsafeAlgebra())) &&
4506 isFMAFasterThanFMulAndFAdd(VT)) {
4513 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4514 DAGCombinerInfo &DCI) const {
4515 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4518 SelectionDAG &DAG = DCI.DAG;
4519 EVT VT = N->getValueType(0);
4522 SDValue LHS = N->getOperand(0);
4523 SDValue RHS = N->getOperand(1);
4525 // These should really be instruction patterns, but writing patterns with
4526 // source modiifiers is a pain.
4528 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4529 if (LHS.getOpcode() == ISD::FADD) {
4530 SDValue A = LHS.getOperand(0);
4531 if (A == LHS.getOperand(1)) {
4532 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4534 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4535 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4540 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4541 if (RHS.getOpcode() == ISD::FADD) {
4542 SDValue A = RHS.getOperand(0);
4543 if (A == RHS.getOperand(1)) {
4544 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4546 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4547 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4555 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4556 DAGCombinerInfo &DCI) const {
4557 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4560 SelectionDAG &DAG = DCI.DAG;
4562 EVT VT = N->getValueType(0);
4563 assert(!VT.isVector());
4565 // Try to get the fneg to fold into the source modifier. This undoes generic
4566 // DAG combines and folds them into the mad.
4568 // Only do this if we are not trying to support denormals. v_mad_f32 does
4569 // not support denormals ever.
4570 SDValue LHS = N->getOperand(0);
4571 SDValue RHS = N->getOperand(1);
4572 if (LHS.getOpcode() == ISD::FADD) {
4573 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4574 SDValue A = LHS.getOperand(0);
4575 if (A == LHS.getOperand(1)) {
4576 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4578 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4579 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4581 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4586 if (RHS.getOpcode() == ISD::FADD) {
4587 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4589 SDValue A = RHS.getOperand(0);
4590 if (A == RHS.getOperand(1)) {
4591 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4593 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4594 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4602 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4603 DAGCombinerInfo &DCI) const {
4604 SelectionDAG &DAG = DCI.DAG;
4607 SDValue LHS = N->getOperand(0);
4608 SDValue RHS = N->getOperand(1);
4609 EVT VT = LHS.getValueType();
4611 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4615 // Match isinf pattern
4616 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4617 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4618 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4619 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4623 const APFloat &APF = CRHS->getValueAPF();
4624 if (APF.isInfinity() && !APF.isNegative()) {
4625 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4626 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4627 DAG.getConstant(Mask, SL, MVT::i32));
4634 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4635 DAGCombinerInfo &DCI) const {
4636 SelectionDAG &DAG = DCI.DAG;
4638 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4640 SDValue Src = N->getOperand(0);
4641 SDValue Srl = N->getOperand(0);
4642 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4643 Srl = Srl.getOperand(0);
4645 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4646 if (Srl.getOpcode() == ISD::SRL) {
4647 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4648 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4649 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4651 if (const ConstantSDNode *C =
4652 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4653 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4656 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4657 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4658 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4664 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4666 APInt KnownZero, KnownOne;
4667 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4668 !DCI.isBeforeLegalizeOps());
4669 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4670 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
4671 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
4672 DCI.CommitTargetLoweringOpt(TLO);
4678 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4679 DAGCombinerInfo &DCI) const {
4680 switch (N->getOpcode()) {
4682 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4684 return performFAddCombine(N, DCI);
4686 return performFSubCombine(N, DCI);
4688 return performSetCCCombine(N, DCI);
4695 case AMDGPUISD::FMIN_LEGACY:
4696 case AMDGPUISD::FMAX_LEGACY: {
4697 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4698 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4699 return performMinMaxCombine(N, DCI);
4704 case ISD::ATOMIC_LOAD:
4705 case ISD::ATOMIC_STORE:
4706 case ISD::ATOMIC_CMP_SWAP:
4707 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4708 case ISD::ATOMIC_SWAP:
4709 case ISD::ATOMIC_LOAD_ADD:
4710 case ISD::ATOMIC_LOAD_SUB:
4711 case ISD::ATOMIC_LOAD_AND:
4712 case ISD::ATOMIC_LOAD_OR:
4713 case ISD::ATOMIC_LOAD_XOR:
4714 case ISD::ATOMIC_LOAD_NAND:
4715 case ISD::ATOMIC_LOAD_MIN:
4716 case ISD::ATOMIC_LOAD_MAX:
4717 case ISD::ATOMIC_LOAD_UMIN:
4718 case ISD::ATOMIC_LOAD_UMAX:
4719 case AMDGPUISD::ATOMIC_INC:
4720 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4721 if (DCI.isBeforeLegalize())
4723 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4725 return performAndCombine(N, DCI);
4727 return performOrCombine(N, DCI);
4729 return performXorCombine(N, DCI);
4730 case ISD::ZERO_EXTEND:
4731 return performZeroExtendCombine(N, DCI);
4732 case AMDGPUISD::FP_CLASS:
4733 return performClassCombine(N, DCI);
4734 case ISD::FCANONICALIZE:
4735 return performFCanonicalizeCombine(N, DCI);
4736 case AMDGPUISD::FRACT:
4737 case AMDGPUISD::RCP:
4738 case AMDGPUISD::RSQ:
4739 case AMDGPUISD::RCP_LEGACY:
4740 case AMDGPUISD::RSQ_LEGACY:
4741 case AMDGPUISD::RSQ_CLAMP:
4742 case AMDGPUISD::LDEXP: {
4743 SDValue Src = N->getOperand(0);
4748 case ISD::SINT_TO_FP:
4749 case ISD::UINT_TO_FP:
4750 return performUCharToFloatCombine(N, DCI);
4751 case AMDGPUISD::CVT_F32_UBYTE0:
4752 case AMDGPUISD::CVT_F32_UBYTE1:
4753 case AMDGPUISD::CVT_F32_UBYTE2:
4754 case AMDGPUISD::CVT_F32_UBYTE3:
4755 return performCvtF32UByteNCombine(N, DCI);
4756 case AMDGPUISD::FMED3:
4757 return performFMed3Combine(N, DCI);
4758 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4759 return performCvtPkRTZCombine(N, DCI);
4760 case ISD::SCALAR_TO_VECTOR: {
4761 SelectionDAG &DAG = DCI.DAG;
4762 EVT VT = N->getValueType(0);
4764 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4765 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4767 SDValue Src = N->getOperand(0);
4768 EVT EltVT = Src.getValueType();
4769 if (EltVT == MVT::f16)
4770 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4772 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4773 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4779 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4782 /// \brief Helper function for adjustWritemask
4783 static unsigned SubIdx2Lane(unsigned Idx) {
4786 case AMDGPU::sub0: return 0;
4787 case AMDGPU::sub1: return 1;
4788 case AMDGPU::sub2: return 2;
4789 case AMDGPU::sub3: return 3;
4793 /// \brief Adjust the writemask of MIMG instructions
4794 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4795 SelectionDAG &DAG) const {
4796 SDNode *Users[4] = { };
4798 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4799 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4800 unsigned NewDmask = 0;
4802 // Try to figure out the used register components
4803 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4806 // Don't look at users of the chain.
4807 if (I.getUse().getResNo() != 0)
4810 // Abort if we can't understand the usage
4811 if (!I->isMachineOpcode() ||
4812 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4815 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4816 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4817 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4819 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4821 // Set which texture component corresponds to the lane.
4823 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4825 Comp = countTrailingZeros(Dmask);
4826 Dmask &= ~(1 << Comp);
4829 // Abort if we have more than one user per component
4834 NewDmask |= 1 << Comp;
4837 // Abort if there's no change
4838 if (NewDmask == OldDmask)
4841 // Adjust the writemask in the node
4842 std::vector<SDValue> Ops;
4843 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4844 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4845 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4846 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4848 // If we only got one lane, replace it with a copy
4849 // (if NewDmask has only one bit set...)
4850 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4851 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4853 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4854 SDLoc(), Users[Lane]->getValueType(0),
4855 SDValue(Node, 0), RC);
4856 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4860 // Update the users of the node with the new indices
4861 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4862 SDNode *User = Users[i];
4866 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4867 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4871 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4872 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4873 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4878 static bool isFrameIndexOp(SDValue Op) {
4879 if (Op.getOpcode() == ISD::AssertZext)
4880 Op = Op.getOperand(0);
4882 return isa<FrameIndexSDNode>(Op);
4885 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4886 /// with frame index operands.
4887 /// LLVM assumes that inputs are to these instructions are registers.
4888 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4889 SelectionDAG &DAG) const {
4890 if (Node->getOpcode() == ISD::CopyToReg) {
4891 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
4892 SDValue SrcVal = Node->getOperand(2);
4894 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
4895 // to try understanding copies to physical registers.
4896 if (SrcVal.getValueType() == MVT::i1 &&
4897 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
4899 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
4900 SDValue VReg = DAG.getRegister(
4901 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
4903 SDNode *Glued = Node->getGluedNode();
4905 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
4906 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
4908 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
4909 VReg, ToVReg.getValue(1));
4910 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
4911 DAG.RemoveDeadNode(Node);
4912 return ToResultReg.getNode();
4916 SmallVector<SDValue, 8> Ops;
4917 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4918 if (!isFrameIndexOp(Node->getOperand(i))) {
4919 Ops.push_back(Node->getOperand(i));
4924 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4925 Node->getOperand(i).getValueType(),
4926 Node->getOperand(i)), 0));
4929 DAG.UpdateNodeOperands(Node, Ops);
4933 /// \brief Fold the instructions after selecting them.
4934 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4935 SelectionDAG &DAG) const {
4936 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4937 unsigned Opcode = Node->getMachineOpcode();
4939 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4940 !TII->isGather4(Opcode))
4941 adjustWritemask(Node, DAG);
4943 if (Opcode == AMDGPU::INSERT_SUBREG ||
4944 Opcode == AMDGPU::REG_SEQUENCE) {
4945 legalizeTargetIndependentNode(Node, DAG);
4951 /// \brief Assign the register class depending on the number of
4952 /// bits set in the writemask
4953 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4954 SDNode *Node) const {
4955 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4957 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4959 if (TII->isVOP3(MI.getOpcode())) {
4960 // Make sure constant bus requirements are respected.
4961 TII->legalizeOperandsVOP3(MRI, MI);
4965 if (TII->isMIMG(MI)) {
4966 unsigned VReg = MI.getOperand(0).getReg();
4967 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4968 // TODO: Need mapping tables to handle other cases (register classes).
4969 if (RC != &AMDGPU::VReg_128RegClass)
4972 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4973 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4974 unsigned BitsSet = 0;
4975 for (unsigned i = 0; i < 4; ++i)
4976 BitsSet += Writemask & (1 << i) ? 1 : 0;
4979 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
4980 case 2: RC = &AMDGPU::VReg_64RegClass; break;
4981 case 3: RC = &AMDGPU::VReg_96RegClass; break;
4984 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4985 MI.setDesc(TII->get(NewOpcode));
4986 MRI.setRegClass(VReg, RC);
4990 // Replace unused atomics with the no return version.
4991 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4992 if (NoRetAtomicOp != -1) {
4993 if (!Node->hasAnyUseOfValue(0)) {
4994 MI.setDesc(TII->get(NoRetAtomicOp));
4995 MI.RemoveOperand(0);
4999 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5000 // instruction, because the return type of these instructions is a vec2 of
5001 // the memory type, so it can be tied to the input operand.
5002 // This means these instructions always have a use, so we need to add a
5003 // special case to check if the atomic has only one extract_subreg use,
5004 // which itself has no uses.
5005 if ((Node->hasNUsesOfValue(1, 0) &&
5006 Node->use_begin()->isMachineOpcode() &&
5007 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5008 !Node->use_begin()->hasAnyUseOfValue(0))) {
5009 unsigned Def = MI.getOperand(0).getReg();
5011 // Change this into a noret atomic.
5012 MI.setDesc(TII->get(NoRetAtomicOp));
5013 MI.RemoveOperand(0);
5015 // If we only remove the def operand from the atomic instruction, the
5016 // extract_subreg will be left with a use of a vreg without a def.
5017 // So we need to insert an implicit_def to avoid machine verifier
5019 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5020 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5026 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5028 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5029 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5032 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5034 SDValue Ptr) const {
5035 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5037 // Build the half of the subregister with the constants before building the
5038 // full 128-bit register. If we are building multiple resource descriptors,
5039 // this will allow CSEing of the 2-component register.
5040 const SDValue Ops0[] = {
5041 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5042 buildSMovImm32(DAG, DL, 0),
5043 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5044 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5045 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5048 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5049 MVT::v2i32, Ops0), 0);
5051 // Combine the constants and the pointer.
5052 const SDValue Ops1[] = {
5053 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5055 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5057 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5060 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5063 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5064 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5065 /// of the resource descriptor) to create an offset, which is added to
5066 /// the resource pointer.
5067 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5068 SDValue Ptr, uint32_t RsrcDword1,
5069 uint64_t RsrcDword2And3) const {
5070 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5071 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5073 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5074 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5078 SDValue DataLo = buildSMovImm32(DAG, DL,
5079 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5080 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5082 const SDValue Ops[] = {
5083 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5085 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5087 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5089 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5091 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5094 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5097 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5098 const TargetRegisterClass *RC,
5099 unsigned Reg, EVT VT) const {
5100 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5102 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5103 cast<RegisterSDNode>(VReg)->getReg(), VT);
5106 //===----------------------------------------------------------------------===//
5107 // SI Inline Assembly Support
5108 //===----------------------------------------------------------------------===//
5110 std::pair<unsigned, const TargetRegisterClass *>
5111 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5112 StringRef Constraint,
5114 if (!isTypeLegal(VT))
5115 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5117 if (Constraint.size() == 1) {
5118 switch (Constraint[0]) {
5121 switch (VT.getSizeInBits()) {
5123 return std::make_pair(0U, nullptr);
5126 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5128 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5130 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5132 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5134 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5138 switch (VT.getSizeInBits()) {
5140 return std::make_pair(0U, nullptr);
5143 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5145 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5147 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5149 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5151 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5153 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5158 if (Constraint.size() > 1) {
5159 const TargetRegisterClass *RC = nullptr;
5160 if (Constraint[1] == 'v') {
5161 RC = &AMDGPU::VGPR_32RegClass;
5162 } else if (Constraint[1] == 's') {
5163 RC = &AMDGPU::SGPR_32RegClass;
5168 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5169 if (!Failed && Idx < RC->getNumRegs())
5170 return std::make_pair(RC->getRegister(Idx), RC);
5173 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5176 SITargetLowering::ConstraintType
5177 SITargetLowering::getConstraintType(StringRef Constraint) const {
5178 if (Constraint.size() == 1) {
5179 switch (Constraint[0]) {
5183 return C_RegisterClass;
5186 return TargetLowering::getConstraintType(Constraint);