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);
491 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
493 // All memory operations. Some folding on the pointer operand is done to help
494 // matching the constant offsets in the addressing modes.
495 setTargetDAGCombine(ISD::LOAD);
496 setTargetDAGCombine(ISD::STORE);
497 setTargetDAGCombine(ISD::ATOMIC_LOAD);
498 setTargetDAGCombine(ISD::ATOMIC_STORE);
499 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
500 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
501 setTargetDAGCombine(ISD::ATOMIC_SWAP);
502 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
503 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
504 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
505 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
506 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
507 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
508 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
509 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
510 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
511 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
513 setSchedulingPreference(Sched::RegPressure);
516 const SISubtarget *SITargetLowering::getSubtarget() const {
517 return static_cast<const SISubtarget *>(Subtarget);
520 //===----------------------------------------------------------------------===//
521 // TargetLowering queries
522 //===----------------------------------------------------------------------===//
524 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
526 // SI has some legal vector types, but no legal vector operations. Say no
527 // shuffles are legal in order to prefer scalarizing some vector operations.
531 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
533 unsigned IntrID) const {
535 case Intrinsic::amdgcn_atomic_inc:
536 case Intrinsic::amdgcn_atomic_dec: {
537 Info.opc = ISD::INTRINSIC_W_CHAIN;
538 Info.memVT = MVT::getVT(CI.getType());
539 Info.ptrVal = CI.getOperand(0);
542 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
543 Info.vol = !Vol || !Vol->isNullValue();
545 Info.writeMem = true;
553 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
554 SmallVectorImpl<Value*> &Ops,
555 Type *&AccessTy) const {
556 switch (II->getIntrinsicID()) {
557 case Intrinsic::amdgcn_atomic_inc:
558 case Intrinsic::amdgcn_atomic_dec: {
559 Value *Ptr = II->getArgOperand(0);
560 AccessTy = II->getType();
569 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
570 // Flat instructions do not have offsets, and only have the register
572 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
575 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
576 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
577 // additionally can do r + r + i with addr64. 32-bit has more addressing
578 // mode options. Depending on the resource constant, it can also do
579 // (i64 r0) + (i32 r1) * (i14 i).
581 // Private arrays end up using a scratch buffer most of the time, so also
582 // assume those use MUBUF instructions. Scratch loads / stores are currently
583 // implemented as mubuf instructions with offen bit set, so slightly
584 // different than the normal addr64.
585 if (!isUInt<12>(AM.BaseOffs))
588 // FIXME: Since we can split immediate into soffset and immediate offset,
589 // would it make sense to allow any immediate?
592 case 0: // r + i or just i, depending on HasBaseReg.
595 return true; // We have r + r or r + i.
602 // Allow 2 * r as r + r
603 // Or 2 * r + i is allowed as r + r + i.
605 default: // Don't allow n * r
610 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
611 const AddrMode &AM, Type *Ty,
613 // No global is ever allowed as a base.
617 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
618 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
619 // Assume the we will use FLAT for all global memory accesses
621 // FIXME: This assumption is currently wrong. On VI we still use
622 // MUBUF instructions for the r + i addressing mode. As currently
623 // implemented, the MUBUF instructions only work on buffer < 4GB.
624 // It may be possible to support > 4GB buffers with MUBUF instructions,
625 // by setting the stride value in the resource descriptor which would
626 // increase the size limit to (stride * 4GB). However, this is risky,
627 // because it has never been validated.
628 return isLegalFlatAddressingMode(AM);
631 return isLegalMUBUFAddressingMode(AM);
632 } else if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
633 // If the offset isn't a multiple of 4, it probably isn't going to be
634 // correctly aligned.
635 // FIXME: Can we get the real alignment here?
636 if (AM.BaseOffs % 4 != 0)
637 return isLegalMUBUFAddressingMode(AM);
639 // There are no SMRD extloads, so if we have to do a small type access we
640 // will use a MUBUF load.
641 // FIXME?: We also need to do this if unaligned, but we don't know the
643 if (DL.getTypeStoreSize(Ty) < 4)
644 return isLegalMUBUFAddressingMode(AM);
646 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
647 // SMRD instructions have an 8-bit, dword offset on SI.
648 if (!isUInt<8>(AM.BaseOffs / 4))
650 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
651 // On CI+, this can also be a 32-bit literal constant offset. If it fits
652 // in 8-bits, it can use a smaller encoding.
653 if (!isUInt<32>(AM.BaseOffs / 4))
655 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
656 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
657 if (!isUInt<20>(AM.BaseOffs))
660 llvm_unreachable("unhandled generation");
662 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
665 if (AM.Scale == 1 && AM.HasBaseReg)
670 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
671 return isLegalMUBUFAddressingMode(AM);
672 } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
673 AS == AMDGPUASI.REGION_ADDRESS) {
674 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
676 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
677 // an 8-bit dword offset but we don't know the alignment here.
678 if (!isUInt<16>(AM.BaseOffs))
681 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
684 if (AM.Scale == 1 && AM.HasBaseReg)
688 } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
689 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
690 // For an unknown address space, this usually means that this is for some
691 // reason being used for pure arithmetic, and not based on some addressing
692 // computation. We don't have instructions that compute pointers with any
693 // addressing modes, so treat them as having no offset like flat
695 return isLegalFlatAddressingMode(AM);
697 llvm_unreachable("unhandled address space");
701 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
704 bool *IsFast) const {
708 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
709 // which isn't a simple VT.
710 // Until MVT is extended to handle this, simply check for the size and
711 // rely on the condition below: allow accesses if the size is a multiple of 4.
712 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
713 VT.getStoreSize() > 16)) {
717 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
718 AddrSpace == AMDGPUASI.REGION_ADDRESS) {
719 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
720 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
721 // with adjacent offsets.
722 bool AlignedBy4 = (Align % 4 == 0);
724 *IsFast = AlignedBy4;
729 // FIXME: We have to be conservative here and assume that flat operations
730 // will access scratch. If we had access to the IR function, then we
731 // could determine if any private memory was used in the function.
732 if (!Subtarget->hasUnalignedScratchAccess() &&
733 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
734 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
738 if (Subtarget->hasUnalignedBufferAccess()) {
739 // If we have an uniform constant load, it still requires using a slow
740 // buffer instruction if unaligned.
742 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS) ?
743 (Align % 4 == 0) : true;
749 // Smaller than dword value must be aligned.
750 if (VT.bitsLT(MVT::i32))
753 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
754 // byte-address are ignored, thus forcing Dword alignment.
755 // This applies to private, global, and constant memory.
759 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
762 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
763 unsigned SrcAlign, bool IsMemset,
766 MachineFunction &MF) const {
767 // FIXME: Should account for address space here.
769 // The default fallback uses the private pointer size as a guess for a type to
770 // use. Make sure we switch these to 64-bit accesses.
772 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
775 if (Size >= 8 && DstAlign >= 4)
782 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
783 return AS == AMDGPUASI.GLOBAL_ADDRESS ||
784 AS == AMDGPUASI.FLAT_ADDRESS ||
785 AS == AMDGPUASI.CONSTANT_ADDRESS;
788 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
789 unsigned DestAS) const {
790 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
791 isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
794 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
795 const MemSDNode *MemNode = cast<MemSDNode>(N);
796 const Value *Ptr = MemNode->getMemOperand()->getValue();
797 const Instruction *I = dyn_cast<Instruction>(Ptr);
798 return I && I->getMetadata("amdgpu.noclobber");
801 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
802 unsigned DestAS) const {
803 // Flat -> private/local is a simple truncate.
804 // Flat -> global is no-op
805 if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
808 return isNoopAddrSpaceCast(SrcAS, DestAS);
811 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
812 const MemSDNode *MemNode = cast<MemSDNode>(N);
814 return AMDGPU::isUniformMMO(MemNode->getMemOperand());
817 TargetLoweringBase::LegalizeTypeAction
818 SITargetLowering::getPreferredVectorAction(EVT VT) const {
819 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
820 return TypeSplitVector;
822 return TargetLoweringBase::getPreferredVectorAction(VT);
825 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
827 // FIXME: Could be smarter if called for vector constants.
831 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
832 if (Subtarget->has16BitInsts() && VT == MVT::i16) {
837 // These operations are done with 32-bit instructions anyway.
849 // SimplifySetCC uses this function to determine whether or not it should
850 // create setcc with i1 operands. We don't have instructions for i1 setcc.
851 if (VT == MVT::i1 && Op == ISD::SETCC)
854 return TargetLowering::isTypeDesirableForOp(Op, VT);
857 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
860 uint64_t Offset) const {
861 const DataLayout &DL = DAG.getDataLayout();
862 MachineFunction &MF = DAG.getMachineFunction();
863 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
864 unsigned InputPtrReg = TRI->getPreloadedValue(MF,
865 SIRegisterInfo::KERNARG_SEGMENT_PTR);
867 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
868 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
869 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
870 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
871 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
872 DAG.getConstant(Offset, SL, PtrVT));
875 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
876 const SDLoc &SL, SDValue Val,
878 const ISD::InputArg *Arg) const {
879 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
881 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
882 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
885 if (MemVT.isFloatingPoint())
886 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
888 Val = DAG.getSExtOrTrunc(Val, SL, VT);
890 Val = DAG.getZExtOrTrunc(Val, SL, VT);
895 SDValue SITargetLowering::lowerKernargMemParameter(
896 SelectionDAG &DAG, EVT VT, EVT MemVT,
897 const SDLoc &SL, SDValue Chain,
898 uint64_t Offset, bool Signed,
899 const ISD::InputArg *Arg) const {
900 const DataLayout &DL = DAG.getDataLayout();
901 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
902 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
903 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
905 unsigned Align = DL.getABITypeAlignment(Ty);
907 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
908 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
909 MachineMemOperand::MONonTemporal |
910 MachineMemOperand::MODereferenceable |
911 MachineMemOperand::MOInvariant);
913 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
914 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
917 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
918 const SDLoc &SL, SDValue Chain,
919 const ISD::InputArg &Arg) const {
920 MachineFunction &MF = DAG.getMachineFunction();
921 MachineFrameInfo &MFI = MF.getFrameInfo();
923 if (Arg.Flags.isByVal()) {
924 unsigned Size = Arg.Flags.getByValSize();
925 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
926 return DAG.getFrameIndex(FrameIdx, MVT::i32);
929 unsigned ArgOffset = VA.getLocMemOffset();
930 unsigned ArgSize = VA.getValVT().getStoreSize();
932 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
934 // Create load nodes to retrieve arguments from the stack.
935 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
938 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
939 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
940 MVT MemVT = VA.getValVT();
942 switch (VA.getLocInfo()) {
945 case CCValAssign::BCvt:
946 MemVT = VA.getLocVT();
948 case CCValAssign::SExt:
949 ExtType = ISD::SEXTLOAD;
951 case CCValAssign::ZExt:
952 ExtType = ISD::ZEXTLOAD;
954 case CCValAssign::AExt:
955 ExtType = ISD::EXTLOAD;
959 ArgValue = DAG.getExtLoad(
960 ExtType, SL, VA.getLocVT(), Chain, FIN,
961 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
966 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
967 CallingConv::ID CallConv,
968 ArrayRef<ISD::InputArg> Ins,
971 SIMachineFunctionInfo *Info) {
972 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
973 const ISD::InputArg &Arg = Ins[I];
975 // First check if it's a PS input addr.
976 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
977 !Arg.Flags.isByVal() && PSInputNum <= 15) {
979 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
980 // We can safely skip PS inputs.
986 Info->markPSInputAllocated(PSInputNum);
988 Info->markPSInputEnabled(PSInputNum);
993 // Second split vertices into their elements.
994 if (Arg.VT.isVector()) {
995 ISD::InputArg NewArg = Arg;
996 NewArg.Flags.setSplit();
997 NewArg.VT = Arg.VT.getVectorElementType();
999 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1000 // three or five element vertex only needs three or five registers,
1001 // NOT four or eight.
1002 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1003 unsigned NumElements = ParamType->getVectorNumElements();
1005 for (unsigned J = 0; J != NumElements; ++J) {
1006 Splits.push_back(NewArg);
1007 NewArg.PartOffset += NewArg.VT.getStoreSize();
1010 Splits.push_back(Arg);
1015 // Allocate special inputs passed in VGPRs.
1016 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1017 MachineFunction &MF,
1018 const SIRegisterInfo &TRI,
1019 SIMachineFunctionInfo &Info) {
1020 if (Info.hasWorkItemIDX()) {
1021 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1022 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1023 CCInfo.AllocateReg(Reg);
1026 if (Info.hasWorkItemIDY()) {
1027 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1028 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1029 CCInfo.AllocateReg(Reg);
1032 if (Info.hasWorkItemIDZ()) {
1033 unsigned Reg = TRI.getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1034 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1035 CCInfo.AllocateReg(Reg);
1039 // Allocate special inputs passed in user SGPRs.
1040 static void allocateHSAUserSGPRs(CCState &CCInfo,
1041 MachineFunction &MF,
1042 const SIRegisterInfo &TRI,
1043 SIMachineFunctionInfo &Info) {
1044 if (Info.hasPrivateMemoryInputPtr()) {
1045 unsigned PrivateMemoryPtrReg = Info.addPrivateMemoryPtr(TRI);
1046 MF.addLiveIn(PrivateMemoryPtrReg, &AMDGPU::SGPR_64RegClass);
1047 CCInfo.AllocateReg(PrivateMemoryPtrReg);
1050 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1051 if (Info.hasPrivateSegmentBuffer()) {
1052 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1053 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1054 CCInfo.AllocateReg(PrivateSegmentBufferReg);
1057 if (Info.hasDispatchPtr()) {
1058 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1059 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1060 CCInfo.AllocateReg(DispatchPtrReg);
1063 if (Info.hasQueuePtr()) {
1064 unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1065 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1066 CCInfo.AllocateReg(QueuePtrReg);
1069 if (Info.hasKernargSegmentPtr()) {
1070 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1071 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1072 CCInfo.AllocateReg(InputPtrReg);
1075 if (Info.hasDispatchID()) {
1076 unsigned DispatchIDReg = Info.addDispatchID(TRI);
1077 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1078 CCInfo.AllocateReg(DispatchIDReg);
1081 if (Info.hasFlatScratchInit()) {
1082 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1083 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1084 CCInfo.AllocateReg(FlatScratchInitReg);
1087 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1088 // these from the dispatch pointer.
1091 // Allocate special input registers that are initialized per-wave.
1092 static void allocateSystemSGPRs(CCState &CCInfo,
1093 MachineFunction &MF,
1094 SIMachineFunctionInfo &Info,
1095 CallingConv::ID CallConv,
1097 if (Info.hasWorkGroupIDX()) {
1098 unsigned Reg = Info.addWorkGroupIDX();
1099 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1100 CCInfo.AllocateReg(Reg);
1103 if (Info.hasWorkGroupIDY()) {
1104 unsigned Reg = Info.addWorkGroupIDY();
1105 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1106 CCInfo.AllocateReg(Reg);
1109 if (Info.hasWorkGroupIDZ()) {
1110 unsigned Reg = Info.addWorkGroupIDZ();
1111 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1112 CCInfo.AllocateReg(Reg);
1115 if (Info.hasWorkGroupInfo()) {
1116 unsigned Reg = Info.addWorkGroupInfo();
1117 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1118 CCInfo.AllocateReg(Reg);
1121 if (Info.hasPrivateSegmentWaveByteOffset()) {
1122 // Scratch wave offset passed in system SGPR.
1123 unsigned PrivateSegmentWaveByteOffsetReg;
1126 PrivateSegmentWaveByteOffsetReg =
1127 Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1129 // This is true if the scratch wave byte offset doesn't have a fixed
1131 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1132 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1133 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1136 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1138 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1139 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1143 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1144 MachineFunction &MF,
1145 const SIRegisterInfo &TRI,
1146 SIMachineFunctionInfo &Info,
1148 // Now that we've figured out where the scratch register inputs are, see if
1149 // should reserve the arguments and use them directly.
1150 MachineFrameInfo &MFI = MF.getFrameInfo();
1151 bool HasStackObjects = MFI.hasStackObjects();
1153 // Record that we know we have non-spill stack objects so we don't need to
1154 // check all stack objects later.
1155 if (HasStackObjects)
1156 Info.setHasNonSpillStackObjects(true);
1158 // Everything live out of a block is spilled with fast regalloc, so it's
1159 // almost certain that spilling will be required.
1160 if (TM.getOptLevel() == CodeGenOpt::None)
1161 HasStackObjects = true;
1163 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1164 if (ST.isAmdCodeObjectV2(MF)) {
1165 if (HasStackObjects) {
1166 // If we have stack objects, we unquestionably need the private buffer
1167 // resource. For the Code Object V2 ABI, this will be the first 4 user
1168 // SGPR inputs. We can reserve those and use them directly.
1170 unsigned PrivateSegmentBufferReg = TRI.getPreloadedValue(
1171 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1172 Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1174 unsigned PrivateSegmentWaveByteOffsetReg = TRI.getPreloadedValue(
1175 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1176 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1178 unsigned ReservedBufferReg
1179 = TRI.reservedPrivateSegmentBufferReg(MF);
1180 unsigned ReservedOffsetReg
1181 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1183 // We tentatively reserve the last registers (skipping the last two
1184 // which may contain VCC). After register allocation, we'll replace
1185 // these with the ones immediately after those which were really
1186 // allocated. In the prologue copies will be inserted from the argument
1187 // to these reserved registers.
1188 Info.setScratchRSrcReg(ReservedBufferReg);
1189 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1192 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1194 // Without HSA, relocations are used for the scratch pointer and the
1195 // buffer resource setup is always inserted in the prologue. Scratch wave
1196 // offset is still in an input SGPR.
1197 Info.setScratchRSrcReg(ReservedBufferReg);
1199 if (HasStackObjects) {
1200 unsigned ScratchWaveOffsetReg = TRI.getPreloadedValue(
1201 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1202 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1204 unsigned ReservedOffsetReg
1205 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1206 Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1211 unsigned ReservedStackPtrOffsetReg = TRI.reservedStackPtrOffsetReg(MF);
1212 Info.setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
1214 assert(Info.getStackPtrOffsetReg() != Info.getFrameOffsetReg());
1215 assert(!TRI.isSubRegister(Info.getScratchRSrcReg(),
1216 Info.getStackPtrOffsetReg()));
1220 SDValue SITargetLowering::LowerFormalArguments(
1221 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1222 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1223 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1224 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1226 MachineFunction &MF = DAG.getMachineFunction();
1227 FunctionType *FType = MF.getFunction()->getFunctionType();
1228 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1229 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1231 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1232 const Function *Fn = MF.getFunction();
1233 DiagnosticInfoUnsupported NoGraphicsHSA(
1234 *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1235 DAG.getContext()->diagnose(NoGraphicsHSA);
1236 return DAG.getEntryNode();
1239 // Create stack objects that are used for emitting debugger prologue if
1240 // "amdgpu-debugger-emit-prologue" attribute was specified.
1241 if (ST.debuggerEmitPrologue())
1242 createDebuggerPrologueStackObjects(MF);
1244 SmallVector<ISD::InputArg, 16> Splits;
1245 SmallVector<CCValAssign, 16> ArgLocs;
1246 BitVector Skipped(Ins.size());
1247 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1250 bool IsShader = AMDGPU::isShader(CallConv);
1251 bool IsKernel = AMDGPU::isKernel(CallConv);
1252 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1255 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1257 // At least one interpolation mode must be enabled or else the GPU will
1260 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1261 // set PSInputAddr, the user wants to enable some bits after the compilation
1262 // based on run-time states. Since we can't know what the final PSInputEna
1263 // will look like, so we shouldn't do anything here and the user should take
1264 // responsibility for the correct programming.
1266 // Otherwise, the following restrictions apply:
1267 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1268 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1270 if (CallConv == CallingConv::AMDGPU_PS &&
1271 ((Info->getPSInputAddr() & 0x7F) == 0 ||
1272 ((Info->getPSInputAddr() & 0xF) == 0 &&
1273 Info->isPSInputAllocated(11)))) {
1274 CCInfo.AllocateReg(AMDGPU::VGPR0);
1275 CCInfo.AllocateReg(AMDGPU::VGPR1);
1276 Info->markPSInputAllocated(0);
1277 Info->markPSInputEnabled(0);
1280 assert(!Info->hasDispatchPtr() &&
1281 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1282 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1283 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1284 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1285 !Info->hasWorkItemIDZ());
1286 } else if (IsKernel) {
1287 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1289 Splits.append(Ins.begin(), Ins.end());
1293 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1294 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1298 analyzeFormalArgumentsCompute(CCInfo, Ins);
1300 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1301 CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1304 SmallVector<SDValue, 16> Chains;
1306 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1307 const ISD::InputArg &Arg = Ins[i];
1309 InVals.push_back(DAG.getUNDEF(Arg.VT));
1313 CCValAssign &VA = ArgLocs[ArgIdx++];
1314 MVT VT = VA.getLocVT();
1316 if (IsEntryFunc && VA.isMemLoc()) {
1318 EVT MemVT = VA.getLocVT();
1320 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1321 VA.getLocMemOffset();
1322 Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1324 // The first 36 bytes of the input buffer contains information about
1325 // thread group and global sizes.
1326 SDValue Arg = lowerKernargMemParameter(
1327 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1328 Chains.push_back(Arg.getValue(1));
1331 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1332 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1333 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1334 // On SI local pointers are just offsets into LDS, so they are always
1335 // less than 16-bits. On CI and newer they could potentially be
1336 // real pointers, so we can't guarantee their size.
1337 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1338 DAG.getValueType(MVT::i16));
1341 InVals.push_back(Arg);
1343 } else if (!IsEntryFunc && VA.isMemLoc()) {
1344 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1345 InVals.push_back(Val);
1346 if (!Arg.Flags.isByVal())
1347 Chains.push_back(Val.getValue(1));
1351 assert(VA.isRegLoc() && "Parameter must be in a register!");
1353 unsigned Reg = VA.getLocReg();
1354 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1356 Reg = MF.addLiveIn(Reg, RC);
1357 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1359 if (IsShader && Arg.VT.isVector()) {
1360 // Build a vector from the registers
1361 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1362 unsigned NumElements = ParamType->getVectorNumElements();
1364 SmallVector<SDValue, 4> Regs;
1365 Regs.push_back(Val);
1366 for (unsigned j = 1; j != NumElements; ++j) {
1367 Reg = ArgLocs[ArgIdx++].getLocReg();
1368 Reg = MF.addLiveIn(Reg, RC);
1370 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1371 Regs.push_back(Copy);
1374 // Fill up the missing vector elements
1375 NumElements = Arg.VT.getVectorNumElements() - NumElements;
1376 Regs.append(NumElements, DAG.getUNDEF(VT));
1378 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1382 InVals.push_back(Val);
1385 const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1387 // TODO: Could maybe omit SP if only tail calls?
1388 bool NeedSP = FrameInfo.hasCalls() || FrameInfo.hasVarSizedObjects();
1390 // Start adding system SGPRs.
1392 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1393 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info, NeedSP);
1395 CCInfo.AllocateReg(Info->getScratchRSrcReg());
1396 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1397 CCInfo.AllocateReg(Info->getFrameOffsetReg());
1400 unsigned StackPtrReg = findFirstFreeSGPR(CCInfo);
1401 CCInfo.AllocateReg(StackPtrReg);
1402 Info->setStackPtrOffsetReg(StackPtrReg);
1406 return Chains.empty() ? Chain :
1407 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1410 // TODO: If return values can't fit in registers, we should return as many as
1411 // possible in registers before passing on stack.
1412 bool SITargetLowering::CanLowerReturn(
1413 CallingConv::ID CallConv,
1414 MachineFunction &MF, bool IsVarArg,
1415 const SmallVectorImpl<ISD::OutputArg> &Outs,
1416 LLVMContext &Context) const {
1417 // Replacing returns with sret/stack usage doesn't make sense for shaders.
1418 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1419 // for shaders. Vector types should be explicitly handled by CC.
1420 if (AMDGPU::isEntryFunctionCC(CallConv))
1423 SmallVector<CCValAssign, 16> RVLocs;
1424 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1425 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1429 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1431 const SmallVectorImpl<ISD::OutputArg> &Outs,
1432 const SmallVectorImpl<SDValue> &OutVals,
1433 const SDLoc &DL, SelectionDAG &DAG) const {
1434 MachineFunction &MF = DAG.getMachineFunction();
1435 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1437 if (AMDGPU::isKernel(CallConv)) {
1438 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1442 bool IsShader = AMDGPU::isShader(CallConv);
1444 Info->setIfReturnsVoid(Outs.size() == 0);
1445 bool IsWaveEnd = Info->returnsVoid() && IsShader;
1447 SmallVector<ISD::OutputArg, 48> Splits;
1448 SmallVector<SDValue, 48> SplitVals;
1450 // Split vectors into their elements.
1451 for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1452 const ISD::OutputArg &Out = Outs[i];
1454 if (IsShader && Out.VT.isVector()) {
1455 MVT VT = Out.VT.getVectorElementType();
1456 ISD::OutputArg NewOut = Out;
1457 NewOut.Flags.setSplit();
1460 // We want the original number of vector elements here, e.g.
1461 // three or five, not four or eight.
1462 unsigned NumElements = Out.ArgVT.getVectorNumElements();
1464 for (unsigned j = 0; j != NumElements; ++j) {
1465 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1466 DAG.getConstant(j, DL, MVT::i32));
1467 SplitVals.push_back(Elem);
1468 Splits.push_back(NewOut);
1469 NewOut.PartOffset += NewOut.VT.getStoreSize();
1472 SplitVals.push_back(OutVals[i]);
1473 Splits.push_back(Out);
1477 // CCValAssign - represent the assignment of the return value to a location.
1478 SmallVector<CCValAssign, 48> RVLocs;
1480 // CCState - Info about the registers and stack slots.
1481 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1484 // Analyze outgoing return values.
1485 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
1488 SmallVector<SDValue, 48> RetOps;
1489 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491 // Add return address for callable functions.
1492 if (!Info->isEntryFunction()) {
1493 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1494 SDValue ReturnAddrReg = CreateLiveInRegister(
1495 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
1497 // FIXME: Should be able to use a vreg here, but need a way to prevent it
1498 // from being allcoated to a CSR.
1500 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
1503 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
1504 Flag = Chain.getValue(1);
1506 RetOps.push_back(PhysReturnAddrReg);
1509 // Copy the result values into the output registers.
1510 for (unsigned i = 0, realRVLocIdx = 0;
1512 ++i, ++realRVLocIdx) {
1513 CCValAssign &VA = RVLocs[i];
1514 assert(VA.isRegLoc() && "Can only return in registers!");
1515 // TODO: Partially return in registers if return values don't fit.
1517 SDValue Arg = SplitVals[realRVLocIdx];
1519 // Copied from other backends.
1520 switch (VA.getLocInfo()) {
1521 case CCValAssign::Full:
1523 case CCValAssign::BCvt:
1524 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1526 case CCValAssign::SExt:
1527 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1529 case CCValAssign::ZExt:
1530 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
1532 case CCValAssign::AExt:
1533 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
1536 llvm_unreachable("Unknown loc info!");
1539 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1540 Flag = Chain.getValue(1);
1541 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1544 // FIXME: Does sret work properly?
1546 // Update chain and glue.
1549 RetOps.push_back(Flag);
1551 unsigned Opc = AMDGPUISD::ENDPGM;
1553 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
1554 return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1557 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1558 SelectionDAG &DAG) const {
1559 unsigned Reg = StringSwitch<unsigned>(RegName)
1560 .Case("m0", AMDGPU::M0)
1561 .Case("exec", AMDGPU::EXEC)
1562 .Case("exec_lo", AMDGPU::EXEC_LO)
1563 .Case("exec_hi", AMDGPU::EXEC_HI)
1564 .Case("flat_scratch", AMDGPU::FLAT_SCR)
1565 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1566 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1567 .Default(AMDGPU::NoRegister);
1569 if (Reg == AMDGPU::NoRegister) {
1570 report_fatal_error(Twine("invalid register name \""
1571 + StringRef(RegName) + "\"."));
1575 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1576 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1577 report_fatal_error(Twine("invalid register \""
1578 + StringRef(RegName) + "\" for subtarget."));
1583 case AMDGPU::EXEC_LO:
1584 case AMDGPU::EXEC_HI:
1585 case AMDGPU::FLAT_SCR_LO:
1586 case AMDGPU::FLAT_SCR_HI:
1587 if (VT.getSizeInBits() == 32)
1591 case AMDGPU::FLAT_SCR:
1592 if (VT.getSizeInBits() == 64)
1596 llvm_unreachable("missing register type checking");
1599 report_fatal_error(Twine("invalid type for register \""
1600 + StringRef(RegName) + "\"."));
1603 // If kill is not the last instruction, split the block so kill is always a
1604 // proper terminator.
1605 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1606 MachineBasicBlock *BB) const {
1607 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1609 MachineBasicBlock::iterator SplitPoint(&MI);
1612 if (SplitPoint == BB->end()) {
1613 // Don't bother with a new block.
1614 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1618 MachineFunction *MF = BB->getParent();
1619 MachineBasicBlock *SplitBB
1620 = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1622 MF->insert(++MachineFunction::iterator(BB), SplitBB);
1623 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1625 SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1626 BB->addSuccessor(SplitBB);
1628 MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1632 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1633 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1634 // will only do one iteration. In the worst case, this will loop 64 times.
1636 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1637 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1638 const SIInstrInfo *TII,
1639 MachineRegisterInfo &MRI,
1640 MachineBasicBlock &OrigBB,
1641 MachineBasicBlock &LoopBB,
1643 const MachineOperand &IdxReg,
1647 unsigned InitSaveExecReg,
1649 bool UseGPRIdxMode) {
1650 MachineBasicBlock::iterator I = LoopBB.begin();
1652 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1653 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1654 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1655 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1657 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1663 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1664 .addReg(InitSaveExecReg)
1669 // Read the next variant <- also loop target.
1670 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1671 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1673 // Compare the just read M0 value to all possible Idx values.
1674 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1675 .addReg(CurrentIdxReg)
1676 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1678 if (UseGPRIdxMode) {
1681 IdxReg = CurrentIdxReg;
1683 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1684 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1685 .addReg(CurrentIdxReg, RegState::Kill)
1689 MachineInstr *SetIdx =
1690 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1691 .addReg(IdxReg, RegState::Kill);
1692 SetIdx->getOperand(2).setIsUndef();
1694 // Move index from VCC into M0
1696 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1697 .addReg(CurrentIdxReg, RegState::Kill);
1699 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1700 .addReg(CurrentIdxReg, RegState::Kill)
1705 // Update EXEC, save the original EXEC value to VCC.
1706 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1707 .addReg(CondReg, RegState::Kill);
1709 MRI.setSimpleHint(NewExec, CondReg);
1711 // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1712 MachineInstr *InsertPt =
1713 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1714 .addReg(AMDGPU::EXEC)
1717 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1720 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1721 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1724 return InsertPt->getIterator();
1727 // This has slightly sub-optimal regalloc when the source vector is killed by
1728 // the read. The register allocator does not understand that the kill is
1729 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1730 // subregister from it, using 1 more VGPR than necessary. This was saved when
1731 // this was expanded after register allocation.
1732 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1733 MachineBasicBlock &MBB,
1735 unsigned InitResultReg,
1738 bool UseGPRIdxMode) {
1739 MachineFunction *MF = MBB.getParent();
1740 MachineRegisterInfo &MRI = MF->getRegInfo();
1741 const DebugLoc &DL = MI.getDebugLoc();
1742 MachineBasicBlock::iterator I(&MI);
1744 unsigned DstReg = MI.getOperand(0).getReg();
1745 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1746 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1748 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1750 // Save the EXEC mask
1751 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1752 .addReg(AMDGPU::EXEC);
1754 // To insert the loop we need to split the block. Move everything after this
1755 // point to a new block, and insert a new empty block between the two.
1756 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1757 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1758 MachineFunction::iterator MBBI(MBB);
1761 MF->insert(MBBI, LoopBB);
1762 MF->insert(MBBI, RemainderBB);
1764 LoopBB->addSuccessor(LoopBB);
1765 LoopBB->addSuccessor(RemainderBB);
1767 // Move the rest of the block into a new block.
1768 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1769 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1771 MBB.addSuccessor(LoopBB);
1773 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1775 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1776 InitResultReg, DstReg, PhiReg, TmpExec,
1777 Offset, UseGPRIdxMode);
1779 MachineBasicBlock::iterator First = RemainderBB->begin();
1780 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1786 // Returns subreg index, offset
1787 static std::pair<unsigned, int>
1788 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1789 const TargetRegisterClass *SuperRC,
1792 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
1794 // Skip out of bounds offsets, or else we would end up using an undefined
1796 if (Offset >= NumElts || Offset < 0)
1797 return std::make_pair(AMDGPU::sub0, Offset);
1799 return std::make_pair(AMDGPU::sub0 + Offset, 0);
1802 // Return true if the index is an SGPR and was set.
1803 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1804 MachineRegisterInfo &MRI,
1808 bool IsIndirectSrc) {
1809 MachineBasicBlock *MBB = MI.getParent();
1810 const DebugLoc &DL = MI.getDebugLoc();
1811 MachineBasicBlock::iterator I(&MI);
1813 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1814 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1816 assert(Idx->getReg() != AMDGPU::NoRegister);
1818 if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1821 if (UseGPRIdxMode) {
1822 unsigned IdxMode = IsIndirectSrc ?
1823 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1825 MachineInstr *SetOn =
1826 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1830 SetOn->getOperand(3).setIsUndef();
1832 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1833 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1836 MachineInstr *SetOn =
1837 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1838 .addReg(Tmp, RegState::Kill)
1841 SetOn->getOperand(3).setIsUndef();
1848 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1851 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1859 // Control flow needs to be inserted if indexing with a VGPR.
1860 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1861 MachineBasicBlock &MBB,
1862 const SISubtarget &ST) {
1863 const SIInstrInfo *TII = ST.getInstrInfo();
1864 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1865 MachineFunction *MF = MBB.getParent();
1866 MachineRegisterInfo &MRI = MF->getRegInfo();
1868 unsigned Dst = MI.getOperand(0).getReg();
1869 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1870 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1872 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1875 std::tie(SubReg, Offset)
1876 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1878 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1880 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1881 MachineBasicBlock::iterator I(&MI);
1882 const DebugLoc &DL = MI.getDebugLoc();
1884 if (UseGPRIdxMode) {
1885 // TODO: Look at the uses to avoid the copy. This may require rescheduling
1886 // to avoid interfering with other uses, so probably requires a new
1887 // optimization pass.
1888 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1889 .addReg(SrcReg, RegState::Undef, SubReg)
1890 .addReg(SrcReg, RegState::Implicit)
1891 .addReg(AMDGPU::M0, RegState::Implicit);
1892 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1894 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1895 .addReg(SrcReg, RegState::Undef, SubReg)
1896 .addReg(SrcReg, RegState::Implicit);
1899 MI.eraseFromParent();
1904 const DebugLoc &DL = MI.getDebugLoc();
1905 MachineBasicBlock::iterator I(&MI);
1907 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1908 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1910 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1912 if (UseGPRIdxMode) {
1913 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1914 .addImm(0) // Reset inside loop.
1915 .addImm(VGPRIndexMode::SRC0_ENABLE);
1916 SetOn->getOperand(3).setIsUndef();
1918 // Disable again after the loop.
1919 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1922 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1923 MachineBasicBlock *LoopBB = InsPt->getParent();
1925 if (UseGPRIdxMode) {
1926 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1927 .addReg(SrcReg, RegState::Undef, SubReg)
1928 .addReg(SrcReg, RegState::Implicit)
1929 .addReg(AMDGPU::M0, RegState::Implicit);
1931 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1932 .addReg(SrcReg, RegState::Undef, SubReg)
1933 .addReg(SrcReg, RegState::Implicit);
1936 MI.eraseFromParent();
1941 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
1942 const TargetRegisterClass *VecRC) {
1943 switch (TRI.getRegSizeInBits(*VecRC)) {
1945 return AMDGPU::V_MOVRELD_B32_V1;
1947 return AMDGPU::V_MOVRELD_B32_V2;
1948 case 128: // 16 bytes
1949 return AMDGPU::V_MOVRELD_B32_V4;
1950 case 256: // 32 bytes
1951 return AMDGPU::V_MOVRELD_B32_V8;
1952 case 512: // 64 bytes
1953 return AMDGPU::V_MOVRELD_B32_V16;
1955 llvm_unreachable("unsupported size for MOVRELD pseudos");
1959 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1960 MachineBasicBlock &MBB,
1961 const SISubtarget &ST) {
1962 const SIInstrInfo *TII = ST.getInstrInfo();
1963 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1964 MachineFunction *MF = MBB.getParent();
1965 MachineRegisterInfo &MRI = MF->getRegInfo();
1967 unsigned Dst = MI.getOperand(0).getReg();
1968 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1969 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1970 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1971 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1972 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1974 // This can be an immediate, but will be folded later.
1975 assert(Val->getReg());
1978 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1981 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
1983 if (Idx->getReg() == AMDGPU::NoRegister) {
1984 MachineBasicBlock::iterator I(&MI);
1985 const DebugLoc &DL = MI.getDebugLoc();
1987 assert(Offset == 0);
1989 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1994 MI.eraseFromParent();
1998 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1999 MachineBasicBlock::iterator I(&MI);
2000 const DebugLoc &DL = MI.getDebugLoc();
2002 if (UseGPRIdxMode) {
2003 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2004 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
2006 .addReg(Dst, RegState::ImplicitDefine)
2007 .addReg(SrcVec->getReg(), RegState::Implicit)
2008 .addReg(AMDGPU::M0, RegState::Implicit);
2010 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2012 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2014 BuildMI(MBB, I, DL, MovRelDesc)
2015 .addReg(Dst, RegState::Define)
2016 .addReg(SrcVec->getReg())
2018 .addImm(SubReg - AMDGPU::sub0);
2021 MI.eraseFromParent();
2026 MRI.clearKillFlags(Val->getReg());
2028 const DebugLoc &DL = MI.getDebugLoc();
2030 if (UseGPRIdxMode) {
2031 MachineBasicBlock::iterator I(&MI);
2033 MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2034 .addImm(0) // Reset inside loop.
2035 .addImm(VGPRIndexMode::DST_ENABLE);
2036 SetOn->getOperand(3).setIsUndef();
2038 // Disable again after the loop.
2039 BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2042 unsigned PhiReg = MRI.createVirtualRegister(VecRC);
2044 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
2045 Offset, UseGPRIdxMode);
2046 MachineBasicBlock *LoopBB = InsPt->getParent();
2048 if (UseGPRIdxMode) {
2049 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
2050 .addReg(PhiReg, RegState::Undef, SubReg) // vdst
2052 .addReg(Dst, RegState::ImplicitDefine)
2053 .addReg(PhiReg, RegState::Implicit)
2054 .addReg(AMDGPU::M0, RegState::Implicit);
2056 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
2058 BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
2059 .addReg(Dst, RegState::Define)
2062 .addImm(SubReg - AMDGPU::sub0);
2065 MI.eraseFromParent();
2070 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
2071 MachineInstr &MI, MachineBasicBlock *BB) const {
2073 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2074 MachineFunction *MF = BB->getParent();
2075 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
2077 if (TII->isMIMG(MI)) {
2078 if (!MI.memoperands_empty())
2080 // Add a memoperand for mimg instructions so that they aren't assumed to
2081 // be ordered memory instuctions.
2083 MachinePointerInfo PtrInfo(MFI->getImagePSV());
2084 MachineMemOperand::Flags Flags = MachineMemOperand::MODereferenceable;
2086 Flags |= MachineMemOperand::MOStore;
2089 Flags |= MachineMemOperand::MOLoad;
2091 auto MMO = MF->getMachineMemOperand(PtrInfo, Flags, 0, 0);
2092 MI.addMemOperand(*MF, MMO);
2096 switch (MI.getOpcode()) {
2097 case AMDGPU::SI_INIT_M0:
2098 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
2099 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2100 .add(MI.getOperand(0));
2101 MI.eraseFromParent();
2104 case AMDGPU::SI_INIT_EXEC:
2105 // This should be before all vector instructions.
2106 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
2108 .addImm(MI.getOperand(0).getImm());
2109 MI.eraseFromParent();
2112 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
2113 // Extract the thread count from an SGPR input and set EXEC accordingly.
2114 // Since BFM can't shift by 64, handle that case with CMP + CMOV.
2116 // S_BFE_U32 count, input, {shift, 7}
2117 // S_BFM_B64 exec, count, 0
2118 // S_CMP_EQ_U32 count, 64
2119 // S_CMOV_B64 exec, -1
2120 MachineInstr *FirstMI = &*BB->begin();
2121 MachineRegisterInfo &MRI = MF->getRegInfo();
2122 unsigned InputReg = MI.getOperand(0).getReg();
2123 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2126 // Move the COPY of the input reg to the beginning, so that we can use it.
2127 for (auto I = BB->begin(); I != &MI; I++) {
2128 if (I->getOpcode() != TargetOpcode::COPY ||
2129 I->getOperand(0).getReg() != InputReg)
2133 FirstMI = &*++BB->begin();
2135 I->removeFromParent();
2136 BB->insert(FirstMI, &*I);
2144 // This should be before all vector instructions.
2145 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
2147 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
2148 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
2152 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
2153 .addReg(CountReg, RegState::Kill)
2155 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
2158 MI.eraseFromParent();
2162 case AMDGPU::GET_GROUPSTATICSIZE: {
2163 DebugLoc DL = MI.getDebugLoc();
2164 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
2165 .add(MI.getOperand(0))
2166 .addImm(MFI->getLDSSize());
2167 MI.eraseFromParent();
2170 case AMDGPU::SI_INDIRECT_SRC_V1:
2171 case AMDGPU::SI_INDIRECT_SRC_V2:
2172 case AMDGPU::SI_INDIRECT_SRC_V4:
2173 case AMDGPU::SI_INDIRECT_SRC_V8:
2174 case AMDGPU::SI_INDIRECT_SRC_V16:
2175 return emitIndirectSrc(MI, *BB, *getSubtarget());
2176 case AMDGPU::SI_INDIRECT_DST_V1:
2177 case AMDGPU::SI_INDIRECT_DST_V2:
2178 case AMDGPU::SI_INDIRECT_DST_V4:
2179 case AMDGPU::SI_INDIRECT_DST_V8:
2180 case AMDGPU::SI_INDIRECT_DST_V16:
2181 return emitIndirectDst(MI, *BB, *getSubtarget());
2182 case AMDGPU::SI_KILL:
2183 return splitKillBlock(MI, BB);
2184 case AMDGPU::V_CNDMASK_B64_PSEUDO: {
2185 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
2187 unsigned Dst = MI.getOperand(0).getReg();
2188 unsigned Src0 = MI.getOperand(1).getReg();
2189 unsigned Src1 = MI.getOperand(2).getReg();
2190 const DebugLoc &DL = MI.getDebugLoc();
2191 unsigned SrcCond = MI.getOperand(3).getReg();
2193 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2194 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2196 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
2197 .addReg(Src0, 0, AMDGPU::sub0)
2198 .addReg(Src1, 0, AMDGPU::sub0)
2200 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
2201 .addReg(Src0, 0, AMDGPU::sub1)
2202 .addReg(Src1, 0, AMDGPU::sub1)
2205 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
2207 .addImm(AMDGPU::sub0)
2209 .addImm(AMDGPU::sub1);
2210 MI.eraseFromParent();
2213 case AMDGPU::SI_BR_UNDEF: {
2214 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2215 const DebugLoc &DL = MI.getDebugLoc();
2216 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
2217 .add(MI.getOperand(0));
2218 Br->getOperand(1).setIsUndef(true); // read undef SCC
2219 MI.eraseFromParent();
2223 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
2227 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
2228 // This currently forces unfolding various combinations of fsub into fma with
2229 // free fneg'd operands. As long as we have fast FMA (controlled by
2230 // isFMAFasterThanFMulAndFAdd), we should perform these.
2232 // When fma is quarter rate, for f64 where add / sub are at best half rate,
2233 // most of these combines appear to be cycle neutral but save on instruction
2234 // count / code size.
2238 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
2240 if (!VT.isVector()) {
2243 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
2246 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
2247 // TODO: Should i16 be used always if legal? For now it would force VALU
2249 return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
2252 // Answering this is somewhat tricky and depends on the specific device which
2253 // have different rates for fma or all f64 operations.
2255 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
2256 // regardless of which device (although the number of cycles differs between
2257 // devices), so it is always profitable for f64.
2259 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
2260 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
2261 // which we can always do even without fused FP ops since it returns the same
2262 // result as the separate operations and since it is always full
2263 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
2264 // however does not support denormals, so we do report fma as faster if we have
2265 // a fast fma device and require denormals.
2267 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
2268 VT = VT.getScalarType();
2270 switch (VT.getSimpleVT().SimpleTy) {
2272 // This is as fast on some subtargets. However, we always have full rate f32
2273 // mad available which returns the same result as the separate operations
2274 // which we should prefer over fma. We can't use this if we want to support
2275 // denormals, so only report this in these cases.
2276 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
2280 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
2288 //===----------------------------------------------------------------------===//
2289 // Custom DAG Lowering Operations
2290 //===----------------------------------------------------------------------===//
2292 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2293 switch (Op.getOpcode()) {
2294 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2295 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2297 SDValue Result = LowerLOAD(Op, DAG);
2298 assert((!Result.getNode() ||
2299 Result.getNode()->getNumValues() == 2) &&
2300 "Load should return a value and a chain");
2306 return LowerTrig(Op, DAG);
2307 case ISD::SELECT: return LowerSELECT(Op, DAG);
2308 case ISD::FDIV: return LowerFDIV(Op, DAG);
2309 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
2310 case ISD::STORE: return LowerSTORE(Op, DAG);
2311 case ISD::GlobalAddress: {
2312 MachineFunction &MF = DAG.getMachineFunction();
2313 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2314 return LowerGlobalAddress(MFI, Op, DAG);
2316 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2317 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2318 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
2319 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
2320 case ISD::INSERT_VECTOR_ELT:
2321 return lowerINSERT_VECTOR_ELT(Op, DAG);
2322 case ISD::EXTRACT_VECTOR_ELT:
2323 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2325 return lowerFP_ROUND(Op, DAG);
2328 case ISD::DEBUGTRAP:
2329 return lowerTRAP(Op, DAG);
2334 void SITargetLowering::ReplaceNodeResults(SDNode *N,
2335 SmallVectorImpl<SDValue> &Results,
2336 SelectionDAG &DAG) const {
2337 switch (N->getOpcode()) {
2338 case ISD::INSERT_VECTOR_ELT: {
2339 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
2340 Results.push_back(Res);
2343 case ISD::EXTRACT_VECTOR_ELT: {
2344 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
2345 Results.push_back(Res);
2348 case ISD::INTRINSIC_WO_CHAIN: {
2349 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2351 case Intrinsic::amdgcn_cvt_pkrtz: {
2352 SDValue Src0 = N->getOperand(1);
2353 SDValue Src1 = N->getOperand(2);
2355 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
2358 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
2367 EVT VT = N->getValueType(0);
2368 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2369 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
2370 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
2372 EVT SelectVT = NewVT;
2373 if (NewVT.bitsLT(MVT::i32)) {
2374 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
2375 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
2376 SelectVT = MVT::i32;
2379 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
2380 N->getOperand(0), LHS, RHS);
2382 if (NewVT != SelectVT)
2383 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
2384 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
2392 /// \brief Helper function for LowerBRCOND
2393 static SDNode *findUser(SDValue Value, unsigned Opcode) {
2395 SDNode *Parent = Value.getNode();
2396 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
2399 if (I.getUse().get() != Value)
2402 if (I->getOpcode() == Opcode)
2408 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
2409 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
2410 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
2411 case Intrinsic::amdgcn_if:
2412 return AMDGPUISD::IF;
2413 case Intrinsic::amdgcn_else:
2414 return AMDGPUISD::ELSE;
2415 case Intrinsic::amdgcn_loop:
2416 return AMDGPUISD::LOOP;
2417 case Intrinsic::amdgcn_end_cf:
2418 llvm_unreachable("should not occur");
2424 // break, if_break, else_break are all only used as inputs to loop, not
2425 // directly as branch conditions.
2429 void SITargetLowering::createDebuggerPrologueStackObjects(
2430 MachineFunction &MF) const {
2431 // Create stack objects that are used for emitting debugger prologue.
2433 // Debugger prologue writes work group IDs and work item IDs to scratch memory
2434 // at fixed location in the following format:
2435 // offset 0: work group ID x
2436 // offset 4: work group ID y
2437 // offset 8: work group ID z
2438 // offset 16: work item ID x
2439 // offset 20: work item ID y
2440 // offset 24: work item ID z
2441 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2444 // For each dimension:
2445 for (unsigned i = 0; i < 3; ++i) {
2446 // Create fixed stack object for work group ID.
2447 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
2448 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
2449 // Create fixed stack object for work item ID.
2450 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
2451 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
2455 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
2456 const Triple &TT = getTargetMachine().getTargetTriple();
2457 return GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS &&
2458 AMDGPU::shouldEmitConstantsToTextSection(TT);
2461 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
2462 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2463 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2464 !shouldEmitFixup(GV) &&
2465 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2468 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
2469 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
2472 /// This transforms the control flow intrinsics to get the branch destination as
2473 /// last parameter, also switches branch target with BR if the need arise
2474 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
2475 SelectionDAG &DAG) const {
2478 SDNode *Intr = BRCOND.getOperand(1).getNode();
2479 SDValue Target = BRCOND.getOperand(2);
2480 SDNode *BR = nullptr;
2481 SDNode *SetCC = nullptr;
2483 if (Intr->getOpcode() == ISD::SETCC) {
2484 // As long as we negate the condition everything is fine
2486 Intr = SetCC->getOperand(0).getNode();
2489 // Get the target from BR if we don't negate the condition
2490 BR = findUser(BRCOND, ISD::BR);
2491 Target = BR->getOperand(1);
2494 // FIXME: This changes the types of the intrinsics instead of introducing new
2495 // nodes with the correct types.
2496 // e.g. llvm.amdgcn.loop
2498 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
2499 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
2501 unsigned CFNode = isCFIntrinsic(Intr);
2503 // This is a uniform branch so we don't need to legalize.
2507 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
2508 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
2511 (SetCC->getConstantOperandVal(1) == 1 &&
2512 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
2515 // operands of the new intrinsic call
2516 SmallVector<SDValue, 4> Ops;
2518 Ops.push_back(BRCOND.getOperand(0));
2520 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
2521 Ops.push_back(Target);
2523 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2525 // build the new intrinsic call
2526 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
2531 BRCOND.getOperand(0)
2534 Result = DAG.getMergeValues(Ops, DL).getNode();
2538 // Give the branch instruction our target
2541 BRCOND.getOperand(2)
2543 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2544 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2545 BR = NewBR.getNode();
2548 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2550 // Copy the intrinsic results to registers
2551 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2552 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2556 Chain = DAG.getCopyToReg(
2558 CopyToReg->getOperand(1),
2559 SDValue(Result, i - 1),
2562 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2565 // Remove the old intrinsic from the chain
2566 DAG.ReplaceAllUsesOfValueWith(
2567 SDValue(Intr, Intr->getNumValues() - 1),
2568 Intr->getOperand(0));
2573 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2577 return Op.getValueType().bitsLE(VT) ?
2578 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2579 DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2582 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2583 assert(Op.getValueType() == MVT::f16 &&
2584 "Do not know how to custom lower FP_ROUND for non-f16 type");
2586 SDValue Src = Op.getOperand(0);
2587 EVT SrcVT = Src.getValueType();
2588 if (SrcVT != MVT::f64)
2593 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2594 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2595 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2598 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
2600 MachineFunction &MF = DAG.getMachineFunction();
2601 SDValue Chain = Op.getOperand(0);
2603 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
2604 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
2606 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
2607 Subtarget->isTrapHandlerEnabled()) {
2608 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2609 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2610 assert(UserSGPR != AMDGPU::NoRegister);
2612 SDValue QueuePtr = CreateLiveInRegister(
2613 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2615 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
2617 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
2618 QueuePtr, SDValue());
2622 DAG.getTargetConstant(TrapID, SL, MVT::i16),
2627 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
2631 case SISubtarget::TrapIDLLVMTrap:
2632 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
2633 case SISubtarget::TrapIDLLVMDebugTrap: {
2634 DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2635 "debugtrap handler not supported",
2638 LLVMContext &Ctx = MF.getFunction()->getContext();
2639 Ctx.diagnose(NoTrap);
2643 llvm_unreachable("unsupported trap handler type!");
2649 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
2650 SelectionDAG &DAG) const {
2651 // FIXME: Use inline constants (src_{shared, private}_base) instead.
2652 if (Subtarget->hasApertureRegs()) {
2653 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
2654 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
2655 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
2656 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
2657 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
2658 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
2660 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
2661 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
2662 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
2664 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
2665 SDValue ApertureReg = SDValue(
2666 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
2667 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
2668 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
2671 MachineFunction &MF = DAG.getMachineFunction();
2672 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2673 unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2674 assert(UserSGPR != AMDGPU::NoRegister);
2676 SDValue QueuePtr = CreateLiveInRegister(
2677 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2679 // Offset into amd_queue_t for group_segment_aperture_base_hi /
2680 // private_segment_aperture_base_hi.
2681 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
2683 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, QueuePtr,
2684 DAG.getConstant(StructOffset, DL, MVT::i64));
2686 // TODO: Use custom target PseudoSourceValue.
2687 // TODO: We should use the value from the IR intrinsic call, but it might not
2688 // be available and how do we get it?
2689 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2690 AMDGPUASI.CONSTANT_ADDRESS));
2692 MachinePointerInfo PtrInfo(V, StructOffset);
2693 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
2694 MinAlign(64, StructOffset),
2695 MachineMemOperand::MODereferenceable |
2696 MachineMemOperand::MOInvariant);
2699 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2700 SelectionDAG &DAG) const {
2702 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2704 SDValue Src = ASC->getOperand(0);
2705 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2707 const AMDGPUTargetMachine &TM =
2708 static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
2710 // flat -> local/private
2711 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2712 unsigned DestAS = ASC->getDestAddressSpace();
2714 if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
2715 DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
2716 unsigned NullVal = TM.getNullPointerValue(DestAS);
2717 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2718 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2719 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2721 return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2722 NonNull, Ptr, SegmentNullPtr);
2726 // local/private -> flat
2727 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
2728 unsigned SrcAS = ASC->getSrcAddressSpace();
2730 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
2731 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
2732 unsigned NullVal = TM.getNullPointerValue(SrcAS);
2733 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
2736 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2738 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
2740 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2742 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2743 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2748 // global <-> flat are no-ops and never emitted.
2750 const MachineFunction &MF = DAG.getMachineFunction();
2751 DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2752 *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2753 DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2755 return DAG.getUNDEF(ASC->getValueType(0));
2758 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
2759 SelectionDAG &DAG) const {
2760 SDValue Idx = Op.getOperand(2);
2761 if (isa<ConstantSDNode>(Idx))
2764 // Avoid stack access for dynamic indexing.
2766 SDValue Vec = Op.getOperand(0);
2767 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
2769 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
2770 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
2772 // Convert vector index to bit-index.
2773 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
2774 DAG.getConstant(16, SL, MVT::i32));
2776 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2778 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
2779 DAG.getConstant(0xffff, SL, MVT::i32),
2782 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
2783 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
2784 DAG.getNOT(SL, BFM, MVT::i32), BCVec);
2786 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
2787 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
2790 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
2791 SelectionDAG &DAG) const {
2794 EVT ResultVT = Op.getValueType();
2795 SDValue Vec = Op.getOperand(0);
2796 SDValue Idx = Op.getOperand(1);
2798 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
2800 // Make sure we we do any optimizations that will make it easier to fold
2801 // source modifiers before obscuring it with bit operations.
2803 // XXX - Why doesn't this get called when vector_shuffle is expanded?
2804 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
2807 if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
2808 SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2810 if (CIdx->getZExtValue() == 1) {
2811 Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
2812 DAG.getConstant(16, SL, MVT::i32));
2814 assert(CIdx->getZExtValue() == 0);
2817 if (ResultVT.bitsLT(MVT::i32))
2818 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2819 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2822 SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
2824 // Convert vector index to bit-index.
2825 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
2827 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
2828 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
2830 SDValue Result = Elt;
2831 if (ResultVT.bitsLT(MVT::i32))
2832 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
2834 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
2838 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2839 // We can fold offsets for anything that doesn't require a GOT relocation.
2840 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
2841 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS) &&
2842 !shouldEmitGOTReloc(GA->getGlobal());
2846 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2847 const SDLoc &DL, unsigned Offset, EVT PtrVT,
2848 unsigned GAFlags = SIInstrInfo::MO_NONE) {
2849 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2850 // lowered to the following code sequence:
2852 // For constant address space:
2853 // s_getpc_b64 s[0:1]
2854 // s_add_u32 s0, s0, $symbol
2855 // s_addc_u32 s1, s1, 0
2857 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2858 // a fixup or relocation is emitted to replace $symbol with a literal
2859 // constant, which is a pc-relative offset from the encoding of the $symbol
2860 // operand to the global variable.
2862 // For global address space:
2863 // s_getpc_b64 s[0:1]
2864 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2865 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2867 // s_getpc_b64 returns the address of the s_add_u32 instruction and then
2868 // fixups or relocations are emitted to replace $symbol@*@lo and
2869 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2870 // which is a 64-bit pc-relative offset from the encoding of the $symbol
2871 // operand to the global variable.
2873 // What we want here is an offset from the value returned by s_getpc
2874 // (which is the address of the s_add_u32 instruction) to the global
2875 // variable, but since the encoding of $symbol starts 4 bytes after the start
2876 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2877 // small. This requires us to add 4 to the global variable offset in order to
2878 // compute the correct address.
2879 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2881 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2882 GAFlags == SIInstrInfo::MO_NONE ?
2883 GAFlags : GAFlags + 1);
2884 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2887 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2889 SelectionDAG &DAG) const {
2890 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2892 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
2893 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS)
2894 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2897 const GlobalValue *GV = GSD->getGlobal();
2898 EVT PtrVT = Op.getValueType();
2900 if (shouldEmitFixup(GV))
2901 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2902 else if (shouldEmitPCReloc(GV))
2903 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2904 SIInstrInfo::MO_REL32);
2906 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2907 SIInstrInfo::MO_GOTPCREL32);
2909 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2910 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
2911 const DataLayout &DataLayout = DAG.getDataLayout();
2912 unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2913 // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2914 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2916 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2917 MachineMemOperand::MODereferenceable |
2918 MachineMemOperand::MOInvariant);
2921 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2922 const SDLoc &DL, SDValue V) const {
2923 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2924 // the destination register.
2926 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2927 // so we will end up with redundant moves to m0.
2929 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2931 // A Null SDValue creates a glue result.
2932 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2934 return SDValue(M0, 0);
2937 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2940 unsigned Offset) const {
2942 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
2943 DAG.getEntryNode(), Offset, false);
2944 // The local size values will have the hi 16-bits as zero.
2945 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2946 DAG.getValueType(VT));
2949 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2951 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2952 "non-hsa intrinsic with hsa target",
2954 DAG.getContext()->diagnose(BadIntrin);
2955 return DAG.getUNDEF(VT);
2958 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
2960 DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2961 "intrinsic not supported on subtarget",
2963 DAG.getContext()->diagnose(BadIntrin);
2964 return DAG.getUNDEF(VT);
2967 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2968 SelectionDAG &DAG) const {
2969 MachineFunction &MF = DAG.getMachineFunction();
2970 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2971 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2973 EVT VT = Op.getValueType();
2975 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2977 // TODO: Should this propagate fast-math-flags?
2979 switch (IntrinsicID) {
2980 case Intrinsic::amdgcn_implicit_buffer_ptr: {
2981 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
2982 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2984 case Intrinsic::amdgcn_dispatch_ptr:
2985 case Intrinsic::amdgcn_queue_ptr: {
2986 if (!Subtarget->isAmdCodeObjectV2(MF)) {
2987 DiagnosticInfoUnsupported BadIntrin(
2988 *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2990 DAG.getContext()->diagnose(BadIntrin);
2991 return DAG.getUNDEF(VT);
2994 auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2995 SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2996 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2997 TRI->getPreloadedValue(MF, Reg), VT);
2999 case Intrinsic::amdgcn_implicitarg_ptr: {
3000 unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
3001 return lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
3003 case Intrinsic::amdgcn_kernarg_segment_ptr: {
3005 = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
3006 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
3008 case Intrinsic::amdgcn_dispatch_id: {
3009 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
3010 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
3012 case Intrinsic::amdgcn_rcp:
3013 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
3014 case Intrinsic::amdgcn_rsq:
3015 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3016 case Intrinsic::amdgcn_rsq_legacy:
3017 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3018 return emitRemovedIntrinsicError(DAG, DL, VT);
3020 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
3021 case Intrinsic::amdgcn_rcp_legacy:
3022 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3023 return emitRemovedIntrinsicError(DAG, DL, VT);
3024 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
3025 case Intrinsic::amdgcn_rsq_clamp: {
3026 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3027 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
3029 Type *Type = VT.getTypeForEVT(*DAG.getContext());
3030 APFloat Max = APFloat::getLargest(Type->getFltSemantics());
3031 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
3033 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
3034 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
3035 DAG.getConstantFP(Max, DL, VT));
3036 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
3037 DAG.getConstantFP(Min, DL, VT));
3039 case Intrinsic::r600_read_ngroups_x:
3040 if (Subtarget->isAmdHsaOS())
3041 return emitNonHSAIntrinsicError(DAG, DL, VT);
3043 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3044 SI::KernelInputOffsets::NGROUPS_X, false);
3045 case Intrinsic::r600_read_ngroups_y:
3046 if (Subtarget->isAmdHsaOS())
3047 return emitNonHSAIntrinsicError(DAG, DL, VT);
3049 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3050 SI::KernelInputOffsets::NGROUPS_Y, false);
3051 case Intrinsic::r600_read_ngroups_z:
3052 if (Subtarget->isAmdHsaOS())
3053 return emitNonHSAIntrinsicError(DAG, DL, VT);
3055 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3056 SI::KernelInputOffsets::NGROUPS_Z, false);
3057 case Intrinsic::r600_read_global_size_x:
3058 if (Subtarget->isAmdHsaOS())
3059 return emitNonHSAIntrinsicError(DAG, DL, VT);
3061 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3062 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
3063 case Intrinsic::r600_read_global_size_y:
3064 if (Subtarget->isAmdHsaOS())
3065 return emitNonHSAIntrinsicError(DAG, DL, VT);
3067 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3068 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
3069 case Intrinsic::r600_read_global_size_z:
3070 if (Subtarget->isAmdHsaOS())
3071 return emitNonHSAIntrinsicError(DAG, DL, VT);
3073 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
3074 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
3075 case Intrinsic::r600_read_local_size_x:
3076 if (Subtarget->isAmdHsaOS())
3077 return emitNonHSAIntrinsicError(DAG, DL, VT);
3079 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3080 SI::KernelInputOffsets::LOCAL_SIZE_X);
3081 case Intrinsic::r600_read_local_size_y:
3082 if (Subtarget->isAmdHsaOS())
3083 return emitNonHSAIntrinsicError(DAG, DL, VT);
3085 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3086 SI::KernelInputOffsets::LOCAL_SIZE_Y);
3087 case Intrinsic::r600_read_local_size_z:
3088 if (Subtarget->isAmdHsaOS())
3089 return emitNonHSAIntrinsicError(DAG, DL, VT);
3091 return lowerImplicitZextParam(DAG, Op, MVT::i16,
3092 SI::KernelInputOffsets::LOCAL_SIZE_Z);
3093 case Intrinsic::amdgcn_workgroup_id_x:
3094 case Intrinsic::r600_read_tgid_x:
3095 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3096 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
3097 case Intrinsic::amdgcn_workgroup_id_y:
3098 case Intrinsic::r600_read_tgid_y:
3099 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3100 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
3101 case Intrinsic::amdgcn_workgroup_id_z:
3102 case Intrinsic::r600_read_tgid_z:
3103 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
3104 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
3105 case Intrinsic::amdgcn_workitem_id_x:
3106 case Intrinsic::r600_read_tidig_x:
3107 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3108 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
3109 case Intrinsic::amdgcn_workitem_id_y:
3110 case Intrinsic::r600_read_tidig_y:
3111 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3112 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
3113 case Intrinsic::amdgcn_workitem_id_z:
3114 case Intrinsic::r600_read_tidig_z:
3115 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
3116 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
3117 case AMDGPUIntrinsic::SI_load_const: {
3123 MachineMemOperand *MMO = MF.getMachineMemOperand(
3124 MachinePointerInfo(),
3125 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3126 MachineMemOperand::MOInvariant,
3127 VT.getStoreSize(), 4);
3128 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
3129 Op->getVTList(), Ops, VT, MMO);
3131 case Intrinsic::amdgcn_fdiv_fast:
3132 return lowerFDIV_FAST(Op, DAG);
3133 case Intrinsic::amdgcn_interp_mov: {
3134 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
3135 SDValue Glue = M0.getValue(1);
3136 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
3137 Op.getOperand(2), Op.getOperand(3), Glue);
3139 case Intrinsic::amdgcn_interp_p1: {
3140 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
3141 SDValue Glue = M0.getValue(1);
3142 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
3143 Op.getOperand(2), Op.getOperand(3), Glue);
3145 case Intrinsic::amdgcn_interp_p2: {
3146 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
3147 SDValue Glue = SDValue(M0.getNode(), 1);
3148 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
3149 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
3152 case Intrinsic::amdgcn_sin:
3153 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
3155 case Intrinsic::amdgcn_cos:
3156 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
3158 case Intrinsic::amdgcn_log_clamp: {
3159 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
3162 DiagnosticInfoUnsupported BadIntrin(
3163 *MF.getFunction(), "intrinsic not supported on subtarget",
3165 DAG.getContext()->diagnose(BadIntrin);
3166 return DAG.getUNDEF(VT);
3168 case Intrinsic::amdgcn_ldexp:
3169 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
3170 Op.getOperand(1), Op.getOperand(2));
3172 case Intrinsic::amdgcn_fract:
3173 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
3175 case Intrinsic::amdgcn_class:
3176 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
3177 Op.getOperand(1), Op.getOperand(2));
3178 case Intrinsic::amdgcn_div_fmas:
3179 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
3180 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
3183 case Intrinsic::amdgcn_div_fixup:
3184 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
3185 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3187 case Intrinsic::amdgcn_trig_preop:
3188 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
3189 Op.getOperand(1), Op.getOperand(2));
3190 case Intrinsic::amdgcn_div_scale: {
3191 // 3rd parameter required to be a constant.
3192 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3194 return DAG.getUNDEF(VT);
3196 // Translate to the operands expected by the machine instruction. The
3197 // first parameter must be the same as the first instruction.
3198 SDValue Numerator = Op.getOperand(1);
3199 SDValue Denominator = Op.getOperand(2);
3201 // Note this order is opposite of the machine instruction's operations,
3202 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
3203 // intrinsic has the numerator as the first operand to match a normal
3204 // division operation.
3206 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
3208 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
3209 Denominator, Numerator);
3211 case Intrinsic::amdgcn_icmp: {
3212 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3214 return DAG.getUNDEF(VT);
3216 int CondCode = CD->getSExtValue();
3217 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3218 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3219 return DAG.getUNDEF(VT);
3221 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3222 ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3223 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3224 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3226 case Intrinsic::amdgcn_fcmp: {
3227 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3229 return DAG.getUNDEF(VT);
3231 int CondCode = CD->getSExtValue();
3232 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3233 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
3234 return DAG.getUNDEF(VT);
3236 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3237 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3238 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
3239 Op.getOperand(2), DAG.getCondCode(CCOpcode));
3241 case Intrinsic::amdgcn_fmed3:
3242 return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
3243 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3244 case Intrinsic::amdgcn_fmul_legacy:
3245 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
3246 Op.getOperand(1), Op.getOperand(2));
3247 case Intrinsic::amdgcn_sffbh:
3248 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
3249 case Intrinsic::amdgcn_sbfe:
3250 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
3251 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3252 case Intrinsic::amdgcn_ubfe:
3253 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
3254 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3255 case Intrinsic::amdgcn_cvt_pkrtz: {
3256 // FIXME: Stop adding cast if v2f16 legal.
3257 EVT VT = Op.getValueType();
3258 SDValue Node = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, DL, MVT::i32,
3259 Op.getOperand(1), Op.getOperand(2));
3260 return DAG.getNode(ISD::BITCAST, DL, VT, Node);
3267 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3268 SelectionDAG &DAG) const {
3269 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3272 case Intrinsic::amdgcn_atomic_inc:
3273 case Intrinsic::amdgcn_atomic_dec: {
3274 MemSDNode *M = cast<MemSDNode>(Op);
3275 unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
3276 AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
3278 M->getOperand(0), // Chain
3279 M->getOperand(2), // Ptr
3280 M->getOperand(3) // Value
3283 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
3284 M->getMemoryVT(), M->getMemOperand());
3286 case Intrinsic::amdgcn_buffer_load:
3287 case Intrinsic::amdgcn_buffer_load_format: {
3289 Op.getOperand(0), // Chain
3290 Op.getOperand(2), // rsrc
3291 Op.getOperand(3), // vindex
3292 Op.getOperand(4), // offset
3293 Op.getOperand(5), // glc
3294 Op.getOperand(6) // slc
3296 MachineFunction &MF = DAG.getMachineFunction();
3297 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3299 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
3300 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
3301 EVT VT = Op.getValueType();
3302 EVT IntVT = VT.changeTypeToInteger();
3304 MachineMemOperand *MMO = MF.getMachineMemOperand(
3305 MachinePointerInfo(MFI->getBufferPSV()),
3306 MachineMemOperand::MOLoad,
3307 VT.getStoreSize(), VT.getStoreSize());
3309 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, MMO);
3312 case Intrinsic::amdgcn_image_sample:
3313 case Intrinsic::amdgcn_image_sample_cl:
3314 case Intrinsic::amdgcn_image_sample_d:
3315 case Intrinsic::amdgcn_image_sample_d_cl:
3316 case Intrinsic::amdgcn_image_sample_l:
3317 case Intrinsic::amdgcn_image_sample_b:
3318 case Intrinsic::amdgcn_image_sample_b_cl:
3319 case Intrinsic::amdgcn_image_sample_lz:
3320 case Intrinsic::amdgcn_image_sample_cd:
3321 case Intrinsic::amdgcn_image_sample_cd_cl:
3323 // Sample with comparison.
3324 case Intrinsic::amdgcn_image_sample_c:
3325 case Intrinsic::amdgcn_image_sample_c_cl:
3326 case Intrinsic::amdgcn_image_sample_c_d:
3327 case Intrinsic::amdgcn_image_sample_c_d_cl:
3328 case Intrinsic::amdgcn_image_sample_c_l:
3329 case Intrinsic::amdgcn_image_sample_c_b:
3330 case Intrinsic::amdgcn_image_sample_c_b_cl:
3331 case Intrinsic::amdgcn_image_sample_c_lz:
3332 case Intrinsic::amdgcn_image_sample_c_cd:
3333 case Intrinsic::amdgcn_image_sample_c_cd_cl:
3335 // Sample with offsets.
3336 case Intrinsic::amdgcn_image_sample_o:
3337 case Intrinsic::amdgcn_image_sample_cl_o:
3338 case Intrinsic::amdgcn_image_sample_d_o:
3339 case Intrinsic::amdgcn_image_sample_d_cl_o:
3340 case Intrinsic::amdgcn_image_sample_l_o:
3341 case Intrinsic::amdgcn_image_sample_b_o:
3342 case Intrinsic::amdgcn_image_sample_b_cl_o:
3343 case Intrinsic::amdgcn_image_sample_lz_o:
3344 case Intrinsic::amdgcn_image_sample_cd_o:
3345 case Intrinsic::amdgcn_image_sample_cd_cl_o:
3347 // Sample with comparison and offsets.
3348 case Intrinsic::amdgcn_image_sample_c_o:
3349 case Intrinsic::amdgcn_image_sample_c_cl_o:
3350 case Intrinsic::amdgcn_image_sample_c_d_o:
3351 case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3352 case Intrinsic::amdgcn_image_sample_c_l_o:
3353 case Intrinsic::amdgcn_image_sample_c_b_o:
3354 case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3355 case Intrinsic::amdgcn_image_sample_c_lz_o:
3356 case Intrinsic::amdgcn_image_sample_c_cd_o:
3357 case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3359 case Intrinsic::amdgcn_image_getlod: {
3360 // Replace dmask with everything disabled with undef.
3361 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
3362 if (!DMask || DMask->isNullValue()) {
3363 SDValue Undef = DAG.getUNDEF(Op.getValueType());
3364 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
3374 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
3375 SelectionDAG &DAG) const {
3376 MachineFunction &MF = DAG.getMachineFunction();
3378 SDValue Chain = Op.getOperand(0);
3379 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3381 switch (IntrinsicID) {
3382 case Intrinsic::amdgcn_exp: {
3383 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3384 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3385 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
3386 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
3388 const SDValue Ops[] = {
3390 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3391 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3392 Op.getOperand(4), // src0
3393 Op.getOperand(5), // src1
3394 Op.getOperand(6), // src2
3395 Op.getOperand(7), // src3
3396 DAG.getTargetConstant(0, DL, MVT::i1), // compr
3397 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3400 unsigned Opc = Done->isNullValue() ?
3401 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3402 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3404 case Intrinsic::amdgcn_exp_compr: {
3405 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
3406 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
3407 SDValue Src0 = Op.getOperand(4);
3408 SDValue Src1 = Op.getOperand(5);
3409 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
3410 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
3412 SDValue Undef = DAG.getUNDEF(MVT::f32);
3413 const SDValue Ops[] = {
3415 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
3416 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
3417 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
3418 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
3421 DAG.getTargetConstant(1, DL, MVT::i1), // compr
3422 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
3425 unsigned Opc = Done->isNullValue() ?
3426 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
3427 return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
3429 case Intrinsic::amdgcn_s_sendmsg:
3430 case Intrinsic::amdgcn_s_sendmsghalt: {
3431 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
3432 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
3433 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
3434 SDValue Glue = Chain.getValue(1);
3435 return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
3436 Op.getOperand(2), Glue);
3438 case Intrinsic::amdgcn_init_exec: {
3439 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
3442 case Intrinsic::amdgcn_init_exec_from_input: {
3443 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
3444 Op.getOperand(2), Op.getOperand(3));
3446 case AMDGPUIntrinsic::SI_tbuffer_store: {
3464 EVT VT = Op.getOperand(3).getValueType();
3466 MachineMemOperand *MMO = MF.getMachineMemOperand(
3467 MachinePointerInfo(),
3468 MachineMemOperand::MOStore,
3469 VT.getStoreSize(), 4);
3470 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
3471 Op->getVTList(), Ops, VT, MMO);
3473 case AMDGPUIntrinsic::AMDGPU_kill: {
3474 SDValue Src = Op.getOperand(2);
3475 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
3476 if (!K->isNegative())
3479 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
3480 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
3483 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
3484 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
3486 case Intrinsic::amdgcn_s_barrier: {
3487 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
3488 const MachineFunction &MF = DAG.getMachineFunction();
3489 const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
3490 unsigned WGSize = ST.getFlatWorkGroupSizes(*MF.getFunction()).second;
3491 if (WGSize <= ST.getWavefrontSize())
3492 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
3493 Op.getOperand(0)), 0);
3502 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
3504 LoadSDNode *Load = cast<LoadSDNode>(Op);
3505 ISD::LoadExtType ExtType = Load->getExtensionType();
3506 EVT MemVT = Load->getMemoryVT();
3508 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
3509 // FIXME: Copied from PPC
3510 // First, load into 32 bits, then truncate to 1 bit.
3512 SDValue Chain = Load->getChain();
3513 SDValue BasePtr = Load->getBasePtr();
3514 MachineMemOperand *MMO = Load->getMemOperand();
3516 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
3518 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
3519 BasePtr, RealMemVT, MMO);
3522 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
3526 return DAG.getMergeValues(Ops, DL);
3529 if (!MemVT.isVector())
3532 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
3533 "Custom lowering for non-i32 vectors hasn't been implemented.");
3535 unsigned AS = Load->getAddressSpace();
3536 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
3537 AS, Load->getAlignment())) {
3539 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
3540 return DAG.getMergeValues(Ops, DL);
3543 MachineFunction &MF = DAG.getMachineFunction();
3544 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3545 // If there is a possibilty that flat instruction access scratch memory
3546 // then we need to use the same legalization rules we use for private.
3547 if (AS == AMDGPUASI.FLAT_ADDRESS)
3548 AS = MFI->hasFlatScratchInit() ?
3549 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3551 unsigned NumElements = MemVT.getVectorNumElements();
3552 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
3553 if (isMemOpUniform(Load))
3555 // Non-uniform loads will be selected to MUBUF instructions, so they
3556 // have the same legalization requirements as global and private
3560 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS) {
3561 if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
3562 isMemOpHasNoClobberedMemOperand(Load))
3564 // Non-uniform loads will be selected to MUBUF instructions, so they
3565 // have the same legalization requirements as global and private
3569 if (AS == AMDGPUASI.CONSTANT_ADDRESS || AS == AMDGPUASI.GLOBAL_ADDRESS ||
3570 AS == AMDGPUASI.FLAT_ADDRESS) {
3571 if (NumElements > 4)
3572 return SplitVectorLoad(Op, DAG);
3573 // v4 loads are supported for private and global memory.
3576 if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3577 // Depending on the setting of the private_element_size field in the
3578 // resource descriptor, we can only make private accesses up to a certain
3580 switch (Subtarget->getMaxPrivateElementSize()) {
3582 return scalarizeVectorLoad(Load, DAG);
3584 if (NumElements > 2)
3585 return SplitVectorLoad(Op, DAG);
3588 // Same as global/flat
3589 if (NumElements > 4)
3590 return SplitVectorLoad(Op, DAG);
3593 llvm_unreachable("unsupported private_element_size");
3595 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
3596 if (NumElements > 2)
3597 return SplitVectorLoad(Op, DAG);
3599 if (NumElements == 2)
3602 // If properly aligned, if we split we might be able to use ds_read_b64.
3603 return SplitVectorLoad(Op, DAG);
3608 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3609 if (Op.getValueType() != MVT::i64)
3613 SDValue Cond = Op.getOperand(0);
3615 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
3616 SDValue One = DAG.getConstant(1, DL, MVT::i32);
3618 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
3619 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
3621 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
3622 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
3624 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
3626 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
3627 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
3629 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
3631 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
3632 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
3635 // Catch division cases where we can use shortcuts with rcp and rsq
3637 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
3638 SelectionDAG &DAG) const {
3640 SDValue LHS = Op.getOperand(0);
3641 SDValue RHS = Op.getOperand(1);
3642 EVT VT = Op.getValueType();
3643 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
3645 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
3648 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
3649 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
3650 if (CLHS->isExactlyValue(1.0)) {
3651 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
3652 // the CI documentation has a worst case error of 1 ulp.
3653 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
3654 // use it as long as we aren't trying to use denormals.
3656 // v_rcp_f16 and v_rsq_f16 DO support denormals.
3658 // 1.0 / sqrt(x) -> rsq(x)
3660 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
3661 // error seems really high at 2^29 ULP.
3662 if (RHS.getOpcode() == ISD::FSQRT)
3663 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
3665 // 1.0 / x -> rcp(x)
3666 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3669 // Same as for 1.0, but expand the sign out of the constant.
3670 if (CLHS->isExactlyValue(-1.0)) {
3671 // -1.0 / x -> rcp (fneg x)
3672 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3673 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
3678 const SDNodeFlags Flags = Op->getFlags();
3680 if (Unsafe || Flags.hasAllowReciprocal()) {
3681 // Turn into multiply by the reciprocal.
3682 // x / y -> x * (1.0 / y)
3683 SDNodeFlags NewFlags;
3684 NewFlags.setUnsafeAlgebra(true);
3685 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
3686 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, NewFlags);
3692 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3693 EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
3694 if (GlueChain->getNumValues() <= 1) {
3695 return DAG.getNode(Opcode, SL, VT, A, B);
3698 assert(GlueChain->getNumValues() == 3);
3700 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3702 default: llvm_unreachable("no chain equivalent for opcode");
3704 Opcode = AMDGPUISD::FMUL_W_CHAIN;
3708 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
3709 GlueChain.getValue(2));
3712 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
3713 EVT VT, SDValue A, SDValue B, SDValue C,
3714 SDValue GlueChain) {
3715 if (GlueChain->getNumValues() <= 1) {
3716 return DAG.getNode(Opcode, SL, VT, A, B, C);
3719 assert(GlueChain->getNumValues() == 3);
3721 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
3723 default: llvm_unreachable("no chain equivalent for opcode");
3725 Opcode = AMDGPUISD::FMA_W_CHAIN;
3729 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
3730 GlueChain.getValue(2));
3733 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
3734 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3738 SDValue Src0 = Op.getOperand(0);
3739 SDValue Src1 = Op.getOperand(1);
3741 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3742 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3744 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
3745 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
3747 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
3748 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
3750 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
3753 // Faster 2.5 ULP division that does not support denormals.
3754 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
3756 SDValue LHS = Op.getOperand(1);
3757 SDValue RHS = Op.getOperand(2);
3759 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
3761 const APFloat K0Val(BitsToFloat(0x6f800000));
3762 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
3764 const APFloat K1Val(BitsToFloat(0x2f800000));
3765 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
3767 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3770 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
3772 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
3774 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
3776 // TODO: Should this propagate fast-math-flags?
3777 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
3779 // rcp does not support denormals.
3780 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
3782 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
3784 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
3787 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
3788 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
3792 SDValue LHS = Op.getOperand(0);
3793 SDValue RHS = Op.getOperand(1);
3795 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3797 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3799 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3801 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3804 // Denominator is scaled to not be denormal, so using rcp is ok.
3805 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3807 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3810 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3811 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3812 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3814 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3816 if (!Subtarget->hasFP32Denormals()) {
3817 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3818 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3820 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3822 EnableDenormValue, BitField);
3825 EnableDenorm.getValue(0),
3826 EnableDenorm.getValue(1)
3829 NegDivScale0 = DAG.getMergeValues(Ops, SL);
3832 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3833 ApproxRcp, One, NegDivScale0);
3835 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3838 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3841 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3842 NumeratorScaled, Mul);
3844 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3846 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3847 NumeratorScaled, Fma3);
3849 if (!Subtarget->hasFP32Denormals()) {
3850 const SDValue DisableDenormValue =
3851 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3852 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3858 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3859 DisableDenorm, DAG.getRoot());
3860 DAG.setRoot(OutputChain);
3863 SDValue Scale = NumeratorScaled.getValue(1);
3864 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3865 Fma4, Fma1, Fma3, Scale);
3867 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3870 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3871 if (DAG.getTarget().Options.UnsafeFPMath)
3872 return lowerFastUnsafeFDIV(Op, DAG);
3875 SDValue X = Op.getOperand(0);
3876 SDValue Y = Op.getOperand(1);
3878 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3880 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3882 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3884 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3886 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3888 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3890 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3892 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3894 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3896 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3897 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3899 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3900 NegDivScale0, Mul, DivScale1);
3904 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3905 // Workaround a hardware bug on SI where the condition output from div_scale
3908 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3910 // Figure out if the scale to use for div_fmas.
3911 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3912 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3913 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3914 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3916 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3917 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3920 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3922 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3924 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3925 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3926 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3928 Scale = DivScale1.getValue(1);
3931 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3932 Fma4, Fma3, Mul, Scale);
3934 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3937 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3938 EVT VT = Op.getValueType();
3941 return LowerFDIV32(Op, DAG);
3944 return LowerFDIV64(Op, DAG);
3947 return LowerFDIV16(Op, DAG);
3949 llvm_unreachable("Unexpected type for fdiv");
3952 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3954 StoreSDNode *Store = cast<StoreSDNode>(Op);
3955 EVT VT = Store->getMemoryVT();
3957 if (VT == MVT::i1) {
3958 return DAG.getTruncStore(Store->getChain(), DL,
3959 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3960 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3963 assert(VT.isVector() &&
3964 Store->getValue().getValueType().getScalarType() == MVT::i32);
3966 unsigned AS = Store->getAddressSpace();
3967 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3968 AS, Store->getAlignment())) {
3969 return expandUnalignedStore(Store, DAG);
3972 MachineFunction &MF = DAG.getMachineFunction();
3973 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3974 // If there is a possibilty that flat instruction access scratch memory
3975 // then we need to use the same legalization rules we use for private.
3976 if (AS == AMDGPUASI.FLAT_ADDRESS)
3977 AS = MFI->hasFlatScratchInit() ?
3978 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
3980 unsigned NumElements = VT.getVectorNumElements();
3981 if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
3982 AS == AMDGPUASI.FLAT_ADDRESS) {
3983 if (NumElements > 4)
3984 return SplitVectorStore(Op, DAG);
3986 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
3987 switch (Subtarget->getMaxPrivateElementSize()) {
3989 return scalarizeVectorStore(Store, DAG);
3991 if (NumElements > 2)
3992 return SplitVectorStore(Op, DAG);
3995 if (NumElements > 4)
3996 return SplitVectorStore(Op, DAG);
3999 llvm_unreachable("unsupported private_element_size");
4001 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
4002 if (NumElements > 2)
4003 return SplitVectorStore(Op, DAG);
4005 if (NumElements == 2)
4008 // If properly aligned, if we split we might be able to use ds_write_b64.
4009 return SplitVectorStore(Op, DAG);
4011 llvm_unreachable("unhandled address space");
4015 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
4017 EVT VT = Op.getValueType();
4018 SDValue Arg = Op.getOperand(0);
4019 // TODO: Should this propagate fast-math-flags?
4020 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
4021 DAG.getNode(ISD::FMUL, DL, VT, Arg,
4022 DAG.getConstantFP(0.5/M_PI, DL,
4025 switch (Op.getOpcode()) {
4027 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
4029 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
4031 llvm_unreachable("Wrong trig opcode");
4035 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
4036 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
4037 assert(AtomicNode->isCompareAndSwap());
4038 unsigned AS = AtomicNode->getAddressSpace();
4040 // No custom lowering required for local address space
4041 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
4044 // Non-local address space requires custom lowering for atomic compare
4045 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
4047 SDValue ChainIn = Op.getOperand(0);
4048 SDValue Addr = Op.getOperand(1);
4049 SDValue Old = Op.getOperand(2);
4050 SDValue New = Op.getOperand(3);
4051 EVT VT = Op.getValueType();
4052 MVT SimpleVT = VT.getSimpleVT();
4053 MVT VecType = MVT::getVectorVT(SimpleVT, 2);
4055 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
4056 SDValue Ops[] = { ChainIn, Addr, NewOld };
4058 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
4059 Ops, VT, AtomicNode->getMemOperand());
4062 //===----------------------------------------------------------------------===//
4063 // Custom DAG optimizations
4064 //===----------------------------------------------------------------------===//
4066 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
4067 DAGCombinerInfo &DCI) const {
4068 EVT VT = N->getValueType(0);
4069 EVT ScalarVT = VT.getScalarType();
4070 if (ScalarVT != MVT::f32)
4073 SelectionDAG &DAG = DCI.DAG;
4076 SDValue Src = N->getOperand(0);
4077 EVT SrcVT = Src.getValueType();
4079 // TODO: We could try to match extracting the higher bytes, which would be
4080 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
4081 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
4082 // about in practice.
4083 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
4084 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
4085 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
4086 DCI.AddToWorklist(Cvt.getNode());
4094 /// \brief Return true if the given offset Size in bytes can be folded into
4095 /// the immediate offsets of a memory instruction for the given address space.
4096 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
4097 const SISubtarget &STI) {
4098 auto AMDGPUASI = STI.getAMDGPUAS();
4099 if (AS == AMDGPUASI.GLOBAL_ADDRESS) {
4100 // MUBUF instructions a 12-bit offset in bytes.
4101 return isUInt<12>(OffsetSize);
4103 if (AS == AMDGPUASI.CONSTANT_ADDRESS) {
4104 // SMRD instructions have an 8-bit offset in dwords on SI and
4105 // a 20-bit offset in bytes on VI.
4106 if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4107 return isUInt<20>(OffsetSize);
4109 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
4111 if (AS == AMDGPUASI.LOCAL_ADDRESS ||
4112 AS == AMDGPUASI.REGION_ADDRESS) {
4113 // The single offset versions have a 16-bit offset in bytes.
4114 return isUInt<16>(OffsetSize);
4116 // Indirect register addressing does not use any offsets.
4120 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
4122 // This is a variant of
4123 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
4125 // The normal DAG combiner will do this, but only if the add has one use since
4126 // that would increase the number of instructions.
4128 // This prevents us from seeing a constant offset that can be folded into a
4129 // memory instruction's addressing mode. If we know the resulting add offset of
4130 // a pointer can be folded into an addressing offset, we can replace the pointer
4131 // operand with the add of new constant offset. This eliminates one of the uses,
4132 // and may allow the remaining use to also be simplified.
4134 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
4136 DAGCombinerInfo &DCI) const {
4137 SDValue N0 = N->getOperand(0);
4138 SDValue N1 = N->getOperand(1);
4140 if (N0.getOpcode() != ISD::ADD)
4143 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
4147 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4151 // If the resulting offset is too large, we can't fold it into the addressing
4153 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
4154 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
4157 SelectionDAG &DAG = DCI.DAG;
4159 EVT VT = N->getValueType(0);
4161 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
4162 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
4164 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
4167 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
4168 DAGCombinerInfo &DCI) const {
4169 SDValue Ptr = N->getBasePtr();
4170 SelectionDAG &DAG = DCI.DAG;
4173 // TODO: We could also do this for multiplies.
4174 unsigned AS = N->getAddressSpace();
4175 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUASI.PRIVATE_ADDRESS) {
4176 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
4178 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
4180 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
4181 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
4188 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
4189 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
4190 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
4191 (Opc == ISD::XOR && Val == 0);
4194 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
4195 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
4196 // integer combine opportunities since most 64-bit operations are decomposed
4197 // this way. TODO: We won't want this for SALU especially if it is an inline
4199 SDValue SITargetLowering::splitBinaryBitConstantOp(
4200 DAGCombinerInfo &DCI,
4202 unsigned Opc, SDValue LHS,
4203 const ConstantSDNode *CRHS) const {
4204 uint64_t Val = CRHS->getZExtValue();
4205 uint32_t ValLo = Lo_32(Val);
4206 uint32_t ValHi = Hi_32(Val);
4207 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4209 if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
4210 bitOpWithConstantIsReducible(Opc, ValHi)) ||
4211 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
4212 // If we need to materialize a 64-bit immediate, it will be split up later
4213 // anyway. Avoid creating the harder to understand 64-bit immediate
4215 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
4221 SDValue SITargetLowering::performAndCombine(SDNode *N,
4222 DAGCombinerInfo &DCI) const {
4223 if (DCI.isBeforeLegalize())
4226 SelectionDAG &DAG = DCI.DAG;
4227 EVT VT = N->getValueType(0);
4228 SDValue LHS = N->getOperand(0);
4229 SDValue RHS = N->getOperand(1);
4232 if (VT == MVT::i64) {
4233 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4236 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
4241 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
4242 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
4243 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
4244 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
4245 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
4247 SDValue X = LHS.getOperand(0);
4248 SDValue Y = RHS.getOperand(0);
4249 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
4252 if (LCC == ISD::SETO) {
4253 if (X != LHS.getOperand(1))
4256 if (RCC == ISD::SETUNE) {
4257 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
4258 if (!C1 || !C1->isInfinity() || C1->isNegative())
4261 const uint32_t Mask = SIInstrFlags::N_NORMAL |
4262 SIInstrFlags::N_SUBNORMAL |
4263 SIInstrFlags::N_ZERO |
4264 SIInstrFlags::P_ZERO |
4265 SIInstrFlags::P_SUBNORMAL |
4266 SIInstrFlags::P_NORMAL;
4268 static_assert(((~(SIInstrFlags::S_NAN |
4269 SIInstrFlags::Q_NAN |
4270 SIInstrFlags::N_INFINITY |
4271 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
4275 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4276 X, DAG.getConstant(Mask, DL, MVT::i32));
4284 SDValue SITargetLowering::performOrCombine(SDNode *N,
4285 DAGCombinerInfo &DCI) const {
4286 SelectionDAG &DAG = DCI.DAG;
4287 SDValue LHS = N->getOperand(0);
4288 SDValue RHS = N->getOperand(1);
4290 EVT VT = N->getValueType(0);
4291 if (VT == MVT::i1) {
4292 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
4293 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
4294 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
4295 SDValue Src = LHS.getOperand(0);
4296 if (Src != RHS.getOperand(0))
4299 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
4300 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
4304 // Only 10 bits are used.
4305 static const uint32_t MaxMask = 0x3ff;
4307 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
4309 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
4310 Src, DAG.getConstant(NewMask, DL, MVT::i32));
4319 // TODO: This could be a generic combine with a predicate for extracting the
4320 // high half of an integer being free.
4322 // (or i64:x, (zero_extend i32:y)) ->
4323 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
4324 if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
4325 RHS.getOpcode() != ISD::ZERO_EXTEND)
4326 std::swap(LHS, RHS);
4328 if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
4329 SDValue ExtSrc = RHS.getOperand(0);
4330 EVT SrcVT = ExtSrc.getValueType();
4331 if (SrcVT == MVT::i32) {
4333 SDValue LowLHS, HiBits;
4334 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
4335 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
4337 DCI.AddToWorklist(LowOr.getNode());
4338 DCI.AddToWorklist(HiBits.getNode());
4340 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
4342 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
4346 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
4349 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
4356 SDValue SITargetLowering::performXorCombine(SDNode *N,
4357 DAGCombinerInfo &DCI) const {
4358 EVT VT = N->getValueType(0);
4362 SDValue LHS = N->getOperand(0);
4363 SDValue RHS = N->getOperand(1);
4365 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
4368 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
4375 // Instructions that will be lowered with a final instruction that zeros the
4376 // high result bits.
4377 // XXX - probably only need to list legal operations.
4378 static bool fp16SrcZerosHighBits(unsigned Opc) {
4387 case ISD::FCANONICALIZE:
4389 case ISD::UINT_TO_FP:
4390 case ISD::SINT_TO_FP:
4392 // Fabs is lowered to a bit operation, but it's an and which will clear the
4393 // high bits anyway.
4407 case ISD::FNEARBYINT:
4412 case AMDGPUISD::FRACT:
4413 case AMDGPUISD::CLAMP:
4414 case AMDGPUISD::COS_HW:
4415 case AMDGPUISD::SIN_HW:
4416 case AMDGPUISD::FMIN3:
4417 case AMDGPUISD::FMAX3:
4418 case AMDGPUISD::FMED3:
4419 case AMDGPUISD::FMAD_FTZ:
4420 case AMDGPUISD::RCP:
4421 case AMDGPUISD::RSQ:
4422 case AMDGPUISD::LDEXP:
4425 // fcopysign, select and others may be lowered to 32-bit bit operations
4426 // which don't zero the high bits.
4431 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
4432 DAGCombinerInfo &DCI) const {
4433 if (!Subtarget->has16BitInsts() ||
4434 DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4437 EVT VT = N->getValueType(0);
4441 SDValue Src = N->getOperand(0);
4442 if (Src.getValueType() != MVT::i16)
4445 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
4446 // FIXME: It is not universally true that the high bits are zeroed on gfx9.
4447 if (Src.getOpcode() == ISD::BITCAST) {
4448 SDValue BCSrc = Src.getOperand(0);
4449 if (BCSrc.getValueType() == MVT::f16 &&
4450 fp16SrcZerosHighBits(BCSrc.getOpcode()))
4451 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
4457 SDValue SITargetLowering::performClassCombine(SDNode *N,
4458 DAGCombinerInfo &DCI) const {
4459 SelectionDAG &DAG = DCI.DAG;
4460 SDValue Mask = N->getOperand(1);
4462 // fp_class x, 0 -> false
4463 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
4464 if (CMask->isNullValue())
4465 return DAG.getConstant(0, SDLoc(N), MVT::i1);
4468 if (N->getOperand(0).isUndef())
4469 return DAG.getUNDEF(MVT::i1);
4474 // Constant fold canonicalize.
4475 SDValue SITargetLowering::performFCanonicalizeCombine(
4477 DAGCombinerInfo &DCI) const {
4478 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
4482 SelectionDAG &DAG = DCI.DAG;
4483 const APFloat &C = CFP->getValueAPF();
4485 // Flush denormals to 0 if not enabled.
4486 if (C.isDenormal()) {
4487 EVT VT = N->getValueType(0);
4488 EVT SVT = VT.getScalarType();
4489 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
4490 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4492 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
4493 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4495 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
4496 return DAG.getConstantFP(0.0, SDLoc(N), VT);
4500 EVT VT = N->getValueType(0);
4501 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
4502 if (C.isSignaling()) {
4503 // Quiet a signaling NaN.
4504 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4507 // Make sure it is the canonical NaN bitpattern.
4509 // TODO: Can we use -1 as the canonical NaN value since it's an inline
4511 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
4512 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
4515 return N->getOperand(0);
4518 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
4521 return AMDGPUISD::FMAX3;
4523 return AMDGPUISD::SMAX3;
4525 return AMDGPUISD::UMAX3;
4527 return AMDGPUISD::FMIN3;
4529 return AMDGPUISD::SMIN3;
4531 return AMDGPUISD::UMIN3;
4533 llvm_unreachable("Not a min/max opcode");
4537 SDValue SITargetLowering::performIntMed3ImmCombine(
4538 SelectionDAG &DAG, const SDLoc &SL,
4539 SDValue Op0, SDValue Op1, bool Signed) const {
4540 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
4544 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
4549 if (K0->getAPIntValue().sge(K1->getAPIntValue()))
4552 if (K0->getAPIntValue().uge(K1->getAPIntValue()))
4556 EVT VT = K0->getValueType(0);
4557 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
4558 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
4559 return DAG.getNode(Med3Opc, SL, VT,
4560 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
4563 // If there isn't a 16-bit med3 operation, convert to 32-bit.
4565 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4567 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
4568 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
4569 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
4571 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
4572 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
4575 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
4576 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
4579 return DAG.isKnownNeverNaN(Op);
4582 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
4585 SDValue Op1) const {
4586 ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
4590 ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
4594 // Ordered >= (although NaN inputs should have folded away by now).
4595 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
4596 if (Cmp == APFloat::cmpGreaterThan)
4599 // TODO: Check IEEE bit enabled?
4600 EVT VT = K0->getValueType(0);
4601 if (Subtarget->enableDX10Clamp()) {
4602 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
4603 // hardware fmed3 behavior converting to a min.
4604 // FIXME: Should this be allowing -0.0?
4605 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
4606 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
4609 // med3 for f16 is only available on gfx9+.
4610 if (VT == MVT::f64 || (VT == MVT::f16 && !Subtarget->hasMed3_16()))
4613 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
4614 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
4615 // give the other result, which is different from med3 with a NaN input.
4616 SDValue Var = Op0.getOperand(0);
4617 if (!isKnownNeverSNan(DAG, Var))
4620 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
4621 Var, SDValue(K0, 0), SDValue(K1, 0));
4624 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
4625 DAGCombinerInfo &DCI) const {
4626 SelectionDAG &DAG = DCI.DAG;
4628 EVT VT = N->getValueType(0);
4629 unsigned Opc = N->getOpcode();
4630 SDValue Op0 = N->getOperand(0);
4631 SDValue Op1 = N->getOperand(1);
4633 // Only do this if the inner op has one use since this will just increases
4634 // register pressure for no benefit.
4637 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
4639 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
4640 // max(max(a, b), c) -> max3(a, b, c)
4641 // min(min(a, b), c) -> min3(a, b, c)
4642 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
4644 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4653 // max(a, max(b, c)) -> max3(a, b, c)
4654 // min(a, min(b, c)) -> min3(a, b, c)
4655 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
4657 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
4666 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
4667 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
4668 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
4672 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
4673 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
4677 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
4678 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
4679 (Opc == AMDGPUISD::FMIN_LEGACY &&
4680 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
4681 (VT == MVT::f32 || VT == MVT::f64 ||
4682 (VT == MVT::f16 && Subtarget->has16BitInsts())) &&
4684 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
4691 static bool isClampZeroToOne(SDValue A, SDValue B) {
4692 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
4693 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
4694 // FIXME: Should this be allowing -0.0?
4695 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
4696 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
4703 // FIXME: Should only worry about snans for version with chain.
4704 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
4705 DAGCombinerInfo &DCI) const {
4706 EVT VT = N->getValueType(0);
4707 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
4708 // NaNs. With a NaN input, the order of the operands may change the result.
4710 SelectionDAG &DAG = DCI.DAG;
4713 SDValue Src0 = N->getOperand(0);
4714 SDValue Src1 = N->getOperand(1);
4715 SDValue Src2 = N->getOperand(2);
4717 if (isClampZeroToOne(Src0, Src1)) {
4718 // const_a, const_b, x -> clamp is safe in all cases including signaling
4720 // FIXME: Should this be allowing -0.0?
4721 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
4724 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
4725 // handling no dx10-clamp?
4726 if (Subtarget->enableDX10Clamp()) {
4727 // If NaNs is clamped to 0, we are free to reorder the inputs.
4729 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4730 std::swap(Src0, Src1);
4732 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
4733 std::swap(Src1, Src2);
4735 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
4736 std::swap(Src0, Src1);
4738 if (isClampZeroToOne(Src1, Src2))
4739 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
4745 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
4746 DAGCombinerInfo &DCI) const {
4747 SDValue Src0 = N->getOperand(0);
4748 SDValue Src1 = N->getOperand(1);
4749 if (Src0.isUndef() && Src1.isUndef())
4750 return DCI.DAG.getUNDEF(N->getValueType(0));
4754 SDValue SITargetLowering::performExtractVectorEltCombine(
4755 SDNode *N, DAGCombinerInfo &DCI) const {
4756 SDValue Vec = N->getOperand(0);
4758 SelectionDAG &DAG= DCI.DAG;
4759 if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
4761 EVT EltVT = N->getValueType(0);
4762 SDValue Idx = N->getOperand(1);
4763 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4764 Vec.getOperand(0), Idx);
4765 return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
4772 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
4774 const SDNode *N1) const {
4775 EVT VT = N0->getValueType(0);
4777 // Only do this if we are not trying to support denormals. v_mad_f32 does not
4778 // support denormals ever.
4779 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
4780 (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
4783 const TargetOptions &Options = DAG.getTarget().Options;
4784 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
4785 (N0->getFlags().hasUnsafeAlgebra() &&
4786 N1->getFlags().hasUnsafeAlgebra())) &&
4787 isFMAFasterThanFMulAndFAdd(VT)) {
4794 SDValue SITargetLowering::performFAddCombine(SDNode *N,
4795 DAGCombinerInfo &DCI) const {
4796 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4799 SelectionDAG &DAG = DCI.DAG;
4800 EVT VT = N->getValueType(0);
4803 SDValue LHS = N->getOperand(0);
4804 SDValue RHS = N->getOperand(1);
4806 // These should really be instruction patterns, but writing patterns with
4807 // source modiifiers is a pain.
4809 // fadd (fadd (a, a), b) -> mad 2.0, a, b
4810 if (LHS.getOpcode() == ISD::FADD) {
4811 SDValue A = LHS.getOperand(0);
4812 if (A == LHS.getOperand(1)) {
4813 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4815 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4816 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
4821 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
4822 if (RHS.getOpcode() == ISD::FADD) {
4823 SDValue A = RHS.getOperand(0);
4824 if (A == RHS.getOperand(1)) {
4825 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4827 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4828 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
4836 SDValue SITargetLowering::performFSubCombine(SDNode *N,
4837 DAGCombinerInfo &DCI) const {
4838 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
4841 SelectionDAG &DAG = DCI.DAG;
4843 EVT VT = N->getValueType(0);
4844 assert(!VT.isVector());
4846 // Try to get the fneg to fold into the source modifier. This undoes generic
4847 // DAG combines and folds them into the mad.
4849 // Only do this if we are not trying to support denormals. v_mad_f32 does
4850 // not support denormals ever.
4851 SDValue LHS = N->getOperand(0);
4852 SDValue RHS = N->getOperand(1);
4853 if (LHS.getOpcode() == ISD::FADD) {
4854 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
4855 SDValue A = LHS.getOperand(0);
4856 if (A == LHS.getOperand(1)) {
4857 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
4859 const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
4860 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
4862 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
4867 if (RHS.getOpcode() == ISD::FADD) {
4868 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
4870 SDValue A = RHS.getOperand(0);
4871 if (A == RHS.getOperand(1)) {
4872 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
4874 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
4875 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
4883 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
4884 DAGCombinerInfo &DCI) const {
4885 SelectionDAG &DAG = DCI.DAG;
4888 SDValue LHS = N->getOperand(0);
4889 SDValue RHS = N->getOperand(1);
4890 EVT VT = LHS.getValueType();
4892 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
4896 // Match isinf pattern
4897 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
4898 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
4899 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
4900 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
4904 const APFloat &APF = CRHS->getValueAPF();
4905 if (APF.isInfinity() && !APF.isNegative()) {
4906 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
4907 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
4908 DAG.getConstant(Mask, SL, MVT::i32));
4915 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
4916 DAGCombinerInfo &DCI) const {
4917 SelectionDAG &DAG = DCI.DAG;
4919 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
4921 SDValue Src = N->getOperand(0);
4922 SDValue Srl = N->getOperand(0);
4923 if (Srl.getOpcode() == ISD::ZERO_EXTEND)
4924 Srl = Srl.getOperand(0);
4926 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
4927 if (Srl.getOpcode() == ISD::SRL) {
4928 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
4929 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
4930 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
4932 if (const ConstantSDNode *C =
4933 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
4934 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
4937 unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
4938 if (SrcOffset < 32 && SrcOffset % 8 == 0) {
4939 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
4945 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
4948 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
4949 !DCI.isBeforeLegalizeOps());
4950 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4951 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
4952 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
4953 DCI.CommitTargetLoweringOpt(TLO);
4959 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
4960 DAGCombinerInfo &DCI) const {
4961 switch (N->getOpcode()) {
4963 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4965 return performFAddCombine(N, DCI);
4967 return performFSubCombine(N, DCI);
4969 return performSetCCCombine(N, DCI);
4976 case AMDGPUISD::FMIN_LEGACY:
4977 case AMDGPUISD::FMAX_LEGACY: {
4978 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
4979 getTargetMachine().getOptLevel() > CodeGenOpt::None)
4980 return performMinMaxCombine(N, DCI);
4985 case ISD::ATOMIC_LOAD:
4986 case ISD::ATOMIC_STORE:
4987 case ISD::ATOMIC_CMP_SWAP:
4988 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4989 case ISD::ATOMIC_SWAP:
4990 case ISD::ATOMIC_LOAD_ADD:
4991 case ISD::ATOMIC_LOAD_SUB:
4992 case ISD::ATOMIC_LOAD_AND:
4993 case ISD::ATOMIC_LOAD_OR:
4994 case ISD::ATOMIC_LOAD_XOR:
4995 case ISD::ATOMIC_LOAD_NAND:
4996 case ISD::ATOMIC_LOAD_MIN:
4997 case ISD::ATOMIC_LOAD_MAX:
4998 case ISD::ATOMIC_LOAD_UMIN:
4999 case ISD::ATOMIC_LOAD_UMAX:
5000 case AMDGPUISD::ATOMIC_INC:
5001 case AMDGPUISD::ATOMIC_DEC: // TODO: Target mem intrinsics.
5002 if (DCI.isBeforeLegalize())
5004 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
5006 return performAndCombine(N, DCI);
5008 return performOrCombine(N, DCI);
5010 return performXorCombine(N, DCI);
5011 case ISD::ZERO_EXTEND:
5012 return performZeroExtendCombine(N, DCI);
5013 case AMDGPUISD::FP_CLASS:
5014 return performClassCombine(N, DCI);
5015 case ISD::FCANONICALIZE:
5016 return performFCanonicalizeCombine(N, DCI);
5017 case AMDGPUISD::FRACT:
5018 case AMDGPUISD::RCP:
5019 case AMDGPUISD::RSQ:
5020 case AMDGPUISD::RCP_LEGACY:
5021 case AMDGPUISD::RSQ_LEGACY:
5022 case AMDGPUISD::RSQ_CLAMP:
5023 case AMDGPUISD::LDEXP: {
5024 SDValue Src = N->getOperand(0);
5029 case ISD::SINT_TO_FP:
5030 case ISD::UINT_TO_FP:
5031 return performUCharToFloatCombine(N, DCI);
5032 case AMDGPUISD::CVT_F32_UBYTE0:
5033 case AMDGPUISD::CVT_F32_UBYTE1:
5034 case AMDGPUISD::CVT_F32_UBYTE2:
5035 case AMDGPUISD::CVT_F32_UBYTE3:
5036 return performCvtF32UByteNCombine(N, DCI);
5037 case AMDGPUISD::FMED3:
5038 return performFMed3Combine(N, DCI);
5039 case AMDGPUISD::CVT_PKRTZ_F16_F32:
5040 return performCvtPkRTZCombine(N, DCI);
5041 case ISD::SCALAR_TO_VECTOR: {
5042 SelectionDAG &DAG = DCI.DAG;
5043 EVT VT = N->getValueType(0);
5045 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
5046 if (VT == MVT::v2i16 || VT == MVT::v2f16) {
5048 SDValue Src = N->getOperand(0);
5049 EVT EltVT = Src.getValueType();
5050 if (EltVT == MVT::f16)
5051 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
5053 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
5054 return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
5059 case ISD::EXTRACT_VECTOR_ELT:
5060 return performExtractVectorEltCombine(N, DCI);
5062 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
5065 /// \brief Helper function for adjustWritemask
5066 static unsigned SubIdx2Lane(unsigned Idx) {
5069 case AMDGPU::sub0: return 0;
5070 case AMDGPU::sub1: return 1;
5071 case AMDGPU::sub2: return 2;
5072 case AMDGPU::sub3: return 3;
5076 /// \brief Adjust the writemask of MIMG instructions
5077 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
5078 SelectionDAG &DAG) const {
5079 SDNode *Users[4] = { };
5081 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
5082 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
5083 unsigned NewDmask = 0;
5085 // Try to figure out the used register components
5086 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
5089 // Don't look at users of the chain.
5090 if (I.getUse().getResNo() != 0)
5093 // Abort if we can't understand the usage
5094 if (!I->isMachineOpcode() ||
5095 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
5098 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
5099 // Note that subregs are packed, i.e. Lane==0 is the first bit set
5100 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
5102 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
5104 // Set which texture component corresponds to the lane.
5106 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
5108 Comp = countTrailingZeros(Dmask);
5109 Dmask &= ~(1 << Comp);
5112 // Abort if we have more than one user per component
5117 NewDmask |= 1 << Comp;
5120 // Abort if there's no change
5121 if (NewDmask == OldDmask)
5124 // Adjust the writemask in the node
5125 std::vector<SDValue> Ops;
5126 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
5127 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
5128 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
5129 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
5131 // If we only got one lane, replace it with a copy
5132 // (if NewDmask has only one bit set...)
5133 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
5134 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
5136 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
5137 SDLoc(), Users[Lane]->getValueType(0),
5138 SDValue(Node, 0), RC);
5139 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
5143 // Update the users of the node with the new indices
5144 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
5145 SDNode *User = Users[i];
5149 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
5150 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
5154 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
5155 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
5156 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
5161 static bool isFrameIndexOp(SDValue Op) {
5162 if (Op.getOpcode() == ISD::AssertZext)
5163 Op = Op.getOperand(0);
5165 return isa<FrameIndexSDNode>(Op);
5168 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
5169 /// with frame index operands.
5170 /// LLVM assumes that inputs are to these instructions are registers.
5171 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
5172 SelectionDAG &DAG) const {
5173 if (Node->getOpcode() == ISD::CopyToReg) {
5174 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
5175 SDValue SrcVal = Node->getOperand(2);
5177 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
5178 // to try understanding copies to physical registers.
5179 if (SrcVal.getValueType() == MVT::i1 &&
5180 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
5182 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
5183 SDValue VReg = DAG.getRegister(
5184 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
5186 SDNode *Glued = Node->getGluedNode();
5188 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
5189 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
5191 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
5192 VReg, ToVReg.getValue(1));
5193 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
5194 DAG.RemoveDeadNode(Node);
5195 return ToResultReg.getNode();
5199 SmallVector<SDValue, 8> Ops;
5200 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
5201 if (!isFrameIndexOp(Node->getOperand(i))) {
5202 Ops.push_back(Node->getOperand(i));
5207 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
5208 Node->getOperand(i).getValueType(),
5209 Node->getOperand(i)), 0));
5212 DAG.UpdateNodeOperands(Node, Ops);
5216 /// \brief Fold the instructions after selecting them.
5217 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
5218 SelectionDAG &DAG) const {
5219 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5220 unsigned Opcode = Node->getMachineOpcode();
5222 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
5223 !TII->isGather4(Opcode))
5224 adjustWritemask(Node, DAG);
5226 if (Opcode == AMDGPU::INSERT_SUBREG ||
5227 Opcode == AMDGPU::REG_SEQUENCE) {
5228 legalizeTargetIndependentNode(Node, DAG);
5234 /// \brief Assign the register class depending on the number of
5235 /// bits set in the writemask
5236 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
5237 SDNode *Node) const {
5238 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5240 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5242 if (TII->isVOP3(MI.getOpcode())) {
5243 // Make sure constant bus requirements are respected.
5244 TII->legalizeOperandsVOP3(MRI, MI);
5248 if (TII->isMIMG(MI)) {
5249 unsigned VReg = MI.getOperand(0).getReg();
5250 const TargetRegisterClass *RC = MRI.getRegClass(VReg);
5251 // TODO: Need mapping tables to handle other cases (register classes).
5252 if (RC != &AMDGPU::VReg_128RegClass)
5255 unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
5256 unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
5257 unsigned BitsSet = 0;
5258 for (unsigned i = 0; i < 4; ++i)
5259 BitsSet += Writemask & (1 << i) ? 1 : 0;
5262 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
5263 case 2: RC = &AMDGPU::VReg_64RegClass; break;
5264 case 3: RC = &AMDGPU::VReg_96RegClass; break;
5267 unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
5268 MI.setDesc(TII->get(NewOpcode));
5269 MRI.setRegClass(VReg, RC);
5273 // Replace unused atomics with the no return version.
5274 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
5275 if (NoRetAtomicOp != -1) {
5276 if (!Node->hasAnyUseOfValue(0)) {
5277 MI.setDesc(TII->get(NoRetAtomicOp));
5278 MI.RemoveOperand(0);
5282 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
5283 // instruction, because the return type of these instructions is a vec2 of
5284 // the memory type, so it can be tied to the input operand.
5285 // This means these instructions always have a use, so we need to add a
5286 // special case to check if the atomic has only one extract_subreg use,
5287 // which itself has no uses.
5288 if ((Node->hasNUsesOfValue(1, 0) &&
5289 Node->use_begin()->isMachineOpcode() &&
5290 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
5291 !Node->use_begin()->hasAnyUseOfValue(0))) {
5292 unsigned Def = MI.getOperand(0).getReg();
5294 // Change this into a noret atomic.
5295 MI.setDesc(TII->get(NoRetAtomicOp));
5296 MI.RemoveOperand(0);
5298 // If we only remove the def operand from the atomic instruction, the
5299 // extract_subreg will be left with a use of a vreg without a def.
5300 // So we need to insert an implicit_def to avoid machine verifier
5302 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
5303 TII->get(AMDGPU::IMPLICIT_DEF), Def);
5309 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
5311 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
5312 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
5315 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
5317 SDValue Ptr) const {
5318 const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5320 // Build the half of the subregister with the constants before building the
5321 // full 128-bit register. If we are building multiple resource descriptors,
5322 // this will allow CSEing of the 2-component register.
5323 const SDValue Ops0[] = {
5324 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
5325 buildSMovImm32(DAG, DL, 0),
5326 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5327 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
5328 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
5331 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
5332 MVT::v2i32, Ops0), 0);
5334 // Combine the constants and the pointer.
5335 const SDValue Ops1[] = {
5336 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5338 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
5340 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
5343 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
5346 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
5347 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
5348 /// of the resource descriptor) to create an offset, which is added to
5349 /// the resource pointer.
5350 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
5351 SDValue Ptr, uint32_t RsrcDword1,
5352 uint64_t RsrcDword2And3) const {
5353 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
5354 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
5356 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
5357 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
5361 SDValue DataLo = buildSMovImm32(DAG, DL,
5362 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
5363 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
5365 const SDValue Ops[] = {
5366 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
5368 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
5370 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
5372 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
5374 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
5377 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
5380 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
5381 const TargetRegisterClass *RC,
5382 unsigned Reg, EVT VT) const {
5383 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
5385 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
5386 cast<RegisterSDNode>(VReg)->getReg(), VT);
5389 //===----------------------------------------------------------------------===//
5390 // SI Inline Assembly Support
5391 //===----------------------------------------------------------------------===//
5393 std::pair<unsigned, const TargetRegisterClass *>
5394 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
5395 StringRef Constraint,
5397 if (!isTypeLegal(VT))
5398 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5400 if (Constraint.size() == 1) {
5401 switch (Constraint[0]) {
5404 switch (VT.getSizeInBits()) {
5406 return std::make_pair(0U, nullptr);
5409 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
5411 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
5413 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
5415 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
5417 return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
5421 switch (VT.getSizeInBits()) {
5423 return std::make_pair(0U, nullptr);
5426 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
5428 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
5430 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
5432 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
5434 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
5436 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
5441 if (Constraint.size() > 1) {
5442 const TargetRegisterClass *RC = nullptr;
5443 if (Constraint[1] == 'v') {
5444 RC = &AMDGPU::VGPR_32RegClass;
5445 } else if (Constraint[1] == 's') {
5446 RC = &AMDGPU::SGPR_32RegClass;
5451 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
5452 if (!Failed && Idx < RC->getNumRegs())
5453 return std::make_pair(RC->getRegister(Idx), RC);
5456 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5459 SITargetLowering::ConstraintType
5460 SITargetLowering::getConstraintType(StringRef Constraint) const {
5461 if (Constraint.size() == 1) {
5462 switch (Constraint[0]) {
5466 return C_RegisterClass;
5469 return TargetLowering::getConstraintType(Constraint);