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/KnownBits.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include "llvm/Target/TargetRegisterInfo.h"
86 static cl::opt<bool> EnableVGPRIndexMode(
87 "amdgpu-vgpr-index-mode",
88 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
91 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
92 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
93 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
94 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
95 return AMDGPU::SGPR0 + Reg;
98 llvm_unreachable("Cannot allocate sgpr");
101 SITargetLowering::SITargetLowering(const TargetMachine &TM,
102 const SISubtarget &STI)
103 : AMDGPUTargetLowering(TM, STI) {
104 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
105 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
107 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
108 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
110 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
111 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
112 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
114 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
115 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
117 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
118 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
120 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
121 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
123 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
124 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
126 if (Subtarget->has16BitInsts()) {
127 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
128 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
131 if (Subtarget->hasVOP3PInsts()) {
132 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
133 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
136 computeRegisterProperties(STI.getRegisterInfo());
138 // We need to custom lower vector stores from local memory
139 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
140 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
141 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
142 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
143 setOperationAction(ISD::LOAD, MVT::i1, Custom);
145 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
146 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
147 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
148 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
149 setOperationAction(ISD::STORE, MVT::i1, Custom);
151 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
152 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
153 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
154 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
155 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
156 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
157 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
158 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
159 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
160 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
162 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
163 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
164 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
166 setOperationAction(ISD::SELECT, MVT::i1, Promote);
167 setOperationAction(ISD::SELECT, MVT::i64, Custom);
168 setOperationAction(ISD::SELECT, MVT::f64, Promote);
169 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
171 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
175 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
177 setOperationAction(ISD::SETCC, MVT::i1, Promote);
178 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
179 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
180 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
182 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
183 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
185 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
186 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
187 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
188 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
190 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
193 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
194 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
195 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
196 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
198 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
200 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
201 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
202 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
204 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
205 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
206 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
207 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
208 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
209 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
211 setOperationAction(ISD::UADDO, MVT::i32, Legal);
212 setOperationAction(ISD::USUBO, MVT::i32, Legal);
214 // We only support LOAD/STORE and vector manipulation ops for vectors
215 // with > 4 elements.
216 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
217 MVT::v2i64, MVT::v2f64}) {
218 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
222 case ISD::BUILD_VECTOR:
224 case ISD::EXTRACT_VECTOR_ELT:
225 case ISD::INSERT_VECTOR_ELT:
226 case ISD::INSERT_SUBVECTOR:
227 case ISD::EXTRACT_SUBVECTOR:
228 case ISD::SCALAR_TO_VECTOR:
230 case ISD::CONCAT_VECTORS:
231 setOperationAction(Op, VT, Custom);
234 setOperationAction(Op, VT, Expand);
240 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
241 // is expanded to avoid having two separate loops in case the index is a VGPR.
243 // Most operations are naturally 32-bit vector operations. We only support
244 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
245 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
246 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
247 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
249 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
250 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
252 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
253 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
255 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
256 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
259 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
260 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
261 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
262 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
264 // Avoid stack access for these.
265 // TODO: Generalize to more vector types.
266 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
267 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
269 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
271 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
272 // and output demarshalling
273 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
274 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
276 // We can't return success/failure, only the old value,
277 // let LLVM add the comparison
278 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
279 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
281 if (getSubtarget()->hasFlatAddressSpace()) {
282 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
283 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
286 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
287 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
289 // On SI this is s_memtime and s_memrealtime on VI.
290 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
291 setOperationAction(ISD::TRAP, MVT::Other, Custom);
292 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
294 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
295 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
297 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
298 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
299 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
300 setOperationAction(ISD::FRINT, MVT::f64, Legal);
303 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
305 setOperationAction(ISD::FSIN, MVT::f32, Custom);
306 setOperationAction(ISD::FCOS, MVT::f32, Custom);
307 setOperationAction(ISD::FDIV, MVT::f32, Custom);
308 setOperationAction(ISD::FDIV, MVT::f64, Custom);
310 if (Subtarget->has16BitInsts()) {
311 setOperationAction(ISD::Constant, MVT::i16, Legal);
313 setOperationAction(ISD::SMIN, MVT::i16, Legal);
314 setOperationAction(ISD::SMAX, MVT::i16, Legal);
316 setOperationAction(ISD::UMIN, MVT::i16, Legal);
317 setOperationAction(ISD::UMAX, MVT::i16, Legal);
319 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
320 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
322 setOperationAction(ISD::ROTR, MVT::i16, Promote);
323 setOperationAction(ISD::ROTL, MVT::i16, Promote);
325 setOperationAction(ISD::SDIV, MVT::i16, Promote);
326 setOperationAction(ISD::UDIV, MVT::i16, Promote);
327 setOperationAction(ISD::SREM, MVT::i16, Promote);
328 setOperationAction(ISD::UREM, MVT::i16, Promote);
330 setOperationAction(ISD::BSWAP, MVT::i16, Promote);
331 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
333 setOperationAction(ISD::CTTZ, MVT::i16, Promote);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
335 setOperationAction(ISD::CTLZ, MVT::i16, Promote);
336 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
338 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
340 setOperationAction(ISD::BR_CC, MVT::i16, Expand);
342 setOperationAction(ISD::LOAD, MVT::i16, Custom);
344 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
346 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
347 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
348 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
349 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
351 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
352 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
353 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
354 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
356 // F16 - Constant Actions.
357 setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
359 // F16 - Load/Store Actions.
360 setOperationAction(ISD::LOAD, MVT::f16, Promote);
361 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
362 setOperationAction(ISD::STORE, MVT::f16, Promote);
363 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
365 // F16 - VOP1 Actions.
366 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
367 setOperationAction(ISD::FCOS, MVT::f16, Promote);
368 setOperationAction(ISD::FSIN, MVT::f16, Promote);
369 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
370 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
371 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
372 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
373 setOperationAction(ISD::FROUND, MVT::f16, Custom);
375 // F16 - VOP2 Actions.
376 setOperationAction(ISD::BR_CC, MVT::f16, Expand);
377 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
378 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
379 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
380 setOperationAction(ISD::FDIV, MVT::f16, Custom);
382 // F16 - VOP3 Actions.
383 setOperationAction(ISD::FMA, MVT::f16, Legal);
384 if (!Subtarget->hasFP16Denormals())
385 setOperationAction(ISD::FMAD, MVT::f16, Legal);
388 if (Subtarget->hasVOP3PInsts()) {
389 for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
390 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
394 case ISD::BUILD_VECTOR:
396 case ISD::EXTRACT_VECTOR_ELT:
397 case ISD::INSERT_VECTOR_ELT:
398 case ISD::INSERT_SUBVECTOR:
399 case ISD::EXTRACT_SUBVECTOR:
400 case ISD::SCALAR_TO_VECTOR:
402 case ISD::CONCAT_VECTORS:
403 setOperationAction(Op, VT, Custom);
406 setOperationAction(Op, VT, Expand);
412 // XXX - Do these do anything? Vector constants turn into build_vector.
413 setOperationAction(ISD::Constant, MVT::v2i16, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
416 setOperationAction(ISD::STORE, MVT::v2i16, Promote);
417 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
418 setOperationAction(ISD::STORE, MVT::v2f16, Promote);
419 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
421 setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
422 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
423 setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
424 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
426 setOperationAction(ISD::AND, MVT::v2i16, Promote);
427 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
428 setOperationAction(ISD::OR, MVT::v2i16, Promote);
429 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
430 setOperationAction(ISD::XOR, MVT::v2i16, Promote);
431 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
432 setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
433 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
434 setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
435 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
437 setOperationAction(ISD::ADD, MVT::v2i16, Legal);
438 setOperationAction(ISD::SUB, MVT::v2i16, Legal);
439 setOperationAction(ISD::MUL, MVT::v2i16, Legal);
440 setOperationAction(ISD::SHL, MVT::v2i16, Legal);
441 setOperationAction(ISD::SRL, MVT::v2i16, Legal);
442 setOperationAction(ISD::SRA, MVT::v2i16, Legal);
443 setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
444 setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
445 setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
446 setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
448 setOperationAction(ISD::FADD, MVT::v2f16, Legal);
449 setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
450 setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
451 setOperationAction(ISD::FMA, MVT::v2f16, Legal);
452 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
453 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
455 // This isn't really legal, but this avoids the legalizer unrolling it (and
456 // allows matching fneg (fabs x) patterns)
457 setOperationAction(ISD::FABS, MVT::v2f16, Legal);
459 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
460 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
462 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
463 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
464 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
466 setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
467 setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
470 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
471 setOperationAction(ISD::SELECT, VT, Custom);
474 setTargetDAGCombine(ISD::FADD);
475 setTargetDAGCombine(ISD::FSUB);
476 setTargetDAGCombine(ISD::FMINNUM);
477 setTargetDAGCombine(ISD::FMAXNUM);
478 setTargetDAGCombine(ISD::SMIN);
479 setTargetDAGCombine(ISD::SMAX);
480 setTargetDAGCombine(ISD::UMIN);
481 setTargetDAGCombine(ISD::UMAX);
482 setTargetDAGCombine(ISD::SETCC);
483 setTargetDAGCombine(ISD::AND);
484 setTargetDAGCombine(ISD::OR);
485 setTargetDAGCombine(ISD::XOR);
486 setTargetDAGCombine(ISD::SINT_TO_FP);
487 setTargetDAGCombine(ISD::UINT_TO_FP);
488 setTargetDAGCombine(ISD::FCANONICALIZE);
489 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
490 setTargetDAGCombine(ISD::ZERO_EXTEND);
492 // All memory operations. Some folding on the pointer operand is done to help
493 // matching the constant offsets in the addressing modes.
494 setTargetDAGCombine(ISD::LOAD);
495 setTargetDAGCombine(ISD::STORE);
496 setTargetDAGCombine(ISD::ATOMIC_LOAD);
497 setTargetDAGCombine(ISD::ATOMIC_STORE);
498 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
499 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
500 setTargetDAGCombine(ISD::ATOMIC_SWAP);
501 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
502 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
503 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
504 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
505 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
506 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
507 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
508 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
509 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
510 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
512 setSchedulingPreference(Sched::RegPressure);
515 const SISubtarget *SITargetLowering::getSubtarget() const {
516 return static_cast<const SISubtarget *>(Subtarget);
519 //===----------------------------------------------------------------------===//
520 // TargetLowering queries
521 //===----------------------------------------------------------------------===//
523 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
525 // SI has some legal vector types, but no legal vector operations. Say no
526 // shuffles are legal in order to prefer scalarizing some vector operations.
530 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
532 unsigned IntrID) const {
534 case Intrinsic::amdgcn_atomic_inc:
535 case Intrinsic::amdgcn_atomic_dec: {
536 Info.opc = ISD::INTRINSIC_W_CHAIN;
537 Info.memVT = MVT::getVT(CI.getType());
538 Info.ptrVal = CI.getOperand(0);
541 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
542 Info.vol = !Vol || !Vol->isNullValue();
544 Info.writeMem = true;
552 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
553 SmallVectorImpl<Value*> &Ops,
554 Type *&AccessTy) const {
555 switch (II->getIntrinsicID()) {
556 case Intrinsic::amdgcn_atomic_inc:
557 case Intrinsic::amdgcn_atomic_dec: {
558 Value *Ptr = II->getArgOperand(0);
559 AccessTy = II->getType();
568 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
569 // Flat instructions do not have offsets, and only have the register
571 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
574 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
575 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
576 // additionally can do r + r + i with addr64. 32-bit has more addressing
577 // mode options. Depending on the resource constant, it can also do
578 // (i64 r0) + (i32 r1) * (i14 i).
580 // Private arrays end up using a scratch buffer most of the time, so also
581 // assume those use MUBUF instructions. Scratch loads / stores are currently
582 // implemented as mubuf instructions with offen bit set, so slightly
583 // different than the normal addr64.
584 if (!isUInt<12>(AM.BaseOffs))
587 // FIXME: Since we can split immediate into soffset and immediate offset,
588 // would it make sense to allow any immediate?
591 case 0: // r + i or just i, depending on HasBaseReg.
594 return true; // We have r + r or r + i.
601 // Allow 2 * r as r + r
602 // Or 2 * r + i is allowed as r + r + i.
604 default: // Don't allow n * r
609 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
610 const AddrMode &AM, Type *Ty,
612 // No global is ever allowed as a base.
616 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
617 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
618 // Assume the we will use FLAT for all global memory accesses
620 // FIXME: This assumption is currently wrong. On VI we still use
621 // MUBUF instructions for the r + i addressing mode. As currently
622 // implemented, the MUBUF instructions only work on buffer < 4GB.
623 // It may be possible to support > 4GB buffers with MUBUF instructions,
624 // by setting the stride value in the resource descriptor which would
625 // increase the size limit to (stride * 4GB). However, this is risky,
626 // because it has never been validated.
627 return isLegalFlatAddressingMode(AM);
630 return isLegalMUBUFAddressingMode(AM);
631 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
632 // If the offset isn't a multiple of 4, it probably isn't going to be
633 // correctly aligned.
634 // FIXME: Can we get the real alignment here?
635 if (AM.BaseOffs % 4 != 0)
636 return isLegalMUBUFAddressingMode(AM);
638 // There are no SMRD extloads, so if we have to do a small type access we
639 // will use a MUBUF load.
640 // FIXME?: We also need to do this if unaligned, but we don't know the
642 if (DL.getTypeStoreSize(Ty) < 4)
643 return isLegalMUBUFAddressingMode(AM);
645 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
646 // SMRD instructions have an 8-bit, dword offset on SI.
647 if (!isUInt<8>(AM.BaseOffs / 4))
649 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
650 // On CI+, this can also be a 32-bit literal constant offset. If it fits
651 // in 8-bits, it can use a smaller encoding.
652 if (!isUInt<32>(AM.BaseOffs / 4))
654 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
655 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
656 if (!isUInt<20>(AM.BaseOffs))
659 llvm_unreachable("unhandled generation");
661 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
664 if (AM.Scale == 1 && AM.HasBaseReg)
669 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
670 return isLegalMUBUFAddressingMode(AM);
671 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
672 AS == AMDGPUASI.REGION_ADDRESS) {
673 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
675 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
676 // an 8-bit dword offset but we don't know the alignment here.
677 if (!isUInt<16>(AM.BaseOffs))
680 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
683 if (AM.Scale == 1 && AM.HasBaseReg)
687 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
688 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
689 // For an unknown address space, this usually means that this is for some
690 // reason being used for pure arithmetic, and not based on some addressing
691 // computation. We don't have instructions that compute pointers with any
692 // addressing modes, so treat them as having no offset like flat
694 return isLegalFlatAddressingMode(AM);
696 llvm_unreachable("unhandled address space");
700 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
703 bool *IsFast) const {
707 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
708 // which isn't a simple VT.
709 // Until MVT is extended to handle this, simply check for the size and
710 // rely on the condition below: allow accesses if the size is a multiple of 4.
711 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
712 VT.getStoreSize() > 16)) {
716 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
717 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
718 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
719 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
720 // with adjacent offsets.
721 bool AlignedBy4 = (Align % 4 == 0);
723 *IsFast = AlignedBy4;
728 // FIXME: We have to be conservative here and assume that flat operations
729 // will access scratch. If we had access to the IR function, then we
730 // could determine if any private memory was used in the function.
731 if (!Subtarget->hasUnalignedScratchAccess() &&
732 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
733 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
737 if (Subtarget->hasUnalignedBufferAccess()) {
738 // If we have an uniform constant load, it still requires using a slow
739 // buffer instruction if unaligned.
741 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
742 (Align % 4 == 0) : true;
748 // Smaller than dword value must be aligned.
749 if (VT.bitsLT(MVT::i32))
752 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
753 // byte-address are ignored, thus forcing Dword alignment.
754 // This applies to private, global, and constant memory.
758 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
761 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
762 unsigned SrcAlign, bool IsMemset,
765 MachineFunction &MF) const {
766 // FIXME: Should account for address space here.
768 // The default fallback uses the private pointer size as a guess for a type to
769 // use. Make sure we switch these to 64-bit accesses.
771 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
774 if (Size >= 8 && DstAlign >= 4)
781 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
782 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
783 AS == AMDGPUASI.FLAT_ADDRESS ||
784 AS == AMDGPUASI.CONSTANT_ADDRESS;
787 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
788 unsigned DestAS) const {
789 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
790 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
793 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
794 const MemSDNode *MemNode = cast<MemSDNode>(N);
795 const Value *Ptr = MemNode->getMemOperand()->getValue();
796 const Instruction *I = dyn_cast<Instruction>(Ptr);
797 return I && I->getMetadata("amdgpu.noclobber");
800 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
801 unsigned DestAS) const {
802 // Flat -> private/local is a simple truncate.
803 // Flat -> global is no-op
804 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
807 return isNoopAddrSpaceCast(SrcAS, DestAS);
810 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
811 const MemSDNode *MemNode = cast<MemSDNode>(N);
813 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
816 TargetLoweringBase::LegalizeTypeAction
817 SITargetLowering::getPreferredVectorAction(EVT VT) const {
818 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
819 return TypeSplitVector;
821 return TargetLoweringBase::getPreferredVectorAction(VT);
824 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
826 // FIXME: Could be smarter if called for vector constants.
830 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
831 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
836 // These operations are done with 32-bit instructions anyway.
848 // SimplifySetCC uses this function to determine whether or not it should
849 // create setcc with i1 operands. We don't have instructions for i1 setcc.
850 if (VT == MVT::i1 && Op == ISD::SETCC)
853 return TargetLowering::isTypeDesirableForOp(Op, VT);
856 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
859 uint64_t Offset) const {
860 const DataLayout &DL = DAG.getDataLayout();
861 MachineFunction &MF = DAG.getMachineFunction();
862 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
863 unsigned InputPtrReg = TRI->getPreloadedValue(MF,
864 SIRegisterInfo::KERNARG_SEGMENT_PTR);
866 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
867 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
868 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
869 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
870 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
871 DAG.getConstant(Offset, SL, PtrVT));
874 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
875 const SDLoc &SL, SDValue Val,
877 const ISD::InputArg *Arg) const {
878 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
880 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
881 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
884 if (MemVT.isFloatingPoint())
885 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
887 Val = DAG.getSExtOrTrunc(Val, SL, VT);
889 Val = DAG.getZExtOrTrunc(Val, SL, VT);
894 SDValue SITargetLowering::lowerKernargMemParameter(
895 SelectionDAG &DAG, EVT VT, EVT MemVT,
896 const SDLoc &SL, SDValue Chain,
897 uint64_t Offset, bool Signed,
898 const ISD::InputArg *Arg) const {
899 const DataLayout &DL = DAG.getDataLayout();
900 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
901 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
902 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
904 unsigned Align = DL.getABITypeAlignment(Ty);
906 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
907 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
908 MachineMemOperand::MONonTemporal |
909 MachineMemOperand::MODereferenceable |
910 MachineMemOperand::MOInvariant);
912 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
913 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
916 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
917 CallingConv::ID CallConv,
918 ArrayRef<ISD::InputArg> Ins,
921 SIMachineFunctionInfo *Info) {
922 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
923 const ISD::InputArg &Arg = Ins[I];
925 // First check if it's a PS input addr.
926 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
927 !Arg.Flags.isByVal() && PSInputNum <= 15) {
929 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
930 // We can safely skip PS inputs.
936 Info->markPSInputAllocated(PSInputNum);
938 Info->markPSInputEnabled(PSInputNum);
943 // Second split vertices into their elements.
944 if (Arg.VT.isVector()) {
945 ISD::InputArg NewArg = Arg;
946 NewArg.Flags.setSplit();
947 NewArg.VT = Arg.VT.getVectorElementType();
949 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
950 // three or five element vertex only needs three or five registers,
951 // NOT four or eight.
952 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
953 unsigned NumElements = ParamType->getVectorNumElements();
955 for (unsigned J = 0; J != NumElements; ++J) {
956 Splits.push_back(NewArg);
957 NewArg.PartOffset += NewArg.VT.getStoreSize();
960 Splits.push_back(Arg);
965 // Allocate special inputs passed in VGPRs.
966 static void allocateSpecialInputVGPRs(CCState &CCInfo,
968 const SIRegisterInfo &TRI,
969 SIMachineFunctionInfo &Info) {
970 if (Info.hasWorkItemIDX()) {
971 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
972 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
973 CCInfo.AllocateReg(Reg);
976 if (Info.hasWorkItemIDY()) {
977 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
978 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
979 CCInfo.AllocateReg(Reg);
982 if (Info.hasWorkItemIDZ()) {
983 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
984 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
985 CCInfo.AllocateReg(Reg);
989 // Allocate special inputs passed in user SGPRs.
990 static void allocateHSAUserSGPRs(CCState &CCInfo,
992 const SIRegisterInfo &TRI,
993 SIMachineFunctionInfo &Info) {
994 if (Info.hasPrivateMemoryInputPtr()) {
995 unsigned PrivateMemoryPtrReg = Info.addPrivateMemoryPtr(TRI);
996 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SGPR_64RegClass);
997 CCInfo.AllocateReg(PrivateMemoryPtrReg);
1000 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1001 if (Info.hasPrivateSegmentBuffer()) {
1002 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1003 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1004 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1007 if (Info.hasDispatchPtr()) {
1008 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1009 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1010 CCInfo.AllocateReg(DispatchPtrReg);
1013 if (Info.hasQueuePtr()) {
1014 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1015 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1016 CCInfo.AllocateReg(QueuePtrReg);
1019 if (Info.hasKernargSegmentPtr()) {
1020 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1021 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1022 CCInfo.AllocateReg(InputPtrReg);
1025 if (Info.hasDispatchID()) {
1026 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1027 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1028 CCInfo.AllocateReg(DispatchIDReg);
1031 if (Info.hasFlatScratchInit()) {
1032 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1033 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1034 CCInfo.AllocateReg(FlatScratchInitReg);
1037 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1038 // these from the dispatch pointer.
1041 // Allocate special input registers that are initialized per-wave.
1042 static void allocateSystemSGPRs(CCState &CCInfo,
1043 MachineFunction &MF,
1044 SIMachineFunctionInfo &Info,
1046 if (Info.hasWorkGroupIDX()) {
1047 unsigned Reg = Info.addWorkGroupIDX();
1048 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1049 CCInfo.AllocateReg(Reg);
1052 if (Info.hasWorkGroupIDY()) {
1053 unsigned Reg = Info.addWorkGroupIDY();
1054 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1055 CCInfo.AllocateReg(Reg);
1058 if (Info.hasWorkGroupIDZ()) {
1059 unsigned Reg = Info.addWorkGroupIDZ();
1060 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1061 CCInfo.AllocateReg(Reg);
1064 if (Info.hasWorkGroupInfo()) {
1065 unsigned Reg = Info.addWorkGroupInfo();
1066 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1067 CCInfo.AllocateReg(Reg);
1070 if (Info.hasPrivateSegmentWaveByteOffset()) {
1071 // Scratch wave offset passed in system SGPR.
1072 unsigned PrivateSegmentWaveByteOffsetReg;
1075 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1076 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1078 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1080 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1081 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1085 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1086 MachineFunction &MF,
1087 const SIRegisterInfo &TRI,
1088 SIMachineFunctionInfo &Info) {
1089 // Now that we've figured out where the scratch register inputs are, see if
1090 // should reserve the arguments and use them directly.
1091 bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1093 // Record that we know we have non-spill stack objects so we don't need to
1094 // check all stack objects later.
1095 if (HasStackObjects)
1096 Info.setHasNonSpillStackObjects(true);
1098 // Everything live out of a block is spilled with fast regalloc, so it's
1099 // almost certain that spilling will be required.
1100 if (TM.getOptLevel() == CodeGenOpt::None)
1101 HasStackObjects = true;
1103 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1104 if (ST.isAmdCodeObjectV2(MF)) {
1105 if (HasStackObjects) {
1106 // If we have stack objects, we unquestionably need the private buffer
1107 // resource. For the Code Object V2 ABI, this will be the first 4 user
1108 // SGPR inputs. We can reserve those and use them directly.
1110 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue(
1111 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1112 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1114 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue(
1115 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1116 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1118 unsigned ReservedBufferReg
1119 = TRI.reservedPrivateSegmentBufferReg(MF);
1120 unsigned ReservedOffsetReg
1121 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1123 // We tentatively reserve the last registers (skipping the last two
1124 // which may contain VCC). After register allocation, we'll replace
1125 // these with the ones immediately after those which were really
1126 // allocated. In the prologue copies will be inserted from the argument
1127 // to these reserved registers.
1128 Info.setScratchRSrcReg(ReservedBufferReg);
1129 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1132 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1134 // Without HSA, relocations are used for the scratch pointer and the
1135 // buffer resource setup is always inserted in the prologue. Scratch wave
1136 // offset is still in an input SGPR.
1137 Info.setScratchRSrcReg(ReservedBufferReg);
1139 if (HasStackObjects) {
1140 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue(
1141 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1142 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1144 unsigned ReservedOffsetReg
1145 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1146 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1151 SDValue SITargetLowering::LowerFormalArguments(
1152 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1153 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1154 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1155 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1157 MachineFunction &MF = DAG.getMachineFunction();
1158 FunctionType *FType = MF.getFunction()->getFunctionType();
1159 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1160 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1162 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1163 const Function *Fn = MF.getFunction();
1164 DiagnosticInfoUnsupported NoGraphicsHSA(
1165 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1166 DAG.getContext()->diagnose(NoGraphicsHSA);
1167 return DAG.getEntryNode();
1170 // Create stack objects that are used for emitting debugger prologue if
1171 // "amdgpu-debugger-emit-prologue" attribute was specified.
1172 if (ST.debuggerEmitPrologue())
1173 createDebuggerPrologueStackObjects(MF);
1175 SmallVector<ISD::InputArg, 16> Splits;
1176 SmallVector<CCValAssign, 16> ArgLocs;
1177 BitVector Skipped(Ins.size());
1178 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1181 bool IsShader = AMDGPU::isShader(CallConv);
1182 bool IsKernel = AMDGPU::isKernel(CallConv);
1183 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1186 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1188 // At least one interpolation mode must be enabled or else the GPU will
1191 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1192 // set PSInputAddr, the user wants to enable some bits after the compilation
1193 // based on run-time states. Since we can't know what the final PSInputEna
1194 // will look like, so we shouldn't do anything here and the user should take
1195 // responsibility for the correct programming.
1197 // Otherwise, the following restrictions apply:
1198 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1199 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1201 if (CallConv == CallingConv::AMDGPU_PS &&
1202 ((Info->getPSInputAddr() & 0x7F) == 0 ||
1203 ((Info->getPSInputAddr() & 0xF) == 0 &&
1204 Info->isPSInputAllocated(11)))) {
1205 CCInfo.AllocateReg(AMDGPU::VGPR0);
1206 CCInfo.AllocateReg(AMDGPU::VGPR1);
1207 Info->markPSInputAllocated(0);
1208 Info->markPSInputEnabled(0);
1211 assert(!Info->hasDispatchPtr() &&
1212 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1213 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1214 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1215 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1216 !Info->hasWorkItemIDZ());
1218 assert(!IsKernel || (Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()));
1222 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1223 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1227 analyzeFormalArgumentsCompute(CCInfo, Ins);
1229 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1230 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1233 SmallVector<SDValue, 16> Chains;
1235 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1236 const ISD::InputArg &Arg = Ins[i];
1238 InVals.push_back(DAG.getUNDEF(Arg.VT));
1242 CCValAssign &VA = ArgLocs[ArgIdx++];
1243 MVT VT = VA.getLocVT();
1245 if (IsEntryFunc && VA.isMemLoc()) {
1247 EVT MemVT = VA.getLocVT();
1249 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1250 VA.getLocMemOffset();
1251 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1253 // The first 36 bytes of the input buffer contains information about
1254 // thread group and global sizes.
1255 SDValue Arg = lowerKernargMemParameter(
1256 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1257 Chains.push_back(Arg.getValue(1));
1260 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1261 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1262 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1263 // On SI local pointers are just offsets into LDS, so they are always
1264 // less than 16-bits. On CI and newer they could potentially be
1265 // real pointers, so we can't guarantee their size.
1266 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1267 DAG.getValueType(MVT::i16));
1270 InVals.push_back(Arg);
1275 report_fatal_error("memloc not supported with calling convention");
1277 assert(VA.isRegLoc() && "Parameter must be in a register!");
1279 unsigned Reg = VA.getLocReg();
1280 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1282 Reg = MF.addLiveIn(Reg, RC);
1283 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1285 if (Arg.VT.isVector()) {
1286 // Build a vector from the registers
1287 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1288 unsigned NumElements = ParamType->getVectorNumElements();
1290 SmallVector<SDValue, 4> Regs;
1291 Regs.push_back(Val);
1292 for (unsigned j = 1; j != NumElements; ++j) {
1293 Reg = ArgLocs[ArgIdx++].getLocReg();
1294 Reg = MF.addLiveIn(Reg, RC);
1296 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1297 Regs.push_back(Copy);
1300 // Fill up the missing vector elements
1301 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1302 Regs.append(NumElements, DAG.getUNDEF(VT));
1304 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1308 InVals.push_back(Val);
1311 // Start adding system SGPRs.
1313 allocateSystemSGPRs(CCInfo, MF, *Info, IsShader);
1315 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
1317 return Chains.empty() ? Chain :
1318 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1322 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1324 const SmallVectorImpl<ISD::OutputArg> &Outs,
1325 const SmallVectorImpl<SDValue> &OutVals,
1326 const SDLoc &DL, SelectionDAG &DAG) const {
1327 MachineFunction &MF = DAG.getMachineFunction();
1328 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1330 if (!AMDGPU::isShader(CallConv))
1331 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1334 Info->setIfReturnsVoid(Outs.size() == 0);
1336 SmallVector<ISD::OutputArg, 48> Splits;
1337 SmallVector<SDValue, 48> SplitVals;
1339 // Split vectors into their elements.
1340 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1341 const ISD::OutputArg &Out = Outs[i];
1343 if (Out.VT.isVector()) {
1344 MVT VT = Out.VT.getVectorElementType();
1345 ISD::OutputArg NewOut = Out;
1346 NewOut.Flags.setSplit();
1349 // We want the original number of vector elements here, e.g.
1350 // three or five, not four or eight.
1351 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1353 for (unsigned j = 0; j != NumElements; ++j) {
1354 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1355 DAG.getConstant(j, DL, MVT::i32));
1356 SplitVals.push_back(Elem);
1357 Splits.push_back(NewOut);
1358 NewOut.PartOffset += NewOut.VT.getStoreSize();
1361 SplitVals.push_back(OutVals[i]);
1362 Splits.push_back(Out);
1366 // CCValAssign - represent the assignment of the return value to a location.
1367 SmallVector<CCValAssign, 48> RVLocs;
1369 // CCState - Info about the registers and stack slots.
1370 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1373 // Analyze outgoing return values.
1374 AnalyzeReturn(CCInfo, Splits);
1377 SmallVector<SDValue, 48> RetOps;
1378 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1380 // Copy the result values into the output registers.
1381 for (unsigned i = 0, realRVLocIdx = 0;
1383 ++i, ++realRVLocIdx) {
1384 CCValAssign &VA = RVLocs[i];
1385 assert(VA.isRegLoc() && "Can only return in registers!");
1387 SDValue Arg = SplitVals[realRVLocIdx];
1389 // Copied from other backends.
1390 switch (VA.getLocInfo()) {
1391 default: llvm_unreachable("Unknown loc info!");
1392 case CCValAssign::Full:
1394 case CCValAssign::BCvt:
1395 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1399 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1400 Flag = Chain.getValue(1);
1401 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1404 // Update chain and glue.
1407 RetOps.push_back(Flag);
1409 unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN_TO_EPILOG;
1410 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1413 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1414 SelectionDAG &DAG) const {
1415 unsigned Reg = StringSwitch<unsigned>(RegName)
1416 .Case("m0", AMDGPU::M0)
1417 .Case("exec", AMDGPU::EXEC)
1418 .Case("exec_lo", AMDGPU::EXEC_LO)
1419 .Case("exec_hi", AMDGPU::EXEC_HI)
1420 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1421 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1422 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1423 .Default(AMDGPU::NoRegister);
1425 if (Reg == AMDGPU::NoRegister) {
1426 report_fatal_error(Twine("invalid register name \""
1427 + StringRef(RegName) + "\"."));
1431 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1432 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1433 report_fatal_error(Twine("invalid register \""
1434 + StringRef(RegName) + "\" for subtarget."));
1439 case AMDGPU::EXEC_LO:
1440 case AMDGPU::EXEC_HI:
1441 case AMDGPU::FLAT_SCR_LO:
1442 case AMDGPU::FLAT_SCR_HI:
1443 if (VT.getSizeInBits() == 32)
1447 case AMDGPU::FLAT_SCR:
1448 if (VT.getSizeInBits() == 64)
1452 llvm_unreachable("missing register type checking");
1455 report_fatal_error(Twine("invalid type for register \""
1456 + StringRef(RegName) + "\"."));
1459 // If kill is not the last instruction, split the block so kill is always a
1460 // proper terminator.
1461 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1462 MachineBasicBlock *BB) const {
1463 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1465 MachineBasicBlock::iterator SplitPoint(&MI);
1468 if (SplitPoint == BB->end()) {
1469 // Don't bother with a new block.
1470 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1474 MachineFunction *MF = BB->getParent();
1475 MachineBasicBlock *SplitBB
1476 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1478 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1479 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1481 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1482 BB->addSuccessor(SplitBB);
1484 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1488 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1489 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1490 // will only do one iteration. In the worst case, this will loop 64 times.
1492 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1493 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1494 const SIInstrInfo *TII,
1495 MachineRegisterInfo &MRI,
1496 MachineBasicBlock &OrigBB,
1497 MachineBasicBlock &LoopBB,
1499 const MachineOperand &IdxReg,
1503 unsigned InitSaveExecReg,
1505 bool UseGPRIdxMode) {
1506 MachineBasicBlock::iterator I = LoopBB.begin();
1508 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1509 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1510 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1511 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1513 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1519 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1520 .addReg(InitSaveExecReg)
1525 // Read the next variant <- also loop target.
1526 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1527 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1529 // Compare the just read M0 value to all possible Idx values.
1530 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1531 .addReg(CurrentIdxReg)
1532 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1534 if (UseGPRIdxMode) {
1537 IdxReg = CurrentIdxReg;
1539 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1540 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1541 .addReg(CurrentIdxReg, RegState::Kill)
1545 MachineInstr *SetIdx =
1546 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1547 .addReg(IdxReg, RegState::Kill);
1548 SetIdx->getOperand(2).setIsUndef();
1550 // Move index from VCC into M0
1552 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1553 .addReg(CurrentIdxReg, RegState::Kill);
1555 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1556 .addReg(CurrentIdxReg, RegState::Kill)
1561 // Update EXEC, save the original EXEC value to VCC.
1562 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1563 .addReg(CondReg, RegState::Kill);
1565 MRI.setSimpleHint(NewExec, CondReg);
1567 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1568 MachineInstr *InsertPt =
1569 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1570 .addReg(AMDGPU::EXEC)
1573 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1576 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1577 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1580 return InsertPt->getIterator();
1583 // This has slightly sub-optimal regalloc when the source vector is killed by
1584 // the read. The register allocator does not understand that the kill is
1585 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1586 // subregister from it, using 1 more VGPR than necessary. This was saved when
1587 // this was expanded after register allocation.
1588 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1589 MachineBasicBlock &MBB,
1591 unsigned InitResultReg,
1594 bool UseGPRIdxMode) {
1595 MachineFunction *MF = MBB.getParent();
1596 MachineRegisterInfo &MRI = MF->getRegInfo();
1597 const DebugLoc &DL = MI.getDebugLoc();
1598 MachineBasicBlock::iterator I(&MI);
1600 unsigned DstReg = MI.getOperand(0).getReg();
1601 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1602 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1604 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1606 // Save the EXEC mask
1607 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1608 .addReg(AMDGPU::EXEC);
1610 // To insert the loop we need to split the block. Move everything after this
1611 // point to a new block, and insert a new empty block between the two.
1612 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1613 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1614 MachineFunction::iterator MBBI(MBB);
1617 MF->insert(MBBI, LoopBB);
1618 MF->insert(MBBI, RemainderBB);
1620 LoopBB->addSuccessor(LoopBB);
1621 LoopBB->addSuccessor(RemainderBB);
1623 // Move the rest of the block into a new block.
1624 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1625 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1627 MBB.addSuccessor(LoopBB);
1629 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1631 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1632 InitResultReg, DstReg, PhiReg, TmpExec,
1633 Offset, UseGPRIdxMode);
1635 MachineBasicBlock::iterator First = RemainderBB->begin();
1636 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1642 // Returns subreg index, offset
1643 static std::pair<unsigned, int>
1644 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1645 const TargetRegisterClass *SuperRC,
1648 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
1650 // Skip out of bounds offsets, or else we would end up using an undefined
1652 if (Offset >= NumElts || Offset < 0)
1653 return std::make_pair(AMDGPU::sub0, Offset);
1655 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1658 // Return true if the index is an SGPR and was set.
1659 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1660 MachineRegisterInfo &MRI,
1664 bool IsIndirectSrc) {
1665 MachineBasicBlock *MBB = MI.getParent();
1666 const DebugLoc &DL = MI.getDebugLoc();
1667 MachineBasicBlock::iterator I(&MI);
1669 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1670 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1672 assert(Idx->getReg() != AMDGPU::NoRegister);
1674 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1677 if (UseGPRIdxMode) {
1678 unsigned IdxMode = IsIndirectSrc ?
1679 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1681 MachineInstr *SetOn =
1682 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1686 SetOn->getOperand(3).setIsUndef();
1688 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1689 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1692 MachineInstr *SetOn =
1693 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1694 .addReg(Tmp, RegState::Kill)
1697 SetOn->getOperand(3).setIsUndef();
1704 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1707 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1715 // Control flow needs to be inserted if indexing with a VGPR.
1716 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1717 MachineBasicBlock &MBB,
1718 const SISubtarget &ST) {
1719 const SIInstrInfo *TII = ST.getInstrInfo();
1720 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1721 MachineFunction *MF = MBB.getParent();
1722 MachineRegisterInfo &MRI = MF->getRegInfo();
1724 unsigned Dst = MI.getOperand(0).getReg();
1725 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1726 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1728 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1731 std::tie(SubReg, Offset)
1732 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1734 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1736 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1737 MachineBasicBlock::iterator I(&MI);
1738 const DebugLoc &DL = MI.getDebugLoc();
1740 if (UseGPRIdxMode) {
1741 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1742 // to avoid interfering with other uses, so probably requires a new
1743 // optimization pass.
1744 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1745 .addReg(SrcReg, RegState::Undef, SubReg)
1746 .addReg(SrcReg, RegState::Implicit)
1747 .addReg(AMDGPU::M0, RegState::Implicit);
1748 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1750 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1751 .addReg(SrcReg, RegState::Undef, SubReg)
1752 .addReg(SrcReg, RegState::Implicit);
1755 MI.eraseFromParent();
1760 const DebugLoc &DL = MI.getDebugLoc();
1761 MachineBasicBlock::iterator I(&MI);
1763 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1764 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1766 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1768 if (UseGPRIdxMode) {
1769 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1770 .addImm(0) // Reset inside loop.
1771 .addImm(VGPRIndexMode::SRC0_ENABLE);
1772 SetOn->getOperand(3).setIsUndef();
1774 // Disable again after the loop.
1775 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1778 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1779 MachineBasicBlock *LoopBB = InsPt->getParent();
1781 if (UseGPRIdxMode) {
1782 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1783 .addReg(SrcReg, RegState::Undef, SubReg)
1784 .addReg(SrcReg, RegState::Implicit)
1785 .addReg(AMDGPU::M0, RegState::Implicit);
1787 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1788 .addReg(SrcReg, RegState::Undef, SubReg)
1789 .addReg(SrcReg, RegState::Implicit);
1792 MI.eraseFromParent();
1797 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
1798 const TargetRegisterClass *VecRC) {
1799 switch (TRI.getRegSizeInBits(*VecRC)) {
1801 return AMDGPU::V_MOVRELD_B32_V1;
1803 return AMDGPU::V_MOVRELD_B32_V2;
1804 case 128: // 16 bytes
1805 return AMDGPU::V_MOVRELD_B32_V4;
1806 case 256: // 32 bytes
1807 return AMDGPU::V_MOVRELD_B32_V8;
1808 case 512: // 64 bytes
1809 return AMDGPU::V_MOVRELD_B32_V16;
1811 llvm_unreachable("unsupported size for MOVRELD pseudos");
1815 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1816 MachineBasicBlock &MBB,
1817 const SISubtarget &ST) {
1818 const SIInstrInfo *TII = ST.getInstrInfo();
1819 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1820 MachineFunction *MF = MBB.getParent();
1821 MachineRegisterInfo &MRI = MF->getRegInfo();
1823 unsigned Dst = MI.getOperand(0).getReg();
1824 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1825 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1826 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1827 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1828 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1830 // This can be an immediate, but will be folded later.
1831 assert(Val->getReg());
1834 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1837 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1839 if (Idx->getReg() == AMDGPU::NoRegister) {
1840 MachineBasicBlock::iterator I(&MI);
1841 const DebugLoc &DL = MI.getDebugLoc();
1843 assert(Offset == 0);
1845 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1850 MI.eraseFromParent();
1854 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1855 MachineBasicBlock::iterator I(&MI);
1856 const DebugLoc &DL = MI.getDebugLoc();
1858 if (UseGPRIdxMode) {
1859 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1860 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1862 .addReg(Dst, RegState::ImplicitDefine)
1863 .addReg(SrcVec->getReg(), RegState::Implicit)
1864 .addReg(AMDGPU::M0, RegState::Implicit);
1866 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1868 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
1870 BuildMI(MBB, I, DL, MovRelDesc)
1871 .addReg(Dst, RegState::Define)
1872 .addReg(SrcVec->getReg())
1874 .addImm(SubReg - AMDGPU::sub0);
1877 MI.eraseFromParent();
1882 MRI.clearKillFlags(Val->getReg());
1884 const DebugLoc &DL = MI.getDebugLoc();
1886 if (UseGPRIdxMode) {
1887 MachineBasicBlock::iterator I(&MI);
1889 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1890 .addImm(0) // Reset inside loop.
1891 .addImm(VGPRIndexMode::DST_ENABLE);
1892 SetOn->getOperand(3).setIsUndef();
1894 // Disable again after the loop.
1895 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1898 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1900 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1901 Offset, UseGPRIdxMode);
1902 MachineBasicBlock *LoopBB = InsPt->getParent();
1904 if (UseGPRIdxMode) {
1905 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1906 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1908 .addReg(Dst, RegState::ImplicitDefine)
1909 .addReg(PhiReg, RegState::Implicit)
1910 .addReg(AMDGPU::M0, RegState::Implicit);
1912 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
1914 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1915 .addReg(Dst, RegState::Define)
1918 .addImm(SubReg - AMDGPU::sub0);
1921 MI.eraseFromParent();
1926 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1927 MachineInstr &MI, MachineBasicBlock *BB) const {
1929 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1930 MachineFunction *MF = BB->getParent();
1931 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1933 if (TII->isMIMG(MI)) {
1934 if (!MI.memoperands_empty())
1936 // Add a memoperand for mimg instructions so that they aren't assumed to
1937 // be ordered memory instuctions.
1939 MachinePointerInfo PtrInfo(MFI->getImagePSV());
1940 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
1942 Flags |= MachineMemOperand::MOStore;
1945 Flags |= MachineMemOperand::MOLoad;
1947 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
1948 MI.addMemOperand(*MF, MMO);
1952 switch (MI.getOpcode()) {
1953 case AMDGPU::SI_INIT_M0:
1954 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1955 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1956 .add(MI.getOperand(0));
1957 MI.eraseFromParent();
1960 case AMDGPU::SI_INIT_EXEC:
1961 // This should be before all vector instructions.
1962 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
1964 .addImm(MI.getOperand(0).getImm());
1965 MI.eraseFromParent();
1968 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
1969 // Extract the thread count from an SGPR input and set EXEC accordingly.
1970 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
1972 // S_BFE_U32 count, input, {shift, 7}
1973 // S_BFM_B64 exec, count, 0
1974 // S_CMP_EQ_U32 count, 64
1975 // S_CMOV_B64 exec, -1
1976 MachineInstr *FirstMI = &*BB->begin();
1977 MachineRegisterInfo &MRI = MF->getRegInfo();
1978 unsigned InputReg = MI.getOperand(0).getReg();
1979 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1982 // Move the COPY of the input reg to the beginning, so that we can use it.
1983 for (auto I = BB->begin(); I != &MI; I++) {
1984 if (I->getOpcode() != TargetOpcode::COPY ||
1985 I->getOperand(0).getReg() != InputReg)
1989 FirstMI = &*++BB->begin();
1991 I->removeFromParent();
1992 BB->insert(FirstMI, &*I);
1999 // This should be before all vector instructions.
2000 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
2002 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
2003 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
2007 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
2008 .addReg(CountReg, RegState::Kill)
2010 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
2013 MI.eraseFromParent();
2017 case AMDGPU::GET_GROUPSTATICSIZE: {
2018 DebugLoc DL = MI.getDebugLoc();
2019 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
2020 .add(MI.getOperand(0))
2021 .addImm(MFI->getLDSSize());
2022 MI.eraseFromParent();
2025 case AMDGPU::SI_INDIRECT_SRC_V1:
2026 case AMDGPU::SI_INDIRECT_SRC_V2:
2027 case AMDGPU::SI_INDIRECT_SRC_V4:
2028 case AMDGPU::SI_INDIRECT_SRC_V8:
2029 case AMDGPU::SI_INDIRECT_SRC_V16:
2030 return emitIndirectSrc(MI, *BB, *getSubtarget());
2031 case AMDGPU::SI_INDIRECT_DST_V1:
2032 case AMDGPU::SI_INDIRECT_DST_V2:
2033 case AMDGPU::SI_INDIRECT_DST_V4:
2034 case AMDGPU::SI_INDIRECT_DST_V8:
2035 case AMDGPU::SI_INDIRECT_DST_V16:
2036 return emitIndirectDst(MI, *BB, *getSubtarget());
2037 case AMDGPU::SI_KILL:
2038 return splitKillBlock(MI, BB);
2039 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
2040 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2042 unsigned Dst = MI.getOperand(0).getReg();
2043 unsigned Src0 = MI.getOperand(1).getReg();
2044 unsigned Src1 = MI.getOperand(2).getReg();
2045 const DebugLoc &DL = MI.getDebugLoc();
2046 unsigned SrcCond = MI.getOperand(3).getReg();
2048 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2049 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2051 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
2052 .addReg(Src0, 0, AMDGPU::sub0)
2053 .addReg(Src1, 0, AMDGPU::sub0)
2055 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
2056 .addReg(Src0, 0, AMDGPU::sub1)
2057 .addReg(Src1, 0, AMDGPU::sub1)
2060 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2062 .addImm(AMDGPU::sub0)
2064 .addImm(AMDGPU::sub1);
2065 MI.eraseFromParent();
2068 case AMDGPU::SI_BR_UNDEF: {
2069 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2070 const DebugLoc &DL = MI.getDebugLoc();
2071 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2072 .add(MI.getOperand(0));
2073 Br->getOperand(1).setIsUndef(true); // read undef SCC
2074 MI.eraseFromParent();
2078 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2082 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2083 // This currently forces unfolding various combinations of fsub into fma with
2084 // free fneg'd operands. As long as we have fast FMA (controlled by
2085 // isFMAFasterThanFMulAndFAdd), we should perform these.
2087 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2088 // most of these combines appear to be cycle neutral but save on instruction
2089 // count / code size.
2093 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2095 if (!VT.isVector()) {
2098 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2101 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2102 // TODO: Should i16 be used always if legal? For now it would force VALU
2104 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2107 // Answering this is somewhat tricky and depends on the specific device which
2108 // have different rates for fma or all f64 operations.
2110 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2111 // regardless of which device (although the number of cycles differs between
2112 // devices), so it is always profitable for f64.
2114 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2115 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2116 // which we can always do even without fused FP ops since it returns the same
2117 // result as the separate operations and since it is always full
2118 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2119 // however does not support denormals, so we do report fma as faster if we have
2120 // a fast fma device and require denormals.
2122 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2123 VT = VT.getScalarType();
2125 switch (VT.getSimpleVT().SimpleTy) {
2127 // This is as fast on some subtargets. However, we always have full rate f32
2128 // mad available which returns the same result as the separate operations
2129 // which we should prefer over fma. We can't use this if we want to support
2130 // denormals, so only report this in these cases.
2131 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2135 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2143 //===----------------------------------------------------------------------===//
2144 // Custom DAG Lowering Operations
2145 //===----------------------------------------------------------------------===//
2147 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2148 switch (Op.getOpcode()) {
2149 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2150 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2152 SDValue Result = LowerLOAD(Op, DAG);
2153 assert((!Result.getNode() ||
2154 Result.getNode()->getNumValues() == 2) &&
2155 "Load should return a value and a chain");
2161 return LowerTrig(Op, DAG);
2162 case ISD::SELECT: return LowerSELECT(Op, DAG);
2163 case ISD::FDIV: return LowerFDIV(Op, DAG);
2164 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2165 case ISD::STORE: return LowerSTORE(Op, DAG);
2166 case ISD::GlobalAddress: {
2167 MachineFunction &MF = DAG.getMachineFunction();
2168 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2169 return LowerGlobalAddress(MFI, Op, DAG);
2171 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2172 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2173 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2174 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2175 case ISD::INSERT_VECTOR_ELT:
2176 return lowerINSERT_VECTOR_ELT(Op, DAG);
2177 case ISD::EXTRACT_VECTOR_ELT:
2178 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2180 return lowerFP_ROUND(Op, DAG);
2183 case ISD::DEBUGTRAP:
2184 return lowerTRAP(Op, DAG);
2189 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2190 SmallVectorImpl<SDValue> &Results,
2191 SelectionDAG &DAG) const {
2192 switch (N->getOpcode()) {
2193 case ISD::INSERT_VECTOR_ELT: {
2194 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2195 Results.push_back(Res);
2198 case ISD::EXTRACT_VECTOR_ELT: {
2199 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2200 Results.push_back(Res);
2203 case ISD::INTRINSIC_WO_CHAIN: {
2204 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2206 case Intrinsic::amdgcn_cvt_pkrtz: {
2207 SDValue Src0 = N->getOperand(1);
2208 SDValue Src1 = N->getOperand(2);
2210 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2213 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2222 EVT VT = N->getValueType(0);
2223 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2224 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
2225 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
2227 EVT SelectVT = NewVT;
2228 if (NewVT.bitsLT(MVT::i32)) {
2229 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
2230 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
2231 SelectVT = MVT::i32;
2234 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
2235 N->getOperand(0), LHS, RHS);
2237 if (NewVT != SelectVT)
2238 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
2239 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
2247 /// \brief Helper function for LowerBRCOND
2248 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2250 SDNode *Parent = Value.getNode();
2251 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2254 if (I.getUse().get() != Value)
2257 if (I->getOpcode() == Opcode)
2263 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2264 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2265 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2266 case Intrinsic::amdgcn_if:
2267 return AMDGPUISD::IF;
2268 case Intrinsic::amdgcn_else:
2269 return AMDGPUISD::ELSE;
2270 case Intrinsic::amdgcn_loop:
2271 return AMDGPUISD::LOOP;
2272 case Intrinsic::amdgcn_end_cf:
2273 llvm_unreachable("should not occur");
2279 // break, if_break, else_break are all only used as inputs to loop, not
2280 // directly as branch conditions.
2284 void SITargetLowering::createDebuggerPrologueStackObjects(
2285 MachineFunction &MF) const {
2286 // Create stack objects that are used for emitting debugger prologue.
2288 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2289 // at fixed location in the following format:
2290 // offset 0: work group ID x
2291 // offset 4: work group ID y
2292 // offset 8: work group ID z
2293 // offset 16: work item ID x
2294 // offset 20: work item ID y
2295 // offset 24: work item ID z
2296 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2299 // For each dimension:
2300 for (unsigned i = 0; i < 3; ++i) {
2301 // Create fixed stack object for work group ID.
2302 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2303 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2304 // Create fixed stack object for work item ID.
2305 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2306 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2310 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2311 const Triple &TT = getTargetMachine().getTargetTriple();
2312 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2313 AMDGPU::shouldEmitConstantsToTextSection(TT);
2316 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2317 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2318 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2319 !shouldEmitFixup(GV) &&
2320 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2323 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2324 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2327 /// This transforms the control flow intrinsics to get the branch destination as
2328 /// last parameter, also switches branch target with BR if the need arise
2329 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2330 SelectionDAG &DAG) const {
2333 SDNode *Intr = BRCOND.getOperand(1).getNode();
2334 SDValue Target = BRCOND.getOperand(2);
2335 SDNode *BR = nullptr;
2336 SDNode *SetCC = nullptr;
2338 if (Intr->getOpcode() == ISD::SETCC) {
2339 // As long as we negate the condition everything is fine
2341 Intr = SetCC->getOperand(0).getNode();
2344 // Get the target from BR if we don't negate the condition
2345 BR = findUser(BRCOND, ISD::BR);
2346 Target = BR->getOperand(1);
2349 // FIXME: This changes the types of the intrinsics instead of introducing new
2350 // nodes with the correct types.
2351 // e.g. llvm.amdgcn.loop
2353 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2354 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2356 unsigned CFNode = isCFIntrinsic(Intr);
2358 // This is a uniform branch so we don't need to legalize.
2362 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2363 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2366 (SetCC->getConstantOperandVal(1) == 1 &&
2367 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2370 // operands of the new intrinsic call
2371 SmallVector<SDValue, 4> Ops;
2373 Ops.push_back(BRCOND.getOperand(0));
2375 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2376 Ops.push_back(Target);
2378 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2380 // build the new intrinsic call
2381 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2386 BRCOND.getOperand(0)
2389 Result = DAG.getMergeValues(Ops, DL).getNode();
2393 // Give the branch instruction our target
2396 BRCOND.getOperand(2)
2398 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2399 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2400 BR = NewBR.getNode();
2403 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2405 // Copy the intrinsic results to registers
2406 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2407 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2411 Chain = DAG.getCopyToReg(
2413 CopyToReg->getOperand(1),
2414 SDValue(Result, i - 1),
2417 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2420 // Remove the old intrinsic from the chain
2421 DAG.ReplaceAllUsesOfValueWith(
2422 SDValue(Intr, Intr->getNumValues() - 1),
2423 Intr->getOperand(0));
2428 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2432 return Op.getValueType().bitsLE(VT) ?
2433 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2434 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2437 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2438 assert(Op.getValueType() == MVT::f16 &&
2439 "Do not know how to custom lower FP_ROUND for non-f16 type");
2441 SDValue Src = Op.getOperand(0);
2442 EVT SrcVT = Src.getValueType();
2443 if (SrcVT != MVT::f64)
2448 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2449 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2450 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2453 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
2455 MachineFunction &MF = DAG.getMachineFunction();
2456 SDValue Chain = Op.getOperand(0);
2458 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
2459 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
2461 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
2462 Subtarget->isTrapHandlerEnabled()) {
2463 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2464 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2465 assert(UserSGPR != AMDGPU::NoRegister);
2467 SDValue QueuePtr = CreateLiveInRegister(
2468 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2470 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
2472 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
2473 QueuePtr, SDValue());
2477 DAG.getTargetConstant(TrapID, SL, MVT::i16),
2482 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
2486 case SISubtarget::TrapIDLLVMTrap:
2487 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
2488 case SISubtarget::TrapIDLLVMDebugTrap: {
2489 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2490 "debugtrap handler not supported",
2493 LLVMContext &Ctx = MF.getFunction()->getContext();
2494 Ctx.diagnose(NoTrap);
2498 llvm_unreachable("unsupported trap handler type!");
2504 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2505 SelectionDAG &DAG) const {
2506 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2507 if (Subtarget->hasApertureRegs()) {
2508 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2509 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2510 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2511 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2512 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2513 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2515 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2516 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2517 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2519 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2520 SDValue ApertureReg = SDValue(
2521 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2522 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2523 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2526 MachineFunction &MF = DAG.getMachineFunction();
2527 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2528 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2529 assert(UserSGPR != AMDGPU::NoRegister);
2531 SDValue QueuePtr = CreateLiveInRegister(
2532 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2534 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2535 // private_segment_aperture_base_hi.
2536 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2538 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2539 DAG.getConstant(StructOffset, DL, MVT::i64));
2541 // TODO: Use custom target PseudoSourceValue.
2542 // TODO: We should use the value from the IR intrinsic call, but it might not
2543 // be available and how do we get it?
2544 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2545 AMDGPUASI.CONSTANT_ADDRESS));
2547 MachinePointerInfo PtrInfo(V, StructOffset);
2548 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2549 MinAlign(64, StructOffset),
2550 MachineMemOperand::MODereferenceable |
2551 MachineMemOperand::MOInvariant);
2554 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2555 SelectionDAG &DAG) const {
2557 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2559 SDValue Src = ASC->getOperand(0);
2560 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2562 const AMDGPUTargetMachine &TM =
2563 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2565 // flat -> local/private
2566 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2567 unsigned DestAS = ASC->getDestAddressSpace();
2569 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2570 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2571 unsigned NullVal = TM.getNullPointerValue(DestAS);
2572 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2573 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2574 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2576 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2577 NonNull, Ptr, SegmentNullPtr);
2581 // local/private -> flat
2582 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2583 unsigned SrcAS = ASC->getSrcAddressSpace();
2585 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2586 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2587 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2588 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2591 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2593 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2595 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2597 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2598 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2603 // global <-> flat are no-ops and never emitted.
2605 const MachineFunction &MF = DAG.getMachineFunction();
2606 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2607 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2608 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2610 return DAG.getUNDEF(ASC->getValueType(0));
2613 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2614 SelectionDAG &DAG) const {
2615 SDValue Idx = Op.getOperand(2);
2616 if (isa<ConstantSDNode>(Idx))
2619 // Avoid stack access for dynamic indexing.
2621 SDValue Vec = Op.getOperand(0);
2622 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2624 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2625 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2627 // Convert vector index to bit-index.
2628 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2629 DAG.getConstant(16, SL, MVT::i32));
2631 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2633 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2634 DAG.getConstant(0xffff, SL, MVT::i32),
2637 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2638 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2639 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2641 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2642 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2645 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2646 SelectionDAG &DAG) const {
2649 EVT ResultVT = Op.getValueType();
2650 SDValue Vec = Op.getOperand(0);
2651 SDValue Idx = Op.getOperand(1);
2653 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2654 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2656 if (CIdx->getZExtValue() == 1) {
2657 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2658 DAG.getConstant(16, SL, MVT::i32));
2660 assert(CIdx->getZExtValue() == 0);
2663 if (ResultVT.bitsLT(MVT::i32))
2664 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2665 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2668 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2670 // Convert vector index to bit-index.
2671 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2673 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2674 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2676 SDValue Result = Elt;
2677 if (ResultVT.bitsLT(MVT::i32))
2678 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2680 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2684 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2685 // We can fold offsets for anything that doesn't require a GOT relocation.
2686 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2687 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2688 !shouldEmitGOTReloc(GA->getGlobal());
2692 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2693 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2694 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2695 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2696 // lowered to the following code sequence:
2698 // For constant address space:
2699 // s_getpc_b64 s[0:1]
2700 // s_add_u32 s0, s0, $symbol
2701 // s_addc_u32 s1, s1, 0
2703 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2704 // a fixup or relocation is emitted to replace $symbol with a literal
2705 // constant, which is a pc-relative offset from the encoding of the $symbol
2706 // operand to the global variable.
2708 // For global address space:
2709 // s_getpc_b64 s[0:1]
2710 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2711 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2713 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2714 // fixups or relocations are emitted to replace $symbol@*@lo and
2715 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2716 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2717 // operand to the global variable.
2719 // What we want here is an offset from the value returned by s_getpc
2720 // (which is the address of the s_add_u32 instruction) to the global
2721 // variable, but since the encoding of $symbol starts 4 bytes after the start
2722 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2723 // small. This requires us to add 4 to the global variable offset in order to
2724 // compute the correct address.
2725 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2727 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2728 GAFlags == SIInstrInfo::MO_NONE ?
2729 GAFlags : GAFlags + 1);
2730 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2733 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2735 SelectionDAG &DAG) const {
2736 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2738 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2739 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2740 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2743 const GlobalValue *GV = GSD->getGlobal();
2744 EVT PtrVT = Op.getValueType();
2746 if (shouldEmitFixup(GV))
2747 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2748 else if (shouldEmitPCReloc(GV))
2749 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2750 SIInstrInfo::MO_REL32);
2752 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2753 SIInstrInfo::MO_GOTPCREL32);
2755 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2756 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2757 const DataLayout &DataLayout = DAG.getDataLayout();
2758 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2759 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2760 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2762 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2763 MachineMemOperand::MODereferenceable |
2764 MachineMemOperand::MOInvariant);
2767 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2768 const SDLoc &DL, SDValue V) const {
2769 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2770 // the destination register.
2772 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2773 // so we will end up with redundant moves to m0.
2775 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2777 // A Null SDValue creates a glue result.
2778 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2780 return SDValue(M0, 0);
2783 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2786 unsigned Offset) const {
2788 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2789 DAG.getEntryNode(), Offset, false);
2790 // The local size values will have the hi 16-bits as zero.
2791 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2792 DAG.getValueType(VT));
2795 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2797 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2798 "non-hsa intrinsic with hsa target",
2800 DAG.getContext()->diagnose(BadIntrin);
2801 return DAG.getUNDEF(VT);
2804 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2806 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2807 "intrinsic not supported on subtarget",
2809 DAG.getContext()->diagnose(BadIntrin);
2810 return DAG.getUNDEF(VT);
2813 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2814 SelectionDAG &DAG) const {
2815 MachineFunction &MF = DAG.getMachineFunction();
2816 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2817 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2819 EVT VT = Op.getValueType();
2821 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2823 // TODO: Should this propagate fast-math-flags?
2825 switch (IntrinsicID) {
2826 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2827 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2828 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2830 case Intrinsic::amdgcn_dispatch_ptr:
2831 case Intrinsic::amdgcn_queue_ptr: {
2832 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2833 DiagnosticInfoUnsupported BadIntrin(
2834 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2836 DAG.getContext()->diagnose(BadIntrin);
2837 return DAG.getUNDEF(VT);
2840 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2841 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2842 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2843 TRI->getPreloadedValue(MF, Reg), VT);
2845 case Intrinsic::amdgcn_implicitarg_ptr: {
2846 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2847 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2849 case Intrinsic::amdgcn_kernarg_segment_ptr: {
2851 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2852 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2854 case Intrinsic::amdgcn_dispatch_id: {
2855 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2856 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2858 case Intrinsic::amdgcn_rcp:
2859 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2860 case Intrinsic::amdgcn_rsq:
2861 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2862 case Intrinsic::amdgcn_rsq_legacy:
2863 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2864 return emitRemovedIntrinsicError(DAG, DL, VT);
2866 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2867 case Intrinsic::amdgcn_rcp_legacy:
2868 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2869 return emitRemovedIntrinsicError(DAG, DL, VT);
2870 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2871 case Intrinsic::amdgcn_rsq_clamp: {
2872 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2873 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2875 Type *Type = VT.getTypeForEVT(*DAG.getContext());
2876 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2877 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2879 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2880 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2881 DAG.getConstantFP(Max, DL, VT));
2882 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2883 DAG.getConstantFP(Min, DL, VT));
2885 case Intrinsic::r600_read_ngroups_x:
2886 if (Subtarget->isAmdHsaOS())
2887 return emitNonHSAIntrinsicError(DAG, DL, VT);
2889 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2890 SI::KernelInputOffsets::NGROUPS_X, false);
2891 case Intrinsic::r600_read_ngroups_y:
2892 if (Subtarget->isAmdHsaOS())
2893 return emitNonHSAIntrinsicError(DAG, DL, VT);
2895 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2896 SI::KernelInputOffsets::NGROUPS_Y, false);
2897 case Intrinsic::r600_read_ngroups_z:
2898 if (Subtarget->isAmdHsaOS())
2899 return emitNonHSAIntrinsicError(DAG, DL, VT);
2901 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2902 SI::KernelInputOffsets::NGROUPS_Z, false);
2903 case Intrinsic::r600_read_global_size_x:
2904 if (Subtarget->isAmdHsaOS())
2905 return emitNonHSAIntrinsicError(DAG, DL, VT);
2907 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2908 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2909 case Intrinsic::r600_read_global_size_y:
2910 if (Subtarget->isAmdHsaOS())
2911 return emitNonHSAIntrinsicError(DAG, DL, VT);
2913 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2914 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2915 case Intrinsic::r600_read_global_size_z:
2916 if (Subtarget->isAmdHsaOS())
2917 return emitNonHSAIntrinsicError(DAG, DL, VT);
2919 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2920 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2921 case Intrinsic::r600_read_local_size_x:
2922 if (Subtarget->isAmdHsaOS())
2923 return emitNonHSAIntrinsicError(DAG, DL, VT);
2925 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2926 SI::KernelInputOffsets::LOCAL_SIZE_X);
2927 case Intrinsic::r600_read_local_size_y:
2928 if (Subtarget->isAmdHsaOS())
2929 return emitNonHSAIntrinsicError(DAG, DL, VT);
2931 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2932 SI::KernelInputOffsets::LOCAL_SIZE_Y);
2933 case Intrinsic::r600_read_local_size_z:
2934 if (Subtarget->isAmdHsaOS())
2935 return emitNonHSAIntrinsicError(DAG, DL, VT);
2937 return lowerImplicitZextParam(DAG, Op, MVT::i16,
2938 SI::KernelInputOffsets::LOCAL_SIZE_Z);
2939 case Intrinsic::amdgcn_workgroup_id_x:
2940 case Intrinsic::r600_read_tgid_x:
2941 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2942 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2943 case Intrinsic::amdgcn_workgroup_id_y:
2944 case Intrinsic::r600_read_tgid_y:
2945 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2946 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2947 case Intrinsic::amdgcn_workgroup_id_z:
2948 case Intrinsic::r600_read_tgid_z:
2949 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2950 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2951 case Intrinsic::amdgcn_workitem_id_x:
2952 case Intrinsic::r600_read_tidig_x:
2953 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2954 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2955 case Intrinsic::amdgcn_workitem_id_y:
2956 case Intrinsic::r600_read_tidig_y:
2957 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2958 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2959 case Intrinsic::amdgcn_workitem_id_z:
2960 case Intrinsic::r600_read_tidig_z:
2961 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2962 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2963 case AMDGPUIntrinsic::SI_load_const: {
2969 MachineMemOperand *MMO = MF.getMachineMemOperand(
2970 MachinePointerInfo(),
2971 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2972 MachineMemOperand::MOInvariant,
2973 VT.getStoreSize(), 4);
2974 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2975 Op->getVTList(), Ops, VT, MMO);
2977 case Intrinsic::amdgcn_fdiv_fast:
2978 return lowerFDIV_FAST(Op, DAG);
2979 case Intrinsic::amdgcn_interp_mov: {
2980 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2981 SDValue Glue = M0.getValue(1);
2982 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2983 Op.getOperand(2), Op.getOperand(3), Glue);
2985 case Intrinsic::amdgcn_interp_p1: {
2986 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2987 SDValue Glue = M0.getValue(1);
2988 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2989 Op.getOperand(2), Op.getOperand(3), Glue);
2991 case Intrinsic::amdgcn_interp_p2: {
2992 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2993 SDValue Glue = SDValue(M0.getNode(), 1);
2994 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2995 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2998 case Intrinsic::amdgcn_sin:
2999 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
3001 case Intrinsic::amdgcn_cos:
3002 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
3004 case Intrinsic::amdgcn_log_clamp: {
3005 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3008 DiagnosticInfoUnsupported BadIntrin(
3009 *MF.getFunction(), "intrinsic not supported on subtarget",
3011 DAG.getContext()->diagnose(BadIntrin);
3012 return DAG.getUNDEF(VT);
3014 case Intrinsic::amdgcn_ldexp:
3015 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
3016 Op.getOperand(1), Op.getOperand(2));
3018 case Intrinsic::amdgcn_fract:
3019 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
3021 case Intrinsic::amdgcn_class:
3022 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
3023 Op.getOperand(1), Op.getOperand(2));
3024 case Intrinsic::amdgcn_div_fmas:
3025 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
3026 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
3029 case Intrinsic::amdgcn_div_fixup:
3030 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
3031 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3033 case Intrinsic::amdgcn_trig_preop:
3034 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
3035 Op.getOperand(1), Op.getOperand(2));
3036 case Intrinsic::amdgcn_div_scale: {
3037 // 3rd parameter required to be a constant.
3038 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3040 return DAG.getUNDEF(VT);
3042 // Translate to the operands expected by the machine instruction. The
3043 // first parameter must be the same as the first instruction.
3044 SDValue Numerator = Op.getOperand(1);
3045 SDValue Denominator = Op.getOperand(2);
3047 // Note this order is opposite of the machine instruction's operations,
3048 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
3049 // intrinsic has the numerator as the first operand to match a normal
3050 // division operation.
3052 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
3054 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
3055 Denominator, Numerator);
3057 case Intrinsic::amdgcn_icmp: {
3058 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3060 return DAG.getUNDEF(VT);
3062 int CondCode = CD->getSExtValue();
3063 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3064 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3065 return DAG.getUNDEF(VT);
3067 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3068 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3069 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3070 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3072 case Intrinsic::amdgcn_fcmp: {
3073 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3075 return DAG.getUNDEF(VT);
3077 int CondCode = CD->getSExtValue();
3078 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3079 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
3080 return DAG.getUNDEF(VT);
3082 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3083 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3084 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3085 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3087 case Intrinsic::amdgcn_fmed3:
3088 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
3089 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3090 case Intrinsic::amdgcn_fmul_legacy:
3091 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
3092 Op.getOperand(1), Op.getOperand(2));
3093 case Intrinsic::amdgcn_sffbh:
3094 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
3095 case Intrinsic::amdgcn_sbfe:
3096 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
3097 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3098 case Intrinsic::amdgcn_ubfe:
3099 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3100 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3101 case Intrinsic::amdgcn_cvt_pkrtz: {
3102 // FIXME: Stop adding cast if v2f16 legal.
3103 EVT VT = Op.getValueType();
3104 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3105 Op.getOperand(1), Op.getOperand(2));
3106 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3113 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3114 SelectionDAG &DAG) const {
3115 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3118 case Intrinsic::amdgcn_atomic_inc:
3119 case Intrinsic::amdgcn_atomic_dec: {
3120 MemSDNode *M = cast<MemSDNode>(Op);
3121 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3122 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3124 M->getOperand(0), // Chain
3125 M->getOperand(2), // Ptr
3126 M->getOperand(3) // Value
3129 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3130 M->getMemoryVT(), M->getMemOperand());
3132 case Intrinsic::amdgcn_buffer_load:
3133 case Intrinsic::amdgcn_buffer_load_format: {
3135 Op.getOperand(0), // Chain
3136 Op.getOperand(2), // rsrc
3137 Op.getOperand(3), // vindex
3138 Op.getOperand(4), // offset
3139 Op.getOperand(5), // glc
3140 Op.getOperand(6) // slc
3142 MachineFunction &MF = DAG.getMachineFunction();
3143 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3145 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3146 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3147 EVT VT = Op.getValueType();
3148 EVT IntVT = VT.changeTypeToInteger();
3150 MachineMemOperand *MMO = MF.getMachineMemOperand(
3151 MachinePointerInfo(MFI->getBufferPSV()),
3152 MachineMemOperand::MOLoad,
3153 VT.getStoreSize(), VT.getStoreSize());
3155 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3158 case Intrinsic::amdgcn_image_sample:
3159 case Intrinsic::amdgcn_image_sample_cl:
3160 case Intrinsic::amdgcn_image_sample_d:
3161 case Intrinsic::amdgcn_image_sample_d_cl:
3162 case Intrinsic::amdgcn_image_sample_l:
3163 case Intrinsic::amdgcn_image_sample_b:
3164 case Intrinsic::amdgcn_image_sample_b_cl:
3165 case Intrinsic::amdgcn_image_sample_lz:
3166 case Intrinsic::amdgcn_image_sample_cd:
3167 case Intrinsic::amdgcn_image_sample_cd_cl:
3169 // Sample with comparison.
3170 case Intrinsic::amdgcn_image_sample_c:
3171 case Intrinsic::amdgcn_image_sample_c_cl:
3172 case Intrinsic::amdgcn_image_sample_c_d:
3173 case Intrinsic::amdgcn_image_sample_c_d_cl:
3174 case Intrinsic::amdgcn_image_sample_c_l:
3175 case Intrinsic::amdgcn_image_sample_c_b:
3176 case Intrinsic::amdgcn_image_sample_c_b_cl:
3177 case Intrinsic::amdgcn_image_sample_c_lz:
3178 case Intrinsic::amdgcn_image_sample_c_cd:
3179 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3181 // Sample with offsets.
3182 case Intrinsic::amdgcn_image_sample_o:
3183 case Intrinsic::amdgcn_image_sample_cl_o:
3184 case Intrinsic::amdgcn_image_sample_d_o:
3185 case Intrinsic::amdgcn_image_sample_d_cl_o:
3186 case Intrinsic::amdgcn_image_sample_l_o:
3187 case Intrinsic::amdgcn_image_sample_b_o:
3188 case Intrinsic::amdgcn_image_sample_b_cl_o:
3189 case Intrinsic::amdgcn_image_sample_lz_o:
3190 case Intrinsic::amdgcn_image_sample_cd_o:
3191 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3193 // Sample with comparison and offsets.
3194 case Intrinsic::amdgcn_image_sample_c_o:
3195 case Intrinsic::amdgcn_image_sample_c_cl_o:
3196 case Intrinsic::amdgcn_image_sample_c_d_o:
3197 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3198 case Intrinsic::amdgcn_image_sample_c_l_o:
3199 case Intrinsic::amdgcn_image_sample_c_b_o:
3200 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3201 case Intrinsic::amdgcn_image_sample_c_lz_o:
3202 case Intrinsic::amdgcn_image_sample_c_cd_o:
3203 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3205 case Intrinsic::amdgcn_image_getlod: {
3206 // Replace dmask with everything disabled with undef.
3207 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3208 if (!DMask || DMask->isNullValue()) {
3209 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3210 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3220 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3221 SelectionDAG &DAG) const {
3222 MachineFunction &MF = DAG.getMachineFunction();
3224 SDValue Chain = Op.getOperand(0);
3225 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3227 switch (IntrinsicID) {
3228 case Intrinsic::amdgcn_exp: {
3229 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3230 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3231 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3232 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3234 const SDValue Ops[] = {
3236 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3237 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3238 Op.getOperand(4), // src0
3239 Op.getOperand(5), // src1
3240 Op.getOperand(6), // src2
3241 Op.getOperand(7), // src3
3242 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3243 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3246 unsigned Opc = Done->isNullValue() ?
3247 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3248 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3250 case Intrinsic::amdgcn_exp_compr: {
3251 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3252 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3253 SDValue Src0 = Op.getOperand(4);
3254 SDValue Src1 = Op.getOperand(5);
3255 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3256 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3258 SDValue Undef = DAG.getUNDEF(MVT::f32);
3259 const SDValue Ops[] = {
3261 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3262 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3263 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3264 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3267 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3268 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3271 unsigned Opc = Done->isNullValue() ?
3272 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3273 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3275 case Intrinsic::amdgcn_s_sendmsg:
3276 case Intrinsic::amdgcn_s_sendmsghalt: {
3277 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3278 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3279 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3280 SDValue Glue = Chain.getValue(1);
3281 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3282 Op.getOperand(2), Glue);
3284 case Intrinsic::amdgcn_init_exec: {
3285 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
3288 case Intrinsic::amdgcn_init_exec_from_input: {
3289 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
3290 Op.getOperand(2), Op.getOperand(3));
3292 case AMDGPUIntrinsic::SI_tbuffer_store: {
3310 EVT VT = Op.getOperand(3).getValueType();
3312 MachineMemOperand *MMO = MF.getMachineMemOperand(
3313 MachinePointerInfo(),
3314 MachineMemOperand::MOStore,
3315 VT.getStoreSize(), 4);
3316 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3317 Op->getVTList(), Ops, VT, MMO);
3319 case AMDGPUIntrinsic::AMDGPU_kill: {
3320 SDValue Src = Op.getOperand(2);
3321 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3322 if (!K->isNegative())
3325 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3326 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3329 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3330 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3332 case Intrinsic::amdgcn_s_barrier: {
3333 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3334 const MachineFunction &MF = DAG.getMachineFunction();
3335 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3336 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3337 if (WGSize <= ST.getWavefrontSize())
3338 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3339 Op.getOperand(0)), 0);
3348 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3350 LoadSDNode *Load = cast<LoadSDNode>(Op);
3351 ISD::LoadExtType ExtType = Load->getExtensionType();
3352 EVT MemVT = Load->getMemoryVT();
3354 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3355 // FIXME: Copied from PPC
3356 // First, load into 32 bits, then truncate to 1 bit.
3358 SDValue Chain = Load->getChain();
3359 SDValue BasePtr = Load->getBasePtr();
3360 MachineMemOperand *MMO = Load->getMemOperand();
3362 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3364 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3365 BasePtr, RealMemVT, MMO);
3368 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3372 return DAG.getMergeValues(Ops, DL);
3375 if (!MemVT.isVector())
3378 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3379 "Custom lowering for non-i32 vectors hasn't been implemented.");
3381 unsigned AS = Load->getAddressSpace();
3382 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3383 AS, Load->getAlignment())) {
3385 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3386 return DAG.getMergeValues(Ops, DL);
3389 MachineFunction &MF = DAG.getMachineFunction();
3390 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3391 // If there is a possibilty that flat instruction access scratch memory
3392 // then we need to use the same legalization rules we use for private.
3393 if (AS == AMDGPUASI.FLAT_ADDRESS)
3394 AS = MFI->hasFlatScratchInit() ?
3395 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3397 unsigned NumElements = MemVT.getVectorNumElements();
3398 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3399 if (isMemOpUniform(Load))
3401 // Non-uniform loads will be selected to MUBUF instructions, so they
3402 // have the same legalization requirements as global and private
3406 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3407 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3408 isMemOpHasNoClobberedMemOperand(Load))
3410 // Non-uniform loads will be selected to MUBUF instructions, so they
3411 // have the same legalization requirements as global and private
3415 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3416 AS == AMDGPUASI.FLAT_ADDRESS) {
3417 if (NumElements > 4)
3418 return SplitVectorLoad(Op, DAG);
3419 // v4 loads are supported for private and global memory.
3422 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3423 // Depending on the setting of the private_element_size field in the
3424 // resource descriptor, we can only make private accesses up to a certain
3426 switch (Subtarget->getMaxPrivateElementSize()) {
3428 return scalarizeVectorLoad(Load, DAG);
3430 if (NumElements > 2)
3431 return SplitVectorLoad(Op, DAG);
3434 // Same as global/flat
3435 if (NumElements > 4)
3436 return SplitVectorLoad(Op, DAG);
3439 llvm_unreachable("unsupported private_element_size");
3441 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3442 if (NumElements > 2)
3443 return SplitVectorLoad(Op, DAG);
3445 if (NumElements == 2)
3448 // If properly aligned, if we split we might be able to use ds_read_b64.
3449 return SplitVectorLoad(Op, DAG);
3454 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3455 if (Op.getValueType() != MVT::i64)
3459 SDValue Cond = Op.getOperand(0);
3461 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3462 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3464 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3465 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3467 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3468 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3470 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3472 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3473 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3475 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3477 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3478 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3481 // Catch division cases where we can use shortcuts with rcp and rsq
3483 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3484 SelectionDAG &DAG) const {
3486 SDValue LHS = Op.getOperand(0);
3487 SDValue RHS = Op.getOperand(1);
3488 EVT VT = Op.getValueType();
3489 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3491 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
3494 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3495 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
3496 if (CLHS->isExactlyValue(1.0)) {
3497 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3498 // the CI documentation has a worst case error of 1 ulp.
3499 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3500 // use it as long as we aren't trying to use denormals.
3502 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3504 // 1.0 / sqrt(x) -> rsq(x)
3506 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3507 // error seems really high at 2^29 ULP.
3508 if (RHS.getOpcode() == ISD::FSQRT)
3509 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3511 // 1.0 / x -> rcp(x)
3512 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3515 // Same as for 1.0, but expand the sign out of the constant.
3516 if (CLHS->isExactlyValue(-1.0)) {
3517 // -1.0 / x -> rcp (fneg x)
3518 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3519 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3524 const SDNodeFlags Flags = Op->getFlags();
3526 if (Unsafe || Flags.hasAllowReciprocal()) {
3527 // Turn into multiply by the reciprocal.
3528 // x / y -> x * (1.0 / y)
3529 SDNodeFlags NewFlags;
3530 NewFlags.setUnsafeAlgebra(true);
3531 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3532 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, NewFlags);
3538 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3539 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3540 if (GlueChain->getNumValues() <= 1) {
3541 return DAG.getNode(Opcode, SL, VT, A, B);
3544 assert(GlueChain->getNumValues() == 3);
3546 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3548 default: llvm_unreachable("no chain equivalent for opcode");
3550 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3554 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3555 GlueChain.getValue(2));
3558 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3559 EVT VT, SDValue A, SDValue B, SDValue C,
3560 SDValue GlueChain) {
3561 if (GlueChain->getNumValues() <= 1) {
3562 return DAG.getNode(Opcode, SL, VT, A, B, C);
3565 assert(GlueChain->getNumValues() == 3);
3567 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3569 default: llvm_unreachable("no chain equivalent for opcode");
3571 Opcode = AMDGPUISD::FMA_W_CHAIN;
3575 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3576 GlueChain.getValue(2));
3579 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3580 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3584 SDValue Src0 = Op.getOperand(0);
3585 SDValue Src1 = Op.getOperand(1);
3587 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3588 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3590 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3591 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3593 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3594 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3596 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3599 // Faster 2.5 ULP division that does not support denormals.
3600 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3602 SDValue LHS = Op.getOperand(1);
3603 SDValue RHS = Op.getOperand(2);
3605 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3607 const APFloat K0Val(BitsToFloat(0x6f800000));
3608 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3610 const APFloat K1Val(BitsToFloat(0x2f800000));
3611 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3613 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3616 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3618 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3620 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3622 // TODO: Should this propagate fast-math-flags?
3623 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3625 // rcp does not support denormals.
3626 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3628 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3630 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3633 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3634 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3638 SDValue LHS = Op.getOperand(0);
3639 SDValue RHS = Op.getOperand(1);
3641 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3643 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3645 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3647 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3650 // Denominator is scaled to not be denormal, so using rcp is ok.
3651 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3653 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3656 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3657 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3658 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3660 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3662 if (!Subtarget->hasFP32Denormals()) {
3663 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3664 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3666 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3668 EnableDenormValue, BitField);
3671 EnableDenorm.getValue(0),
3672 EnableDenorm.getValue(1)
3675 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3678 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3679 ApproxRcp, One, NegDivScale0);
3681 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3684 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3687 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3688 NumeratorScaled, Mul);
3690 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3692 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3693 NumeratorScaled, Fma3);
3695 if (!Subtarget->hasFP32Denormals()) {
3696 const SDValue DisableDenormValue =
3697 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3698 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3704 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3705 DisableDenorm, DAG.getRoot());
3706 DAG.setRoot(OutputChain);
3709 SDValue Scale = NumeratorScaled.getValue(1);
3710 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3711 Fma4, Fma1, Fma3, Scale);
3713 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3716 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3717 if (DAG.getTarget().Options.UnsafeFPMath)
3718 return lowerFastUnsafeFDIV(Op, DAG);
3721 SDValue X = Op.getOperand(0);
3722 SDValue Y = Op.getOperand(1);
3724 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3726 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3728 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3730 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3732 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3734 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3736 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3738 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3740 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3742 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3743 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3745 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3746 NegDivScale0, Mul, DivScale1);
3750 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3751 // Workaround a hardware bug on SI where the condition output from div_scale
3754 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3756 // Figure out if the scale to use for div_fmas.
3757 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3758 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3759 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3760 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3762 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3763 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3766 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3768 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3770 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3771 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3772 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3774 Scale = DivScale1.getValue(1);
3777 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3778 Fma4, Fma3, Mul, Scale);
3780 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3783 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3784 EVT VT = Op.getValueType();
3787 return LowerFDIV32(Op, DAG);
3790 return LowerFDIV64(Op, DAG);
3793 return LowerFDIV16(Op, DAG);
3795 llvm_unreachable("Unexpected type for fdiv");
3798 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3800 StoreSDNode *Store = cast<StoreSDNode>(Op);
3801 EVT VT = Store->getMemoryVT();
3803 if (VT == MVT::i1) {
3804 return DAG.getTruncStore(Store->getChain(), DL,
3805 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3806 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3809 assert(VT.isVector() &&
3810 Store->getValue().getValueType().getScalarType() == MVT::i32);
3812 unsigned AS = Store->getAddressSpace();
3813 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3814 AS, Store->getAlignment())) {
3815 return expandUnalignedStore(Store, DAG);
3818 MachineFunction &MF = DAG.getMachineFunction();
3819 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3820 // If there is a possibilty that flat instruction access scratch memory
3821 // then we need to use the same legalization rules we use for private.
3822 if (AS == AMDGPUASI.FLAT_ADDRESS)
3823 AS = MFI->hasFlatScratchInit() ?
3824 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3826 unsigned NumElements = VT.getVectorNumElements();
3827 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3828 AS == AMDGPUASI.FLAT_ADDRESS) {
3829 if (NumElements > 4)
3830 return SplitVectorStore(Op, DAG);
3832 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3833 switch (Subtarget->getMaxPrivateElementSize()) {
3835 return scalarizeVectorStore(Store, DAG);
3837 if (NumElements > 2)
3838 return SplitVectorStore(Op, DAG);
3841 if (NumElements > 4)
3842 return SplitVectorStore(Op, DAG);
3845 llvm_unreachable("unsupported private_element_size");
3847 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3848 if (NumElements > 2)
3849 return SplitVectorStore(Op, DAG);
3851 if (NumElements == 2)
3854 // If properly aligned, if we split we might be able to use ds_write_b64.
3855 return SplitVectorStore(Op, DAG);
3857 llvm_unreachable("unhandled address space");
3861 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3863 EVT VT = Op.getValueType();
3864 SDValue Arg = Op.getOperand(0);
3865 // TODO: Should this propagate fast-math-flags?
3866 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3867 DAG.getNode(ISD::FMUL, DL, VT, Arg,
3868 DAG.getConstantFP(0.5/M_PI, DL,
3871 switch (Op.getOpcode()) {
3873 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3875 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3877 llvm_unreachable("Wrong trig opcode");
3881 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3882 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3883 assert(AtomicNode->isCompareAndSwap());
3884 unsigned AS = AtomicNode->getAddressSpace();
3886 // No custom lowering required for local address space
3887 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
3890 // Non-local address space requires custom lowering for atomic compare
3891 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3893 SDValue ChainIn = Op.getOperand(0);
3894 SDValue Addr = Op.getOperand(1);
3895 SDValue Old = Op.getOperand(2);
3896 SDValue New = Op.getOperand(3);
3897 EVT VT = Op.getValueType();
3898 MVT SimpleVT = VT.getSimpleVT();
3899 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3901 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3902 SDValue Ops[] = { ChainIn, Addr, NewOld };
3904 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3905 Ops, VT, AtomicNode->getMemOperand());
3908 //===----------------------------------------------------------------------===//
3909 // Custom DAG optimizations
3910 //===----------------------------------------------------------------------===//
3912 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3913 DAGCombinerInfo &DCI) const {
3914 EVT VT = N->getValueType(0);
3915 EVT ScalarVT = VT.getScalarType();
3916 if (ScalarVT != MVT::f32)
3919 SelectionDAG &DAG = DCI.DAG;
3922 SDValue Src = N->getOperand(0);
3923 EVT SrcVT = Src.getValueType();
3925 // TODO: We could try to match extracting the higher bytes, which would be
3926 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3927 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3928 // about in practice.
3929 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3930 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3931 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3932 DCI.AddToWorklist(Cvt.getNode());
3940 /// \brief Return true if the given offset Size in bytes can be folded into
3941 /// the immediate offsets of a memory instruction for the given address space.
3942 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3943 const SISubtarget &STI) {
3944 auto AMDGPUASI = STI.getAMDGPUAS();
3945 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
3946 // MUBUF instructions a 12-bit offset in bytes.
3947 return isUInt<12>(OffsetSize);
3949 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3950 // SMRD instructions have an 8-bit offset in dwords on SI and
3951 // a 20-bit offset in bytes on VI.
3952 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3953 return isUInt<20>(OffsetSize);
3955 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3957 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
3958 AS == AMDGPUASI.REGION_ADDRESS) {
3959 // The single offset versions have a 16-bit offset in bytes.
3960 return isUInt<16>(OffsetSize);
3962 // Indirect register addressing does not use any offsets.
3966 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3968 // This is a variant of
3969 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3971 // The normal DAG combiner will do this, but only if the add has one use since
3972 // that would increase the number of instructions.
3974 // This prevents us from seeing a constant offset that can be folded into a
3975 // memory instruction's addressing mode. If we know the resulting add offset of
3976 // a pointer can be folded into an addressing offset, we can replace the pointer
3977 // operand with the add of new constant offset. This eliminates one of the uses,
3978 // and may allow the remaining use to also be simplified.
3980 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3982 DAGCombinerInfo &DCI) const {
3983 SDValue N0 = N->getOperand(0);
3984 SDValue N1 = N->getOperand(1);
3986 if (N0.getOpcode() != ISD::ADD)
3989 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3993 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3997 // If the resulting offset is too large, we can't fold it into the addressing
3999 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
4000 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
4003 SelectionDAG &DAG = DCI.DAG;
4005 EVT VT = N->getValueType(0);
4007 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
4008 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
4010 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
4013 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
4014 DAGCombinerInfo &DCI) const {
4015 SDValue Ptr = N->getBasePtr();
4016 SelectionDAG &DAG = DCI.DAG;
4019 // TODO: We could also do this for multiplies.
4020 unsigned AS = N->getAddressSpace();
4021 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
4022 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
4024 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
4026 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
4027 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
4034 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
4035 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
4036 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
4037 (Opc == ISD::XOR && Val == 0);
4040 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
4041 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
4042 // integer combine opportunities since most 64-bit operations are decomposed
4043 // this way. TODO: We won't want this for SALU especially if it is an inline
4045 SDValue SITargetLowering::splitBinaryBitConstantOp(
4046 DAGCombinerInfo &DCI,
4048 unsigned Opc, SDValue LHS,
4049 const ConstantSDNode *CRHS) const {
4050 uint64_t Val = CRHS->getZExtValue();
4051 uint32_t ValLo = Lo_32(Val);
4052 uint32_t ValHi = Hi_32(Val);
4053 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4055 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
4056 bitOpWithConstantIsReducible(Opc, ValHi)) ||
4057 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
4058 // If we need to materialize a 64-bit immediate, it will be split up later
4059 // anyway. Avoid creating the harder to understand 64-bit immediate
4061 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
4067 SDValue SITargetLowering::performAndCombine(SDNode *N,
4068 DAGCombinerInfo &DCI) const {
4069 if (DCI.isBeforeLegalize())
4072 SelectionDAG &DAG = DCI.DAG;
4073 EVT VT = N->getValueType(0);
4074 SDValue LHS = N->getOperand(0);
4075 SDValue RHS = N->getOperand(1);
4078 if (VT == MVT::i64) {
4079 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4082 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
4087 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
4088 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
4089 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
4090 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
4091 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
4093 SDValue X = LHS.getOperand(0);
4094 SDValue Y = RHS.getOperand(0);
4095 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
4098 if (LCC == ISD::SETO) {
4099 if (X != LHS.getOperand(1))
4102 if (RCC == ISD::SETUNE) {
4103 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
4104 if (!C1 || !C1->isInfinity() || C1->isNegative())
4107 const uint32_t Mask = SIInstrFlags::N_NORMAL |
4108 SIInstrFlags::N_SUBNORMAL |
4109 SIInstrFlags::N_ZERO |
4110 SIInstrFlags::P_ZERO |
4111 SIInstrFlags::P_SUBNORMAL |
4112 SIInstrFlags::P_NORMAL;
4114 static_assert(((~(SIInstrFlags::S_NAN |
4115 SIInstrFlags::Q_NAN |
4116 SIInstrFlags::N_INFINITY |
4117 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4121 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4122 X, DAG.getConstant(Mask, DL, MVT::i32));
4130 SDValue SITargetLowering::performOrCombine(SDNode *N,
4131 DAGCombinerInfo &DCI) const {
4132 SelectionDAG &DAG = DCI.DAG;
4133 SDValue LHS = N->getOperand(0);
4134 SDValue RHS = N->getOperand(1);
4136 EVT VT = N->getValueType(0);
4137 if (VT == MVT::i1) {
4138 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4139 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4140 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4141 SDValue Src = LHS.getOperand(0);
4142 if (Src != RHS.getOperand(0))
4145 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4146 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4150 // Only 10 bits are used.
4151 static const uint32_t MaxMask = 0x3ff;
4153 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4155 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4156 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4165 // TODO: This could be a generic combine with a predicate for extracting the
4166 // high half of an integer being free.
4168 // (or i64:x, (zero_extend i32:y)) ->
4169 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4170 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4171 RHS.getOpcode() != ISD::ZERO_EXTEND)
4172 std::swap(LHS, RHS);
4174 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4175 SDValue ExtSrc = RHS.getOperand(0);
4176 EVT SrcVT = ExtSrc.getValueType();
4177 if (SrcVT == MVT::i32) {
4179 SDValue LowLHS, HiBits;
4180 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4181 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4183 DCI.AddToWorklist(LowOr.getNode());
4184 DCI.AddToWorklist(HiBits.getNode());
4186 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4188 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4192 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4195 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4202 SDValue SITargetLowering::performXorCombine(SDNode *N,
4203 DAGCombinerInfo &DCI) const {
4204 EVT VT = N->getValueType(0);
4208 SDValue LHS = N->getOperand(0);
4209 SDValue RHS = N->getOperand(1);
4211 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4214 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4221 // Instructions that will be lowered with a final instruction that zeros the
4222 // high result bits.
4223 // XXX - probably only need to list legal operations.
4224 static bool fp16SrcZerosHighBits(unsigned Opc) {
4233 case ISD::FCANONICALIZE:
4235 case ISD::UINT_TO_FP:
4236 case ISD::SINT_TO_FP:
4238 // Fabs is lowered to a bit operation, but it's an and which will clear the
4239 // high bits anyway.
4253 case ISD::FNEARBYINT:
4258 case AMDGPUISD::FRACT:
4259 case AMDGPUISD::CLAMP:
4260 case AMDGPUISD::COS_HW:
4261 case AMDGPUISD::SIN_HW:
4262 case AMDGPUISD::FMIN3:
4263 case AMDGPUISD::FMAX3:
4264 case AMDGPUISD::FMED3:
4265 case AMDGPUISD::FMAD_FTZ:
4266 case AMDGPUISD::RCP:
4267 case AMDGPUISD::RSQ:
4268 case AMDGPUISD::LDEXP:
4271 // fcopysign, select and others may be lowered to 32-bit bit operations
4272 // which don't zero the high bits.
4277 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4278 DAGCombinerInfo &DCI) const {
4279 if (!Subtarget->has16BitInsts() ||
4280 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4283 EVT VT = N->getValueType(0);
4287 SDValue Src = N->getOperand(0);
4288 if (Src.getValueType() != MVT::i16)
4291 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4292 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4293 if (Src.getOpcode() == ISD::BITCAST) {
4294 SDValue BCSrc = Src.getOperand(0);
4295 if (BCSrc.getValueType() == MVT::f16 &&
4296 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4297 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4303 SDValue SITargetLowering::performClassCombine(SDNode *N,
4304 DAGCombinerInfo &DCI) const {
4305 SelectionDAG &DAG = DCI.DAG;
4306 SDValue Mask = N->getOperand(1);
4308 // fp_class x, 0 -> false
4309 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4310 if (CMask->isNullValue())
4311 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4314 if (N->getOperand(0).isUndef())
4315 return DAG.getUNDEF(MVT::i1);
4320 // Constant fold canonicalize.
4321 SDValue SITargetLowering::performFCanonicalizeCombine(
4323 DAGCombinerInfo &DCI) const {
4324 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4328 SelectionDAG &DAG = DCI.DAG;
4329 const APFloat &C = CFP->getValueAPF();
4331 // Flush denormals to 0 if not enabled.
4332 if (C.isDenormal()) {
4333 EVT VT = N->getValueType(0);
4334 EVT SVT = VT.getScalarType();
4335 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4336 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4338 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4339 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4341 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4342 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4346 EVT VT = N->getValueType(0);
4347 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4348 if (C.isSignaling()) {
4349 // Quiet a signaling NaN.
4350 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4353 // Make sure it is the canonical NaN bitpattern.
4355 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4357 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4358 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4361 return N->getOperand(0);
4364 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4367 return AMDGPUISD::FMAX3;
4369 return AMDGPUISD::SMAX3;
4371 return AMDGPUISD::UMAX3;
4373 return AMDGPUISD::FMIN3;
4375 return AMDGPUISD::SMIN3;
4377 return AMDGPUISD::UMIN3;
4379 llvm_unreachable("Not a min/max opcode");
4383 SDValue SITargetLowering::performIntMed3ImmCombine(
4384 SelectionDAG &DAG, const SDLoc &SL,
4385 SDValue Op0, SDValue Op1, bool Signed) const {
4386 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4390 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4395 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4398 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4402 EVT VT = K0->getValueType(0);
4403 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4404 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4405 return DAG.getNode(Med3Opc, SL, VT,
4406 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4409 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4411 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4413 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4414 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4415 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4417 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4418 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4421 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4422 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4425 return DAG.isKnownNeverNaN(Op);
4428 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4431 SDValue Op1) const {
4432 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4436 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4440 // Ordered >= (although NaN inputs should have folded away by now).
4441 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4442 if (Cmp == APFloat::cmpGreaterThan)
4445 // TODO: Check IEEE bit enabled?
4446 EVT VT = K0->getValueType(0);
4447 if (Subtarget->enableDX10Clamp()) {
4448 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4449 // hardware fmed3 behavior converting to a min.
4450 // FIXME: Should this be allowing -0.0?
4451 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4452 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4455 // med3 for f16 is only available on gfx9+.
4456 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4459 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4460 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4461 // give the other result, which is different from med3 with a NaN input.
4462 SDValue Var = Op0.getOperand(0);
4463 if (!isKnownNeverSNan(DAG, Var))
4466 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4467 Var, SDValue(K0, 0), SDValue(K1, 0));
4470 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4471 DAGCombinerInfo &DCI) const {
4472 SelectionDAG &DAG = DCI.DAG;
4474 EVT VT = N->getValueType(0);
4475 unsigned Opc = N->getOpcode();
4476 SDValue Op0 = N->getOperand(0);
4477 SDValue Op1 = N->getOperand(1);
4479 // Only do this if the inner op has one use since this will just increases
4480 // register pressure for no benefit.
4483 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4485 // max(max(a, b), c) -> max3(a, b, c)
4486 // min(min(a, b), c) -> min3(a, b, c)
4487 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4489 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4498 // max(a, max(b, c)) -> max3(a, b, c)
4499 // min(a, min(b, c)) -> min3(a, b, c)
4500 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4502 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4511 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4512 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4513 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4517 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4518 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4522 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4523 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4524 (Opc == AMDGPUISD::FMIN_LEGACY &&
4525 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4526 (VT == MVT::f32 || VT == MVT::f64 ||
4527 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4529 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4536 static bool isClampZeroToOne(SDValue A, SDValue B) {
4537 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4538 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4539 // FIXME: Should this be allowing -0.0?
4540 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4541 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4548 // FIXME: Should only worry about snans for version with chain.
4549 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4550 DAGCombinerInfo &DCI) const {
4551 EVT VT = N->getValueType(0);
4552 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4553 // NaNs. With a NaN input, the order of the operands may change the result.
4555 SelectionDAG &DAG = DCI.DAG;
4558 SDValue Src0 = N->getOperand(0);
4559 SDValue Src1 = N->getOperand(1);
4560 SDValue Src2 = N->getOperand(2);
4562 if (isClampZeroToOne(Src0, Src1)) {
4563 // const_a, const_b, x -> clamp is safe in all cases including signaling
4565 // FIXME: Should this be allowing -0.0?
4566 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4569 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4570 // handling no dx10-clamp?
4571 if (Subtarget->enableDX10Clamp()) {
4572 // If NaNs is clamped to 0, we are free to reorder the inputs.
4574 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4575 std::swap(Src0, Src1);
4577 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4578 std::swap(Src1, Src2);
4580 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4581 std::swap(Src0, Src1);
4583 if (isClampZeroToOne(Src1, Src2))
4584 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4590 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4591 DAGCombinerInfo &DCI) const {
4592 SDValue Src0 = N->getOperand(0);
4593 SDValue Src1 = N->getOperand(1);
4594 if (Src0.isUndef() && Src1.isUndef())
4595 return DCI.DAG.getUNDEF(N->getValueType(0));
4599 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4601 const SDNode *N1) const {
4602 EVT VT = N0->getValueType(0);
4604 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4605 // support denormals ever.
4606 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4607 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4610 const TargetOptions &Options = DAG.getTarget().Options;
4611 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
4612 (N0->getFlags().hasUnsafeAlgebra() &&
4613 N1->getFlags().hasUnsafeAlgebra())) &&
4614 isFMAFasterThanFMulAndFAdd(VT)) {
4621 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4622 DAGCombinerInfo &DCI) const {
4623 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4626 SelectionDAG &DAG = DCI.DAG;
4627 EVT VT = N->getValueType(0);
4630 SDValue LHS = N->getOperand(0);
4631 SDValue RHS = N->getOperand(1);
4633 // These should really be instruction patterns, but writing patterns with
4634 // source modiifiers is a pain.
4636 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4637 if (LHS.getOpcode() == ISD::FADD) {
4638 SDValue A = LHS.getOperand(0);
4639 if (A == LHS.getOperand(1)) {
4640 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4642 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4643 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4648 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4649 if (RHS.getOpcode() == ISD::FADD) {
4650 SDValue A = RHS.getOperand(0);
4651 if (A == RHS.getOperand(1)) {
4652 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4654 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4655 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4663 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4664 DAGCombinerInfo &DCI) const {
4665 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4668 SelectionDAG &DAG = DCI.DAG;
4670 EVT VT = N->getValueType(0);
4671 assert(!VT.isVector());
4673 // Try to get the fneg to fold into the source modifier. This undoes generic
4674 // DAG combines and folds them into the mad.
4676 // Only do this if we are not trying to support denormals. v_mad_f32 does
4677 // not support denormals ever.
4678 SDValue LHS = N->getOperand(0);
4679 SDValue RHS = N->getOperand(1);
4680 if (LHS.getOpcode() == ISD::FADD) {
4681 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4682 SDValue A = LHS.getOperand(0);
4683 if (A == LHS.getOperand(1)) {
4684 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4686 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4687 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4689 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4694 if (RHS.getOpcode() == ISD::FADD) {
4695 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4697 SDValue A = RHS.getOperand(0);
4698 if (A == RHS.getOperand(1)) {
4699 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4701 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4702 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4710 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4711 DAGCombinerInfo &DCI) const {
4712 SelectionDAG &DAG = DCI.DAG;
4715 SDValue LHS = N->getOperand(0);
4716 SDValue RHS = N->getOperand(1);
4717 EVT VT = LHS.getValueType();
4719 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4723 // Match isinf pattern
4724 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4725 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4726 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4727 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4731 const APFloat &APF = CRHS->getValueAPF();
4732 if (APF.isInfinity() && !APF.isNegative()) {
4733 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4734 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4735 DAG.getConstant(Mask, SL, MVT::i32));
4742 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4743 DAGCombinerInfo &DCI) const {
4744 SelectionDAG &DAG = DCI.DAG;
4746 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4748 SDValue Src = N->getOperand(0);
4749 SDValue Srl = N->getOperand(0);
4750 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4751 Srl = Srl.getOperand(0);
4753 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4754 if (Srl.getOpcode() == ISD::SRL) {
4755 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4756 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4757 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4759 if (const ConstantSDNode *C =
4760 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4761 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4764 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4765 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4766 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4772 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4775 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4776 !DCI.isBeforeLegalizeOps());
4777 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4778 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
4779 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
4780 DCI.CommitTargetLoweringOpt(TLO);
4786 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4787 DAGCombinerInfo &DCI) const {
4788 switch (N->getOpcode()) {
4790 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4792 return performFAddCombine(N, DCI);
4794 return performFSubCombine(N, DCI);
4796 return performSetCCCombine(N, DCI);
4803 case AMDGPUISD::FMIN_LEGACY:
4804 case AMDGPUISD::FMAX_LEGACY: {
4805 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4806 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4807 return performMinMaxCombine(N, DCI);
4812 case ISD::ATOMIC_LOAD:
4813 case ISD::ATOMIC_STORE:
4814 case ISD::ATOMIC_CMP_SWAP:
4815 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4816 case ISD::ATOMIC_SWAP:
4817 case ISD::ATOMIC_LOAD_ADD:
4818 case ISD::ATOMIC_LOAD_SUB:
4819 case ISD::ATOMIC_LOAD_AND:
4820 case ISD::ATOMIC_LOAD_OR:
4821 case ISD::ATOMIC_LOAD_XOR:
4822 case ISD::ATOMIC_LOAD_NAND:
4823 case ISD::ATOMIC_LOAD_MIN:
4824 case ISD::ATOMIC_LOAD_MAX:
4825 case ISD::ATOMIC_LOAD_UMIN:
4826 case ISD::ATOMIC_LOAD_UMAX:
4827 case AMDGPUISD::ATOMIC_INC:
4828 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
4829 if (DCI.isBeforeLegalize())
4831 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
4833 return performAndCombine(N, DCI);
4835 return performOrCombine(N, DCI);
4837 return performXorCombine(N, DCI);
4838 case ISD::ZERO_EXTEND:
4839 return performZeroExtendCombine(N, DCI);
4840 case AMDGPUISD::FP_CLASS:
4841 return performClassCombine(N, DCI);
4842 case ISD::FCANONICALIZE:
4843 return performFCanonicalizeCombine(N, DCI);
4844 case AMDGPUISD::FRACT:
4845 case AMDGPUISD::RCP:
4846 case AMDGPUISD::RSQ:
4847 case AMDGPUISD::RCP_LEGACY:
4848 case AMDGPUISD::RSQ_LEGACY:
4849 case AMDGPUISD::RSQ_CLAMP:
4850 case AMDGPUISD::LDEXP: {
4851 SDValue Src = N->getOperand(0);
4856 case ISD::SINT_TO_FP:
4857 case ISD::UINT_TO_FP:
4858 return performUCharToFloatCombine(N, DCI);
4859 case AMDGPUISD::CVT_F32_UBYTE0:
4860 case AMDGPUISD::CVT_F32_UBYTE1:
4861 case AMDGPUISD::CVT_F32_UBYTE2:
4862 case AMDGPUISD::CVT_F32_UBYTE3:
4863 return performCvtF32UByteNCombine(N, DCI);
4864 case AMDGPUISD::FMED3:
4865 return performFMed3Combine(N, DCI);
4866 case AMDGPUISD::CVT_PKRTZ_F16_F32:
4867 return performCvtPkRTZCombine(N, DCI);
4868 case ISD::SCALAR_TO_VECTOR: {
4869 SelectionDAG &DAG = DCI.DAG;
4870 EVT VT = N->getValueType(0);
4872 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
4873 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
4875 SDValue Src = N->getOperand(0);
4876 EVT EltVT = Src.getValueType();
4877 if (EltVT == MVT::f16)
4878 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
4880 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
4881 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
4887 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4890 /// \brief Helper function for adjustWritemask
4891 static unsigned SubIdx2Lane(unsigned Idx) {
4894 case AMDGPU::sub0: return 0;
4895 case AMDGPU::sub1: return 1;
4896 case AMDGPU::sub2: return 2;
4897 case AMDGPU::sub3: return 3;
4901 /// \brief Adjust the writemask of MIMG instructions
4902 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4903 SelectionDAG &DAG) const {
4904 SDNode *Users[4] = { };
4906 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4907 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4908 unsigned NewDmask = 0;
4910 // Try to figure out the used register components
4911 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4914 // Don't look at users of the chain.
4915 if (I.getUse().getResNo() != 0)
4918 // Abort if we can't understand the usage
4919 if (!I->isMachineOpcode() ||
4920 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4923 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4924 // Note that subregs are packed, i.e. Lane==0 is the first bit set
4925 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4927 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4929 // Set which texture component corresponds to the lane.
4931 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4933 Comp = countTrailingZeros(Dmask);
4934 Dmask &= ~(1 << Comp);
4937 // Abort if we have more than one user per component
4942 NewDmask |= 1 << Comp;
4945 // Abort if there's no change
4946 if (NewDmask == OldDmask)
4949 // Adjust the writemask in the node
4950 std::vector<SDValue> Ops;
4951 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4952 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4953 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4954 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4956 // If we only got one lane, replace it with a copy
4957 // (if NewDmask has only one bit set...)
4958 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4959 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4961 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4962 SDLoc(), Users[Lane]->getValueType(0),
4963 SDValue(Node, 0), RC);
4964 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4968 // Update the users of the node with the new indices
4969 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4970 SDNode *User = Users[i];
4974 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4975 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4979 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4980 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4981 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4986 static bool isFrameIndexOp(SDValue Op) {
4987 if (Op.getOpcode() == ISD::AssertZext)
4988 Op = Op.getOperand(0);
4990 return isa<FrameIndexSDNode>(Op);
4993 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4994 /// with frame index operands.
4995 /// LLVM assumes that inputs are to these instructions are registers.
4996 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4997 SelectionDAG &DAG) const {
4998 if (Node->getOpcode() == ISD::CopyToReg) {
4999 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
5000 SDValue SrcVal = Node->getOperand(2);
5002 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
5003 // to try understanding copies to physical registers.
5004 if (SrcVal.getValueType() == MVT::i1 &&
5005 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
5007 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
5008 SDValue VReg = DAG.getRegister(
5009 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
5011 SDNode *Glued = Node->getGluedNode();
5013 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
5014 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
5016 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
5017 VReg, ToVReg.getValue(1));
5018 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
5019 DAG.RemoveDeadNode(Node);
5020 return ToResultReg.getNode();
5024 SmallVector<SDValue, 8> Ops;
5025 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
5026 if (!isFrameIndexOp(Node->getOperand(i))) {
5027 Ops.push_back(Node->getOperand(i));
5032 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
5033 Node->getOperand(i).getValueType(),
5034 Node->getOperand(i)), 0));
5037 DAG.UpdateNodeOperands(Node, Ops);
5041 /// \brief Fold the instructions after selecting them.
5042 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
5043 SelectionDAG &DAG) const {
5044 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5045 unsigned Opcode = Node->getMachineOpcode();
5047 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
5048 !TII->isGather4(Opcode))
5049 adjustWritemask(Node, DAG);
5051 if (Opcode == AMDGPU::INSERT_SUBREG ||
5052 Opcode == AMDGPU::REG_SEQUENCE) {
5053 legalizeTargetIndependentNode(Node, DAG);
5059 /// \brief Assign the register class depending on the number of
5060 /// bits set in the writemask
5061 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
5062 SDNode *Node) const {
5063 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5065 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5067 if (TII->isVOP3(MI.getOpcode())) {
5068 // Make sure constant bus requirements are respected.
5069 TII->legalizeOperandsVOP3(MRI, MI);
5073 if (TII->isMIMG(MI)) {
5074 unsigned VReg = MI.getOperand(0).getReg();
5075 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
5076 // TODO: Need mapping tables to handle other cases (register classes).
5077 if (RC != &AMDGPU::VReg_128RegClass)
5080 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
5081 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
5082 unsigned BitsSet = 0;
5083 for (unsigned i = 0; i < 4; ++i)
5084 BitsSet += Writemask & (1 << i) ? 1 : 0;
5087 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
5088 case 2: RC = &AMDGPU::VReg_64RegClass; break;
5089 case 3: RC = &AMDGPU::VReg_96RegClass; break;
5092 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
5093 MI.setDesc(TII->get(NewOpcode));
5094 MRI.setRegClass(VReg, RC);
5098 // Replace unused atomics with the no return version.
5099 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
5100 if (NoRetAtomicOp != -1) {
5101 if (!Node->hasAnyUseOfValue(0)) {
5102 MI.setDesc(TII->get(NoRetAtomicOp));
5103 MI.RemoveOperand(0);
5107 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5108 // instruction, because the return type of these instructions is a vec2 of
5109 // the memory type, so it can be tied to the input operand.
5110 // This means these instructions always have a use, so we need to add a
5111 // special case to check if the atomic has only one extract_subreg use,
5112 // which itself has no uses.
5113 if ((Node->hasNUsesOfValue(1, 0) &&
5114 Node->use_begin()->isMachineOpcode() &&
5115 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5116 !Node->use_begin()->hasAnyUseOfValue(0))) {
5117 unsigned Def = MI.getOperand(0).getReg();
5119 // Change this into a noret atomic.
5120 MI.setDesc(TII->get(NoRetAtomicOp));
5121 MI.RemoveOperand(0);
5123 // If we only remove the def operand from the atomic instruction, the
5124 // extract_subreg will be left with a use of a vreg without a def.
5125 // So we need to insert an implicit_def to avoid machine verifier
5127 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5128 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5134 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5136 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5137 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5140 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5142 SDValue Ptr) const {
5143 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5145 // Build the half of the subregister with the constants before building the
5146 // full 128-bit register. If we are building multiple resource descriptors,
5147 // this will allow CSEing of the 2-component register.
5148 const SDValue Ops0[] = {
5149 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5150 buildSMovImm32(DAG, DL, 0),
5151 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5152 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5153 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5156 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5157 MVT::v2i32, Ops0), 0);
5159 // Combine the constants and the pointer.
5160 const SDValue Ops1[] = {
5161 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5163 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5165 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5168 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5171 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5172 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5173 /// of the resource descriptor) to create an offset, which is added to
5174 /// the resource pointer.
5175 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5176 SDValue Ptr, uint32_t RsrcDword1,
5177 uint64_t RsrcDword2And3) const {
5178 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5179 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5181 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5182 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5186 SDValue DataLo = buildSMovImm32(DAG, DL,
5187 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5188 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5190 const SDValue Ops[] = {
5191 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5193 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5195 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5197 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5199 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5202 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5205 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5206 const TargetRegisterClass *RC,
5207 unsigned Reg, EVT VT) const {
5208 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5210 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5211 cast<RegisterSDNode>(VReg)->getReg(), VT);
5214 //===----------------------------------------------------------------------===//
5215 // SI Inline Assembly Support
5216 //===----------------------------------------------------------------------===//
5218 std::pair<unsigned, const TargetRegisterClass *>
5219 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5220 StringRef Constraint,
5222 if (!isTypeLegal(VT))
5223 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5225 if (Constraint.size() == 1) {
5226 switch (Constraint[0]) {
5229 switch (VT.getSizeInBits()) {
5231 return std::make_pair(0U, nullptr);
5234 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5236 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5238 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5240 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5242 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5246 switch (VT.getSizeInBits()) {
5248 return std::make_pair(0U, nullptr);
5251 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5253 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5255 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5257 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5259 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5261 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5266 if (Constraint.size() > 1) {
5267 const TargetRegisterClass *RC = nullptr;
5268 if (Constraint[1] == 'v') {
5269 RC = &AMDGPU::VGPR_32RegClass;
5270 } else if (Constraint[1] == 's') {
5271 RC = &AMDGPU::SGPR_32RegClass;
5276 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5277 if (!Failed && Idx < RC->getNumRegs())
5278 return std::make_pair(RC->getRegister(Idx), RC);
5281 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5284 SITargetLowering::ConstraintType
5285 SITargetLowering::getConstraintType(StringRef Constraint) const {
5286 if (Constraint.size() == 1) {
5287 switch (Constraint[0]) {
5291 return C_RegisterClass;
5294 return TargetLowering::getConstraintType(Constraint);