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 "SIISelLowering.h"
23 #include "AMDGPUDiagnosticInfoUnsupported.h"
24 #include "AMDGPUIntrinsicInfo.h"
25 #include "AMDGPUSubtarget.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/ADT/SmallString.h"
39 SITargetLowering::SITargetLowering(TargetMachine &TM,
40 const AMDGPUSubtarget &STI)
41 : AMDGPUTargetLowering(TM, STI) {
42 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
43 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
45 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
46 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
48 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
49 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
51 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
52 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
53 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
55 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
56 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
58 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
59 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
61 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
62 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
64 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
65 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
67 computeRegisterProperties(STI.getRegisterInfo());
69 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
70 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
71 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
72 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
74 setOperationAction(ISD::ADD, MVT::i32, Legal);
75 setOperationAction(ISD::ADDC, MVT::i32, Legal);
76 setOperationAction(ISD::ADDE, MVT::i32, Legal);
77 setOperationAction(ISD::SUBC, MVT::i32, Legal);
78 setOperationAction(ISD::SUBE, MVT::i32, Legal);
80 setOperationAction(ISD::FSIN, MVT::f32, Custom);
81 setOperationAction(ISD::FCOS, MVT::f32, Custom);
83 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
84 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
86 // We need to custom lower vector stores from local memory
87 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
88 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
89 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
91 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
92 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
94 setOperationAction(ISD::STORE, MVT::i1, Custom);
95 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
97 setOperationAction(ISD::SELECT, MVT::i64, Custom);
98 setOperationAction(ISD::SELECT, MVT::f64, Promote);
99 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
101 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
104 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
106 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
107 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
109 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
110 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
129 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
130 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
132 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
133 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
135 for (MVT VT : MVT::integer_valuetypes()) {
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
144 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
145 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
146 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
147 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
149 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
150 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
151 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
152 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
155 for (MVT VT : MVT::integer_vector_valuetypes()) {
156 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
157 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
160 for (MVT VT : MVT::fp_valuetypes())
161 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
163 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
164 setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
166 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
167 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
168 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
169 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
172 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
174 setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
175 setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
177 setOperationAction(ISD::LOAD, MVT::i1, Custom);
179 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
180 AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
182 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
183 AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
185 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
187 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
188 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
189 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
191 // These should use UDIVREM, so set them to expand
192 setOperationAction(ISD::UDIV, MVT::i64, Expand);
193 setOperationAction(ISD::UREM, MVT::i64, Expand);
195 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
196 setOperationAction(ISD::SELECT, MVT::i1, Promote);
198 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
201 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
203 // We only support LOAD/STORE and vector manipulation ops for vectors
204 // with > 4 elements.
205 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
206 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
210 case ISD::BUILD_VECTOR:
212 case ISD::EXTRACT_VECTOR_ELT:
213 case ISD::INSERT_VECTOR_ELT:
214 case ISD::INSERT_SUBVECTOR:
215 case ISD::EXTRACT_SUBVECTOR:
216 case ISD::SCALAR_TO_VECTOR:
218 case ISD::CONCAT_VECTORS:
219 setOperationAction(Op, VT, Custom);
222 setOperationAction(Op, VT, Expand);
228 // Most operations are naturally 32-bit vector operations. We only support
229 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
230 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
231 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
232 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
234 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
235 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
237 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
238 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
240 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
241 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
244 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
245 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
246 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
247 setOperationAction(ISD::FRINT, MVT::f64, Legal);
250 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
251 setOperationAction(ISD::FDIV, MVT::f32, Custom);
252 setOperationAction(ISD::FDIV, MVT::f64, Custom);
254 setTargetDAGCombine(ISD::FADD);
255 setTargetDAGCombine(ISD::FSUB);
256 setTargetDAGCombine(ISD::FMINNUM);
257 setTargetDAGCombine(ISD::FMAXNUM);
258 setTargetDAGCombine(ISD::SMIN);
259 setTargetDAGCombine(ISD::SMAX);
260 setTargetDAGCombine(ISD::UMIN);
261 setTargetDAGCombine(ISD::UMAX);
262 setTargetDAGCombine(ISD::SELECT_CC);
263 setTargetDAGCombine(ISD::SETCC);
264 setTargetDAGCombine(ISD::AND);
265 setTargetDAGCombine(ISD::OR);
266 setTargetDAGCombine(ISD::UINT_TO_FP);
268 // All memory operations. Some folding on the pointer operand is done to help
269 // matching the constant offsets in the addressing modes.
270 setTargetDAGCombine(ISD::LOAD);
271 setTargetDAGCombine(ISD::STORE);
272 setTargetDAGCombine(ISD::ATOMIC_LOAD);
273 setTargetDAGCombine(ISD::ATOMIC_STORE);
274 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
275 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
276 setTargetDAGCombine(ISD::ATOMIC_SWAP);
277 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
278 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
279 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
280 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
281 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
282 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
283 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
284 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
285 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
286 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
288 setSchedulingPreference(Sched::RegPressure);
291 //===----------------------------------------------------------------------===//
292 // TargetLowering queries
293 //===----------------------------------------------------------------------===//
295 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
297 // SI has some legal vector types, but no legal vector operations. Say no
298 // shuffles are legal in order to prefer scalarizing some vector operations.
302 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
303 // Flat instructions do not have offsets, and only have the register
305 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
308 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
309 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
310 // additionally can do r + r + i with addr64. 32-bit has more addressing
311 // mode options. Depending on the resource constant, it can also do
312 // (i64 r0) + (i32 r1) * (i14 i).
314 // Private arrays end up using a scratch buffer most of the time, so also
315 // assume those use MUBUF instructions. Scratch loads / stores are currently
316 // implemented as mubuf instructions with offen bit set, so slightly
317 // different than the normal addr64.
318 if (!isUInt<12>(AM.BaseOffs))
321 // FIXME: Since we can split immediate into soffset and immediate offset,
322 // would it make sense to allow any immediate?
325 case 0: // r + i or just i, depending on HasBaseReg.
328 return true; // We have r + r or r + i.
335 // Allow 2 * r as r + r
336 // Or 2 * r + i is allowed as r + r + i.
338 default: // Don't allow n * r
343 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
344 const AddrMode &AM, Type *Ty,
346 // No global is ever allowed as a base.
351 case AMDGPUAS::GLOBAL_ADDRESS: {
352 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
353 // Assume the we will use FLAT for all global memory accesses
355 // FIXME: This assumption is currently wrong. On VI we still use
356 // MUBUF instructions for the r + i addressing mode. As currently
357 // implemented, the MUBUF instructions only work on buffer < 4GB.
358 // It may be possible to support > 4GB buffers with MUBUF instructions,
359 // by setting the stride value in the resource descriptor which would
360 // increase the size limit to (stride * 4GB). However, this is risky,
361 // because it has never been validated.
362 return isLegalFlatAddressingMode(AM);
365 return isLegalMUBUFAddressingMode(AM);
367 case AMDGPUAS::CONSTANT_ADDRESS: {
368 // If the offset isn't a multiple of 4, it probably isn't going to be
369 // correctly aligned.
370 if (AM.BaseOffs % 4 != 0)
371 return isLegalMUBUFAddressingMode(AM);
373 // There are no SMRD extloads, so if we have to do a small type access we
374 // will use a MUBUF load.
375 // FIXME?: We also need to do this if unaligned, but we don't know the
377 if (DL.getTypeStoreSize(Ty) < 4)
378 return isLegalMUBUFAddressingMode(AM);
380 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
381 // SMRD instructions have an 8-bit, dword offset on SI.
382 if (!isUInt<8>(AM.BaseOffs / 4))
384 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
385 // On CI+, this can also be a 32-bit literal constant offset. If it fits
386 // in 8-bits, it can use a smaller encoding.
387 if (!isUInt<32>(AM.BaseOffs / 4))
389 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
390 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
391 if (!isUInt<20>(AM.BaseOffs))
394 llvm_unreachable("unhandled generation");
396 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
399 if (AM.Scale == 1 && AM.HasBaseReg)
405 case AMDGPUAS::PRIVATE_ADDRESS:
406 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
407 return isLegalMUBUFAddressingMode(AM);
409 case AMDGPUAS::LOCAL_ADDRESS:
410 case AMDGPUAS::REGION_ADDRESS: {
411 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
413 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
414 // an 8-bit dword offset but we don't know the alignment here.
415 if (!isUInt<16>(AM.BaseOffs))
418 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
421 if (AM.Scale == 1 && AM.HasBaseReg)
426 case AMDGPUAS::FLAT_ADDRESS:
427 return isLegalFlatAddressingMode(AM);
430 llvm_unreachable("unhandled address space");
434 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
437 bool *IsFast) const {
441 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
442 // which isn't a simple VT.
443 if (!VT.isSimple() || VT == MVT::Other)
446 // TODO - CI+ supports unaligned memory accesses, but this requires driver
449 // XXX - The only mention I see of this in the ISA manual is for LDS direct
450 // reads the "byte address and must be dword aligned". Is it also true for the
451 // normal loads and stores?
452 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
453 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
454 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
455 // with adjacent offsets.
456 bool AlignedBy4 = (Align % 4 == 0);
458 *IsFast = AlignedBy4;
462 // Smaller than dword value must be aligned.
463 // FIXME: This should be allowed on CI+
464 if (VT.bitsLT(MVT::i32))
467 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
468 // byte-address are ignored, thus forcing Dword alignment.
469 // This applies to private, global, and constant memory.
473 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
476 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
477 unsigned SrcAlign, bool IsMemset,
480 MachineFunction &MF) const {
481 // FIXME: Should account for address space here.
483 // The default fallback uses the private pointer size as a guess for a type to
484 // use. Make sure we switch these to 64-bit accesses.
486 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
489 if (Size >= 8 && DstAlign >= 4)
496 static bool isFlatGlobalAddrSpace(unsigned AS) {
497 return AS == AMDGPUAS::GLOBAL_ADDRESS ||
498 AS == AMDGPUAS::FLAT_ADDRESS ||
499 AS == AMDGPUAS::CONSTANT_ADDRESS;
502 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
503 unsigned DestAS) const {
504 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
507 TargetLoweringBase::LegalizeTypeAction
508 SITargetLowering::getPreferredVectorAction(EVT VT) const {
509 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
510 return TypeSplitVector;
512 return TargetLoweringBase::getPreferredVectorAction(VT);
515 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
517 const SIInstrInfo *TII =
518 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
519 return TII->isInlineConstant(Imm);
522 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
523 SDLoc SL, SDValue Chain,
524 unsigned Offset, bool Signed) const {
525 const DataLayout &DL = DAG.getDataLayout();
526 MachineFunction &MF = DAG.getMachineFunction();
527 const SIRegisterInfo *TRI =
528 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
529 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
531 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
533 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
534 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
535 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
536 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
537 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
538 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
539 DAG.getConstant(Offset, SL, PtrVT));
540 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
541 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
543 unsigned Align = DL.getABITypeAlignment(Ty);
545 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
546 if (MemVT.isFloatingPoint())
547 ExtTy = ISD::EXTLOAD;
549 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
550 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
552 true, // isNonTemporal
557 SDValue SITargetLowering::LowerFormalArguments(
558 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
559 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
560 SmallVectorImpl<SDValue> &InVals) const {
561 const SIRegisterInfo *TRI =
562 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
564 MachineFunction &MF = DAG.getMachineFunction();
565 FunctionType *FType = MF.getFunction()->getFunctionType();
566 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
567 const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
569 if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) {
570 const Function *Fn = MF.getFunction();
571 DiagnosticInfoUnsupported NoGraphicsHSA(*Fn, "non-compute shaders with HSA");
572 DAG.getContext()->diagnose(NoGraphicsHSA);
576 // FIXME: We currently assume all calling conventions are kernels.
578 SmallVector<ISD::InputArg, 16> Splits;
579 BitVector Skipped(Ins.size());
581 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
582 const ISD::InputArg &Arg = Ins[i];
584 // First check if it's a PS input addr
585 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
586 !Arg.Flags.isByVal()) {
588 assert((PSInputNum <= 15) && "Too many PS inputs!");
591 // We can safely skip PS inputs
597 Info->PSInputAddr |= 1 << PSInputNum++;
600 // Second split vertices into their elements
601 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
602 ISD::InputArg NewArg = Arg;
603 NewArg.Flags.setSplit();
604 NewArg.VT = Arg.VT.getVectorElementType();
606 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
607 // three or five element vertex only needs three or five registers,
608 // NOT four or eight.
609 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
610 unsigned NumElements = ParamType->getVectorNumElements();
612 for (unsigned j = 0; j != NumElements; ++j) {
613 Splits.push_back(NewArg);
614 NewArg.PartOffset += NewArg.VT.getStoreSize();
617 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
618 Splits.push_back(Arg);
622 SmallVector<CCValAssign, 16> ArgLocs;
623 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
626 // At least one interpolation mode must be enabled or else the GPU will hang.
627 if (Info->getShaderType() == ShaderType::PIXEL &&
628 (Info->PSInputAddr & 0x7F) == 0) {
629 Info->PSInputAddr |= 1;
630 CCInfo.AllocateReg(AMDGPU::VGPR0);
631 CCInfo.AllocateReg(AMDGPU::VGPR1);
634 if (Info->getShaderType() == ShaderType::COMPUTE) {
635 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
639 // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
640 if (Info->hasPrivateSegmentBuffer()) {
641 unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
642 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
643 CCInfo.AllocateReg(PrivateSegmentBufferReg);
646 if (Info->hasDispatchPtr()) {
647 unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
648 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
649 CCInfo.AllocateReg(DispatchPtrReg);
652 if (Info->hasKernargSegmentPtr()) {
653 unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
654 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
655 CCInfo.AllocateReg(InputPtrReg);
658 AnalyzeFormalArguments(CCInfo, Splits);
660 SmallVector<SDValue, 16> Chains;
662 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
664 const ISD::InputArg &Arg = Ins[i];
666 InVals.push_back(DAG.getUNDEF(Arg.VT));
670 CCValAssign &VA = ArgLocs[ArgIdx++];
671 MVT VT = VA.getLocVT();
675 EVT MemVT = Splits[i].VT;
676 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
677 VA.getLocMemOffset();
678 // The first 36 bytes of the input buffer contains information about
679 // thread group and global sizes.
680 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
681 Offset, Ins[i].Flags.isSExt());
682 Chains.push_back(Arg.getValue(1));
685 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
686 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
687 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
688 // On SI local pointers are just offsets into LDS, so they are always
689 // less than 16-bits. On CI and newer they could potentially be
690 // real pointers, so we can't guarantee their size.
691 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
692 DAG.getValueType(MVT::i16));
695 InVals.push_back(Arg);
696 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
699 assert(VA.isRegLoc() && "Parameter must be in a register!");
701 unsigned Reg = VA.getLocReg();
703 if (VT == MVT::i64) {
704 // For now assume it is a pointer
705 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
706 &AMDGPU::SReg_64RegClass);
707 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
708 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
709 InVals.push_back(Copy);
713 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
715 Reg = MF.addLiveIn(Reg, RC);
716 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
718 if (Arg.VT.isVector()) {
720 // Build a vector from the registers
721 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
722 unsigned NumElements = ParamType->getVectorNumElements();
724 SmallVector<SDValue, 4> Regs;
726 for (unsigned j = 1; j != NumElements; ++j) {
727 Reg = ArgLocs[ArgIdx++].getLocReg();
728 Reg = MF.addLiveIn(Reg, RC);
730 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
731 Regs.push_back(Copy);
734 // Fill up the missing vector elements
735 NumElements = Arg.VT.getVectorNumElements() - NumElements;
736 Regs.append(NumElements, DAG.getUNDEF(VT));
738 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
742 InVals.push_back(Val);
745 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
746 // these from the dispatch pointer.
748 // Start adding system SGPRs.
749 if (Info->hasWorkGroupIDX()) {
750 unsigned Reg = Info->addWorkGroupIDX();
751 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
752 CCInfo.AllocateReg(Reg);
754 llvm_unreachable("work group id x is always enabled");
756 if (Info->hasWorkGroupIDY()) {
757 unsigned Reg = Info->addWorkGroupIDY();
758 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
759 CCInfo.AllocateReg(Reg);
762 if (Info->hasWorkGroupIDZ()) {
763 unsigned Reg = Info->addWorkGroupIDZ();
764 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
765 CCInfo.AllocateReg(Reg);
768 if (Info->hasWorkGroupInfo()) {
769 unsigned Reg = Info->addWorkGroupInfo();
770 MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
771 CCInfo.AllocateReg(Reg);
774 if (Info->hasPrivateSegmentWaveByteOffset()) {
775 // Scratch wave offset passed in system SGPR.
776 unsigned PrivateSegmentWaveByteOffsetReg
777 = Info->addPrivateSegmentWaveByteOffset();
779 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
780 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
783 // Now that we've figured out where the scratch register inputs are, see if
784 // should reserve the arguments and use them directly.
786 bool HasStackObjects = MF.getFrameInfo()->hasStackObjects();
788 if (ST.isAmdHsaOS()) {
789 // TODO: Assume we will spill without optimizations.
790 if (HasStackObjects) {
791 // If we have stack objects, we unquestionably need the private buffer
792 // resource. For the HSA ABI, this will be the first 4 user SGPR
793 // inputs. We can reserve those and use them directly.
795 unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
796 MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
797 Info->setScratchRSrcReg(PrivateSegmentBufferReg);
799 unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
800 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
801 Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
803 unsigned ReservedBufferReg
804 = TRI->reservedPrivateSegmentBufferReg(MF);
805 unsigned ReservedOffsetReg
806 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
808 // We tentatively reserve the last registers (skipping the last two
809 // which may contain VCC). After register allocation, we'll replace
810 // these with the ones immediately after those which were really
811 // allocated. In the prologue copies will be inserted from the argument
812 // to these reserved registers.
813 Info->setScratchRSrcReg(ReservedBufferReg);
814 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
817 unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
819 // Without HSA, relocations are used for the scratch pointer and the
820 // buffer resource setup is always inserted in the prologue. Scratch wave
821 // offset is still in an input SGPR.
822 Info->setScratchRSrcReg(ReservedBufferReg);
824 if (HasStackObjects) {
825 unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
826 MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
827 Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
829 unsigned ReservedOffsetReg
830 = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
831 Info->setScratchWaveOffsetReg(ReservedOffsetReg);
835 if (Info->hasWorkItemIDX()) {
836 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
837 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
838 CCInfo.AllocateReg(Reg);
840 llvm_unreachable("workitem id x should always be enabled");
842 if (Info->hasWorkItemIDY()) {
843 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
844 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
845 CCInfo.AllocateReg(Reg);
848 if (Info->hasWorkItemIDZ()) {
849 unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
850 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
851 CCInfo.AllocateReg(Reg);
857 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
860 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
861 MachineInstr * MI, MachineBasicBlock * BB) const {
863 switch (MI->getOpcode()) {
865 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
872 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
873 // This currently forces unfolding various combinations of fsub into fma with
874 // free fneg'd operands. As long as we have fast FMA (controlled by
875 // isFMAFasterThanFMulAndFAdd), we should perform these.
877 // When fma is quarter rate, for f64 where add / sub are at best half rate,
878 // most of these combines appear to be cycle neutral but save on instruction
879 // count / code size.
883 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
885 if (!VT.isVector()) {
888 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
891 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
895 // Answering this is somewhat tricky and depends on the specific device which
896 // have different rates for fma or all f64 operations.
898 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
899 // regardless of which device (although the number of cycles differs between
900 // devices), so it is always profitable for f64.
902 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
903 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
904 // which we can always do even without fused FP ops since it returns the same
905 // result as the separate operations and since it is always full
906 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
907 // however does not support denormals, so we do report fma as faster if we have
908 // a fast fma device and require denormals.
910 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
911 VT = VT.getScalarType();
916 switch (VT.getSimpleVT().SimpleTy) {
918 // This is as fast on some subtargets. However, we always have full rate f32
919 // mad available which returns the same result as the separate operations
920 // which we should prefer over fma. We can't use this if we want to support
921 // denormals, so only report this in these cases.
922 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
932 //===----------------------------------------------------------------------===//
933 // Custom DAG Lowering Operations
934 //===----------------------------------------------------------------------===//
936 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
937 switch (Op.getOpcode()) {
938 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
939 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
940 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
942 SDValue Result = LowerLOAD(Op, DAG);
943 assert((!Result.getNode() ||
944 Result.getNode()->getNumValues() == 2) &&
945 "Load should return a value and a chain");
951 return LowerTrig(Op, DAG);
952 case ISD::SELECT: return LowerSELECT(Op, DAG);
953 case ISD::FDIV: return LowerFDIV(Op, DAG);
954 case ISD::STORE: return LowerSTORE(Op, DAG);
955 case ISD::GlobalAddress: {
956 MachineFunction &MF = DAG.getMachineFunction();
957 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
958 return LowerGlobalAddress(MFI, Op, DAG);
960 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
961 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
966 /// \brief Helper function for LowerBRCOND
967 static SDNode *findUser(SDValue Value, unsigned Opcode) {
969 SDNode *Parent = Value.getNode();
970 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
973 if (I.getUse().get() != Value)
976 if (I->getOpcode() == Opcode)
982 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
985 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
986 unsigned FrameIndex = FINode->getIndex();
988 // A FrameIndex node represents a 32-bit offset into scratch memory. If
989 // the high bit of a frame index offset were to be set, this would mean
990 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
991 // scratch buffer, with 64 being the number of threads per wave.
993 // If we know the machine uses less than 128GB of scratch, then we can
994 // amrk the high bit of the FrameIndex node as known zero,
995 // which is important, because it means in most situations we can
996 // prove that values derived from FrameIndex nodes are non-negative.
997 // This enables us to take advantage of more addressing modes when
998 // accessing scratch buffers, since for scratch reads/writes, the register
999 // offset must always be positive.
1001 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
1002 if (Subtarget->enableHugeScratchBuffer())
1005 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
1006 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
1009 /// This transforms the control flow intrinsics to get the branch destination as
1010 /// last parameter, also switches branch target with BR if the need arise
1011 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1012 SelectionDAG &DAG) const {
1016 SDNode *Intr = BRCOND.getOperand(1).getNode();
1017 SDValue Target = BRCOND.getOperand(2);
1018 SDNode *BR = nullptr;
1020 if (Intr->getOpcode() == ISD::SETCC) {
1021 // As long as we negate the condition everything is fine
1022 SDNode *SetCC = Intr;
1023 assert(SetCC->getConstantOperandVal(1) == 1);
1024 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1026 Intr = SetCC->getOperand(0).getNode();
1029 // Get the target from BR if we don't negate the condition
1030 BR = findUser(BRCOND, ISD::BR);
1031 Target = BR->getOperand(1);
1034 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
1036 // Build the result and
1037 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1039 // operands of the new intrinsic call
1040 SmallVector<SDValue, 4> Ops;
1041 Ops.push_back(BRCOND.getOperand(0));
1042 Ops.append(Intr->op_begin() + 1, Intr->op_end());
1043 Ops.push_back(Target);
1045 // build the new intrinsic call
1046 SDNode *Result = DAG.getNode(
1047 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1048 DAG.getVTList(Res), Ops).getNode();
1051 // Give the branch instruction our target
1054 BRCOND.getOperand(2)
1056 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
1057 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
1058 BR = NewBR.getNode();
1061 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
1063 // Copy the intrinsic results to registers
1064 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
1065 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
1069 Chain = DAG.getCopyToReg(
1071 CopyToReg->getOperand(1),
1072 SDValue(Result, i - 1),
1075 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
1078 // Remove the old intrinsic from the chain
1079 DAG.ReplaceAllUsesOfValueWith(
1080 SDValue(Intr, Intr->getNumValues() - 1),
1081 Intr->getOperand(0));
1086 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1088 SelectionDAG &DAG) const {
1089 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1091 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1092 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1095 const GlobalValue *GV = GSD->getGlobal();
1096 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
1098 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
1099 return DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT, GA);
1102 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1104 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1105 // so we will end up with redundant moves to m0.
1107 // We can't use S_MOV_B32, because there is no way to specify m0 as the
1108 // destination register.
1110 // We have to use them both. Machine cse will combine all the S_MOV_B32
1111 // instructions and the register coalescer eliminate the extra copies.
1112 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1113 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1114 SDValue(M0, 0), SDValue()); // Glue
1115 // A Null SDValue creates
1119 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1122 unsigned Offset) const {
1124 SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1125 DAG.getEntryNode(), Offset, false);
1126 // The local size values will have the hi 16-bits as zero.
1127 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1128 DAG.getValueType(VT));
1131 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1132 SelectionDAG &DAG) const {
1133 MachineFunction &MF = DAG.getMachineFunction();
1134 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1135 const SIRegisterInfo *TRI =
1136 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1138 EVT VT = Op.getValueType();
1140 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1142 // TODO: Should this propagate fast-math-flags?
1144 switch (IntrinsicID) {
1145 case Intrinsic::amdgcn_dispatch_ptr:
1146 return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1147 TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT);
1149 case Intrinsic::r600_read_ngroups_x:
1150 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1151 SI::KernelInputOffsets::NGROUPS_X, false);
1152 case Intrinsic::r600_read_ngroups_y:
1153 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1154 SI::KernelInputOffsets::NGROUPS_Y, false);
1155 case Intrinsic::r600_read_ngroups_z:
1156 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1157 SI::KernelInputOffsets::NGROUPS_Z, false);
1158 case Intrinsic::r600_read_global_size_x:
1159 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1160 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1161 case Intrinsic::r600_read_global_size_y:
1162 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1163 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1164 case Intrinsic::r600_read_global_size_z:
1165 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1166 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1167 case Intrinsic::r600_read_local_size_x:
1168 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1169 SI::KernelInputOffsets::LOCAL_SIZE_X);
1170 case Intrinsic::r600_read_local_size_y:
1171 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1172 SI::KernelInputOffsets::LOCAL_SIZE_Y);
1173 case Intrinsic::r600_read_local_size_z:
1174 return lowerImplicitZextParam(DAG, Op, MVT::i16,
1175 SI::KernelInputOffsets::LOCAL_SIZE_Z);
1176 case Intrinsic::AMDGPU_read_workdim:
1177 // Really only 2 bits.
1178 return lowerImplicitZextParam(DAG, Op, MVT::i8,
1179 getImplicitParameterOffset(MFI, GRID_DIM));
1180 case Intrinsic::r600_read_tgid_x:
1181 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1182 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1183 case Intrinsic::r600_read_tgid_y:
1184 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1185 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1186 case Intrinsic::r600_read_tgid_z:
1187 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1188 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1189 case Intrinsic::r600_read_tidig_x:
1190 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1191 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1192 case Intrinsic::r600_read_tidig_y:
1193 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1194 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1195 case Intrinsic::r600_read_tidig_z:
1196 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1197 TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1198 case AMDGPUIntrinsic::SI_load_const: {
1204 MachineMemOperand *MMO = MF.getMachineMemOperand(
1205 MachinePointerInfo(),
1206 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1207 VT.getStoreSize(), 4);
1208 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1209 Op->getVTList(), Ops, VT, MMO);
1211 case AMDGPUIntrinsic::SI_sample:
1212 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1213 case AMDGPUIntrinsic::SI_sampleb:
1214 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1215 case AMDGPUIntrinsic::SI_sampled:
1216 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1217 case AMDGPUIntrinsic::SI_samplel:
1218 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1219 case AMDGPUIntrinsic::SI_vs_load_input:
1220 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1225 case AMDGPUIntrinsic::AMDGPU_fract:
1226 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1227 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1228 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1229 case AMDGPUIntrinsic::SI_fs_constant: {
1230 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1231 SDValue Glue = M0.getValue(1);
1232 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1233 DAG.getConstant(2, DL, MVT::i32), // P0
1234 Op.getOperand(1), Op.getOperand(2), Glue);
1236 case AMDGPUIntrinsic::SI_packf16:
1237 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1238 return DAG.getUNDEF(MVT::i32);
1240 case AMDGPUIntrinsic::SI_fs_interp: {
1241 SDValue IJ = Op.getOperand(4);
1242 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1243 DAG.getConstant(0, DL, MVT::i32));
1244 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1245 DAG.getConstant(1, DL, MVT::i32));
1246 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1247 SDValue Glue = M0.getValue(1);
1248 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1249 DAG.getVTList(MVT::f32, MVT::Glue),
1250 I, Op.getOperand(1), Op.getOperand(2), Glue);
1251 Glue = SDValue(P1.getNode(), 1);
1252 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1253 Op.getOperand(1), Op.getOperand(2), Glue);
1255 case Intrinsic::amdgcn_interp_p1: {
1256 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
1257 SDValue Glue = M0.getValue(1);
1258 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
1259 Op.getOperand(2), Op.getOperand(3), Glue);
1261 case Intrinsic::amdgcn_interp_p2: {
1262 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
1263 SDValue Glue = SDValue(M0.getNode(), 1);
1264 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
1265 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
1269 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1273 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1274 SelectionDAG &DAG) const {
1275 MachineFunction &MF = DAG.getMachineFunction();
1277 SDValue Chain = Op.getOperand(0);
1278 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1280 switch (IntrinsicID) {
1281 case AMDGPUIntrinsic::SI_sendmsg: {
1282 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1283 SDValue Glue = Chain.getValue(1);
1284 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1285 Op.getOperand(2), Glue);
1287 case AMDGPUIntrinsic::SI_tbuffer_store: {
1305 EVT VT = Op.getOperand(3).getValueType();
1307 MachineMemOperand *MMO = MF.getMachineMemOperand(
1308 MachinePointerInfo(),
1309 MachineMemOperand::MOStore,
1310 VT.getStoreSize(), 4);
1311 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1312 Op->getVTList(), Ops, VT, MMO);
1319 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1321 LoadSDNode *Load = cast<LoadSDNode>(Op);
1323 if (Op.getValueType().isVector()) {
1324 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1325 "Custom lowering for non-i32 vectors hasn't been implemented.");
1326 unsigned NumElements = Op.getValueType().getVectorNumElements();
1327 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1329 switch (Load->getAddressSpace()) {
1331 case AMDGPUAS::GLOBAL_ADDRESS:
1332 case AMDGPUAS::PRIVATE_ADDRESS:
1333 if (NumElements >= 8)
1334 return SplitVectorLoad(Op, DAG);
1336 // v4 loads are supported for private and global memory.
1337 if (NumElements <= 4)
1340 case AMDGPUAS::LOCAL_ADDRESS:
1341 // If properly aligned, if we split we might be able to use ds_read_b64.
1342 return SplitVectorLoad(Op, DAG);
1346 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1349 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1351 SelectionDAG &DAG) const {
1352 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1358 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1359 if (Op.getValueType() != MVT::i64)
1363 SDValue Cond = Op.getOperand(0);
1365 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1366 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1368 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1369 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1371 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1372 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1374 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1376 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1377 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1379 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1381 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1382 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1385 // Catch division cases where we can use shortcuts with rcp and rsq
1387 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1389 SDValue LHS = Op.getOperand(0);
1390 SDValue RHS = Op.getOperand(1);
1391 EVT VT = Op.getValueType();
1392 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1394 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1395 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1396 CLHS->isExactlyValue(1.0)) {
1397 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1398 // the CI documentation has a worst case error of 1 ulp.
1399 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1400 // use it as long as we aren't trying to use denormals.
1402 // 1.0 / sqrt(x) -> rsq(x)
1404 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1405 // error seems really high at 2^29 ULP.
1406 if (RHS.getOpcode() == ISD::FSQRT)
1407 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1409 // 1.0 / x -> rcp(x)
1410 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1415 // Turn into multiply by the reciprocal.
1416 // x / y -> x * (1.0 / y)
1418 Flags.setUnsafeAlgebra(true);
1419 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1420 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1426 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1427 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1428 if (FastLowered.getNode())
1431 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1432 // selection error for now rather than do something incorrect.
1433 if (Subtarget->hasFP32Denormals())
1437 SDValue LHS = Op.getOperand(0);
1438 SDValue RHS = Op.getOperand(1);
1440 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1442 const APFloat K0Val(BitsToFloat(0x6f800000));
1443 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1445 const APFloat K1Val(BitsToFloat(0x2f800000));
1446 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1448 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1451 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1453 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1455 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1457 // TODO: Should this propagate fast-math-flags?
1459 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1461 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1463 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1465 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1468 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1469 if (DAG.getTarget().Options.UnsafeFPMath)
1470 return LowerFastFDIV(Op, DAG);
1473 SDValue X = Op.getOperand(0);
1474 SDValue Y = Op.getOperand(1);
1476 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1478 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1480 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1482 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1484 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1486 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1488 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1490 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1492 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1494 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1495 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1497 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1498 NegDivScale0, Mul, DivScale1);
1502 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1503 // Workaround a hardware bug on SI where the condition output from div_scale
1506 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1508 // Figure out if the scale to use for div_fmas.
1509 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1510 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1511 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1512 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1514 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1515 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1518 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1520 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1522 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1523 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1524 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1526 Scale = DivScale1.getValue(1);
1529 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1530 Fma4, Fma3, Mul, Scale);
1532 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1535 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1536 EVT VT = Op.getValueType();
1539 return LowerFDIV32(Op, DAG);
1542 return LowerFDIV64(Op, DAG);
1544 llvm_unreachable("Unexpected type for fdiv");
1547 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1549 StoreSDNode *Store = cast<StoreSDNode>(Op);
1550 EVT VT = Store->getMemoryVT();
1552 // These stores are legal.
1553 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1554 if (VT.isVector() && VT.getVectorNumElements() > 4)
1555 return ScalarizeVectorStore(Op, DAG);
1559 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1563 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1564 return SplitVectorStore(Op, DAG);
1567 return DAG.getTruncStore(Store->getChain(), DL,
1568 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1569 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1574 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1576 EVT VT = Op.getValueType();
1577 SDValue Arg = Op.getOperand(0);
1578 // TODO: Should this propagate fast-math-flags?
1579 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1580 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1581 DAG.getConstantFP(0.5/M_PI, DL,
1584 switch (Op.getOpcode()) {
1586 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1588 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1590 llvm_unreachable("Wrong trig opcode");
1594 //===----------------------------------------------------------------------===//
1595 // Custom DAG optimizations
1596 //===----------------------------------------------------------------------===//
1598 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1599 DAGCombinerInfo &DCI) const {
1600 EVT VT = N->getValueType(0);
1601 EVT ScalarVT = VT.getScalarType();
1602 if (ScalarVT != MVT::f32)
1605 SelectionDAG &DAG = DCI.DAG;
1608 SDValue Src = N->getOperand(0);
1609 EVT SrcVT = Src.getValueType();
1611 // TODO: We could try to match extracting the higher bytes, which would be
1612 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1613 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1614 // about in practice.
1615 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1616 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1617 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1618 DCI.AddToWorklist(Cvt.getNode());
1623 // We are primarily trying to catch operations on illegal vector types
1624 // before they are expanded.
1625 // For scalars, we can use the more flexible method of checking masked bits
1626 // after legalization.
1627 if (!DCI.isBeforeLegalize() ||
1628 !SrcVT.isVector() ||
1629 SrcVT.getVectorElementType() != MVT::i8) {
1633 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1635 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1637 unsigned NElts = SrcVT.getVectorNumElements();
1638 if (!SrcVT.isSimple() && NElts != 3)
1641 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1642 // prevent a mess from expanding to v4i32 and repacking.
1643 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1644 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1645 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1646 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1647 LoadSDNode *Load = cast<LoadSDNode>(Src);
1649 unsigned AS = Load->getAddressSpace();
1650 unsigned Align = Load->getAlignment();
1651 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1652 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1654 // Don't try to replace the load if we have to expand it due to alignment
1655 // problems. Otherwise we will end up scalarizing the load, and trying to
1656 // repack into the vector for no real reason.
1657 if (Align < ABIAlignment &&
1658 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1662 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1666 Load->getMemOperand());
1668 // Make sure successors of the original load stay after it by updating
1669 // them to use the new Chain.
1670 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1672 SmallVector<SDValue, 4> Elts;
1673 if (RegVT.isVector())
1674 DAG.ExtractVectorElements(NewLoad, Elts);
1676 Elts.push_back(NewLoad);
1678 SmallVector<SDValue, 4> Ops;
1680 unsigned EltIdx = 0;
1681 for (SDValue Elt : Elts) {
1682 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1683 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1684 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1685 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1686 DCI.AddToWorklist(Cvt.getNode());
1693 assert(Ops.size() == NElts);
1695 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1701 /// \brief Return true if the given offset Size in bytes can be folded into
1702 /// the immediate offsets of a memory instruction for the given address space.
1703 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1704 const AMDGPUSubtarget &STI) {
1706 case AMDGPUAS::GLOBAL_ADDRESS: {
1707 // MUBUF instructions a 12-bit offset in bytes.
1708 return isUInt<12>(OffsetSize);
1710 case AMDGPUAS::CONSTANT_ADDRESS: {
1711 // SMRD instructions have an 8-bit offset in dwords on SI and
1712 // a 20-bit offset in bytes on VI.
1713 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1714 return isUInt<20>(OffsetSize);
1716 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1718 case AMDGPUAS::LOCAL_ADDRESS:
1719 case AMDGPUAS::REGION_ADDRESS: {
1720 // The single offset versions have a 16-bit offset in bytes.
1721 return isUInt<16>(OffsetSize);
1723 case AMDGPUAS::PRIVATE_ADDRESS:
1724 // Indirect register addressing does not use any offsets.
1730 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1732 // This is a variant of
1733 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1735 // The normal DAG combiner will do this, but only if the add has one use since
1736 // that would increase the number of instructions.
1738 // This prevents us from seeing a constant offset that can be folded into a
1739 // memory instruction's addressing mode. If we know the resulting add offset of
1740 // a pointer can be folded into an addressing offset, we can replace the pointer
1741 // operand with the add of new constant offset. This eliminates one of the uses,
1742 // and may allow the remaining use to also be simplified.
1744 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1746 DAGCombinerInfo &DCI) const {
1747 SDValue N0 = N->getOperand(0);
1748 SDValue N1 = N->getOperand(1);
1750 if (N0.getOpcode() != ISD::ADD)
1753 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1757 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1761 // If the resulting offset is too large, we can't fold it into the addressing
1763 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1764 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1767 SelectionDAG &DAG = DCI.DAG;
1769 EVT VT = N->getValueType(0);
1771 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1772 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1774 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1777 SDValue SITargetLowering::performAndCombine(SDNode *N,
1778 DAGCombinerInfo &DCI) const {
1779 if (DCI.isBeforeLegalize())
1782 SelectionDAG &DAG = DCI.DAG;
1784 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1785 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1786 SDValue LHS = N->getOperand(0);
1787 SDValue RHS = N->getOperand(1);
1789 if (LHS.getOpcode() == ISD::SETCC &&
1790 RHS.getOpcode() == ISD::SETCC) {
1791 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1792 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1794 SDValue X = LHS.getOperand(0);
1795 SDValue Y = RHS.getOperand(0);
1796 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1799 if (LCC == ISD::SETO) {
1800 if (X != LHS.getOperand(1))
1803 if (RCC == ISD::SETUNE) {
1804 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1805 if (!C1 || !C1->isInfinity() || C1->isNegative())
1808 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1809 SIInstrFlags::N_SUBNORMAL |
1810 SIInstrFlags::N_ZERO |
1811 SIInstrFlags::P_ZERO |
1812 SIInstrFlags::P_SUBNORMAL |
1813 SIInstrFlags::P_NORMAL;
1815 static_assert(((~(SIInstrFlags::S_NAN |
1816 SIInstrFlags::Q_NAN |
1817 SIInstrFlags::N_INFINITY |
1818 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1822 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1823 X, DAG.getConstant(Mask, DL, MVT::i32));
1831 SDValue SITargetLowering::performOrCombine(SDNode *N,
1832 DAGCombinerInfo &DCI) const {
1833 SelectionDAG &DAG = DCI.DAG;
1834 SDValue LHS = N->getOperand(0);
1835 SDValue RHS = N->getOperand(1);
1837 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1838 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1839 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1840 SDValue Src = LHS.getOperand(0);
1841 if (Src != RHS.getOperand(0))
1844 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1845 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1849 // Only 10 bits are used.
1850 static const uint32_t MaxMask = 0x3ff;
1852 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1854 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1855 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1861 SDValue SITargetLowering::performClassCombine(SDNode *N,
1862 DAGCombinerInfo &DCI) const {
1863 SelectionDAG &DAG = DCI.DAG;
1864 SDValue Mask = N->getOperand(1);
1866 // fp_class x, 0 -> false
1867 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1868 if (CMask->isNullValue())
1869 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1875 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1878 return AMDGPUISD::FMAX3;
1880 return AMDGPUISD::SMAX3;
1882 return AMDGPUISD::UMAX3;
1884 return AMDGPUISD::FMIN3;
1886 return AMDGPUISD::SMIN3;
1888 return AMDGPUISD::UMIN3;
1890 llvm_unreachable("Not a min/max opcode");
1894 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1895 DAGCombinerInfo &DCI) const {
1896 SelectionDAG &DAG = DCI.DAG;
1898 unsigned Opc = N->getOpcode();
1899 SDValue Op0 = N->getOperand(0);
1900 SDValue Op1 = N->getOperand(1);
1902 // Only do this if the inner op has one use since this will just increases
1903 // register pressure for no benefit.
1905 // max(max(a, b), c)
1906 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1908 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1916 // max(a, max(b, c))
1917 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1919 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1930 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1931 DAGCombinerInfo &DCI) const {
1932 SelectionDAG &DAG = DCI.DAG;
1935 SDValue LHS = N->getOperand(0);
1936 SDValue RHS = N->getOperand(1);
1937 EVT VT = LHS.getValueType();
1939 if (VT != MVT::f32 && VT != MVT::f64)
1942 // Match isinf pattern
1943 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1944 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1945 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1946 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1950 const APFloat &APF = CRHS->getValueAPF();
1951 if (APF.isInfinity() && !APF.isNegative()) {
1952 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1953 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1954 DAG.getConstant(Mask, SL, MVT::i32));
1961 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1962 DAGCombinerInfo &DCI) const {
1963 SelectionDAG &DAG = DCI.DAG;
1966 switch (N->getOpcode()) {
1968 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1970 return performSetCCCombine(N, DCI);
1971 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1977 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1978 N->getValueType(0) != MVT::f64 &&
1979 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1980 return performMin3Max3Combine(N, DCI);
1984 case AMDGPUISD::CVT_F32_UBYTE0:
1985 case AMDGPUISD::CVT_F32_UBYTE1:
1986 case AMDGPUISD::CVT_F32_UBYTE2:
1987 case AMDGPUISD::CVT_F32_UBYTE3: {
1988 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1990 SDValue Src = N->getOperand(0);
1991 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1993 APInt KnownZero, KnownOne;
1994 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1995 !DCI.isBeforeLegalizeOps());
1996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1997 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1998 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1999 DCI.CommitTargetLoweringOpt(TLO);
2005 case ISD::UINT_TO_FP: {
2006 return performUCharToFloatCombine(N, DCI);
2009 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2012 EVT VT = N->getValueType(0);
2016 // Only do this if we are not trying to support denormals. v_mad_f32 does
2017 // not support denormals ever.
2018 if (Subtarget->hasFP32Denormals())
2021 SDValue LHS = N->getOperand(0);
2022 SDValue RHS = N->getOperand(1);
2024 // These should really be instruction patterns, but writing patterns with
2025 // source modiifiers is a pain.
2027 // fadd (fadd (a, a), b) -> mad 2.0, a, b
2028 if (LHS.getOpcode() == ISD::FADD) {
2029 SDValue A = LHS.getOperand(0);
2030 if (A == LHS.getOperand(1)) {
2031 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2032 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
2036 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
2037 if (RHS.getOpcode() == ISD::FADD) {
2038 SDValue A = RHS.getOperand(0);
2039 if (A == RHS.getOperand(1)) {
2040 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2041 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
2048 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2051 EVT VT = N->getValueType(0);
2053 // Try to get the fneg to fold into the source modifier. This undoes generic
2054 // DAG combines and folds them into the mad.
2056 // Only do this if we are not trying to support denormals. v_mad_f32 does
2057 // not support denormals ever.
2058 if (VT == MVT::f32 &&
2059 !Subtarget->hasFP32Denormals()) {
2060 SDValue LHS = N->getOperand(0);
2061 SDValue RHS = N->getOperand(1);
2062 if (LHS.getOpcode() == ISD::FADD) {
2063 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
2065 SDValue A = LHS.getOperand(0);
2066 if (A == LHS.getOperand(1)) {
2067 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2068 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
2070 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
2074 if (RHS.getOpcode() == ISD::FADD) {
2075 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
2077 SDValue A = RHS.getOperand(0);
2078 if (A == RHS.getOperand(1)) {
2079 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
2080 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
2092 case ISD::ATOMIC_LOAD:
2093 case ISD::ATOMIC_STORE:
2094 case ISD::ATOMIC_CMP_SWAP:
2095 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2096 case ISD::ATOMIC_SWAP:
2097 case ISD::ATOMIC_LOAD_ADD:
2098 case ISD::ATOMIC_LOAD_SUB:
2099 case ISD::ATOMIC_LOAD_AND:
2100 case ISD::ATOMIC_LOAD_OR:
2101 case ISD::ATOMIC_LOAD_XOR:
2102 case ISD::ATOMIC_LOAD_NAND:
2103 case ISD::ATOMIC_LOAD_MIN:
2104 case ISD::ATOMIC_LOAD_MAX:
2105 case ISD::ATOMIC_LOAD_UMIN:
2106 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
2107 if (DCI.isBeforeLegalize())
2110 MemSDNode *MemNode = cast<MemSDNode>(N);
2111 SDValue Ptr = MemNode->getBasePtr();
2113 // TODO: We could also do this for multiplies.
2114 unsigned AS = MemNode->getAddressSpace();
2115 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
2116 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
2118 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
2120 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
2121 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
2127 return performAndCombine(N, DCI);
2129 return performOrCombine(N, DCI);
2130 case AMDGPUISD::FP_CLASS:
2131 return performClassCombine(N, DCI);
2133 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2136 /// \brief Analyze the possible immediate value Op
2138 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
2139 /// and the immediate value if it's a literal immediate
2140 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
2142 const SIInstrInfo *TII =
2143 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2145 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2146 if (TII->isInlineConstant(Node->getAPIntValue()))
2149 uint64_t Val = Node->getZExtValue();
2150 return isUInt<32>(Val) ? Val : -1;
2153 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2154 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2157 if (Node->getValueType(0) == MVT::f32)
2158 return FloatToBits(Node->getValueAPF().convertToFloat());
2166 /// \brief Helper function for adjustWritemask
2167 static unsigned SubIdx2Lane(unsigned Idx) {
2170 case AMDGPU::sub0: return 0;
2171 case AMDGPU::sub1: return 1;
2172 case AMDGPU::sub2: return 2;
2173 case AMDGPU::sub3: return 3;
2177 /// \brief Adjust the writemask of MIMG instructions
2178 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2179 SelectionDAG &DAG) const {
2180 SDNode *Users[4] = { };
2182 unsigned OldDmask = Node->getConstantOperandVal(0);
2183 unsigned NewDmask = 0;
2185 // Try to figure out the used register components
2186 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2189 // Abort if we can't understand the usage
2190 if (!I->isMachineOpcode() ||
2191 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2194 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2195 // Note that subregs are packed, i.e. Lane==0 is the first bit set
2196 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2198 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2200 // Set which texture component corresponds to the lane.
2202 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2204 Comp = countTrailingZeros(Dmask);
2205 Dmask &= ~(1 << Comp);
2208 // Abort if we have more than one user per component
2213 NewDmask |= 1 << Comp;
2216 // Abort if there's no change
2217 if (NewDmask == OldDmask)
2220 // Adjust the writemask in the node
2221 std::vector<SDValue> Ops;
2222 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2223 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2224 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2226 // If we only got one lane, replace it with a copy
2227 // (if NewDmask has only one bit set...)
2228 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2229 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2231 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2232 SDLoc(), Users[Lane]->getValueType(0),
2233 SDValue(Node, 0), RC);
2234 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2238 // Update the users of the node with the new indices
2239 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2241 SDNode *User = Users[i];
2245 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2246 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2250 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2251 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2252 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2257 static bool isFrameIndexOp(SDValue Op) {
2258 if (Op.getOpcode() == ISD::AssertZext)
2259 Op = Op.getOperand(0);
2261 return isa<FrameIndexSDNode>(Op);
2264 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2265 /// with frame index operands.
2266 /// LLVM assumes that inputs are to these instructions are registers.
2267 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2268 SelectionDAG &DAG) const {
2270 SmallVector<SDValue, 8> Ops;
2271 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2272 if (!isFrameIndexOp(Node->getOperand(i))) {
2273 Ops.push_back(Node->getOperand(i));
2278 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2279 Node->getOperand(i).getValueType(),
2280 Node->getOperand(i)), 0));
2283 DAG.UpdateNodeOperands(Node, Ops);
2286 /// \brief Fold the instructions after selecting them.
2287 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2288 SelectionDAG &DAG) const {
2289 const SIInstrInfo *TII =
2290 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2292 if (TII->isMIMG(Node->getMachineOpcode()))
2293 adjustWritemask(Node, DAG);
2295 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2296 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2297 legalizeTargetIndependentNode(Node, DAG);
2303 /// \brief Assign the register class depending on the number of
2304 /// bits set in the writemask
2305 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2306 SDNode *Node) const {
2307 const SIInstrInfo *TII =
2308 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2310 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2312 if (TII->isVOP3(MI->getOpcode())) {
2313 // Make sure constant bus requirements are respected.
2314 TII->legalizeOperandsVOP3(MRI, MI);
2318 if (TII->isMIMG(*MI)) {
2319 unsigned VReg = MI->getOperand(0).getReg();
2320 unsigned Writemask = MI->getOperand(1).getImm();
2321 unsigned BitsSet = 0;
2322 for (unsigned i = 0; i < 4; ++i)
2323 BitsSet += Writemask & (1 << i) ? 1 : 0;
2325 const TargetRegisterClass *RC;
2328 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2329 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2330 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2333 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2334 MI->setDesc(TII->get(NewOpcode));
2335 MRI.setRegClass(VReg, RC);
2339 // Replace unused atomics with the no return version.
2340 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2341 if (NoRetAtomicOp != -1) {
2342 if (!Node->hasAnyUseOfValue(0)) {
2343 MI->setDesc(TII->get(NoRetAtomicOp));
2344 MI->RemoveOperand(0);
2351 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2352 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2353 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2356 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2358 SDValue Ptr) const {
2359 const SIInstrInfo *TII =
2360 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2362 // Build the half of the subregister with the constants before building the
2363 // full 128-bit register. If we are building multiple resource descriptors,
2364 // this will allow CSEing of the 2-component register.
2365 const SDValue Ops0[] = {
2366 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2367 buildSMovImm32(DAG, DL, 0),
2368 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2369 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2370 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2373 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2374 MVT::v2i32, Ops0), 0);
2376 // Combine the constants and the pointer.
2377 const SDValue Ops1[] = {
2378 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2380 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2382 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2385 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2388 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2389 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2390 /// of the resource descriptor) to create an offset, which is added to
2391 /// the resource pointer.
2392 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2395 uint32_t RsrcDword1,
2396 uint64_t RsrcDword2And3) const {
2397 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2398 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2400 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2401 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2405 SDValue DataLo = buildSMovImm32(DAG, DL,
2406 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2407 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2409 const SDValue Ops[] = {
2410 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2412 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2414 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2416 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2418 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2421 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2424 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2425 const TargetRegisterClass *RC,
2426 unsigned Reg, EVT VT) const {
2427 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2429 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2430 cast<RegisterSDNode>(VReg)->getReg(), VT);
2433 //===----------------------------------------------------------------------===//
2434 // SI Inline Assembly Support
2435 //===----------------------------------------------------------------------===//
2437 std::pair<unsigned, const TargetRegisterClass *>
2438 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2439 StringRef Constraint,
2442 if (Constraint.size() == 1) {
2443 switch (Constraint[0]) {
2446 switch (VT.getSizeInBits()) {
2448 return std::make_pair(0U, nullptr);
2450 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2452 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2454 return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
2456 return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
2460 switch (VT.getSizeInBits()) {
2462 return std::make_pair(0U, nullptr);
2464 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
2466 return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
2468 return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
2470 return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
2472 return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
2474 return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
2479 if (Constraint.size() > 1) {
2480 const TargetRegisterClass *RC = nullptr;
2481 if (Constraint[1] == 'v') {
2482 RC = &AMDGPU::VGPR_32RegClass;
2483 } else if (Constraint[1] == 's') {
2484 RC = &AMDGPU::SGPR_32RegClass;
2489 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2490 if (!Failed && Idx < RC->getNumRegs())
2491 return std::make_pair(RC->getRegister(Idx), RC);
2494 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2497 SITargetLowering::ConstraintType
2498 SITargetLowering::getConstraintType(StringRef Constraint) const {
2499 if (Constraint.size() == 1) {
2500 switch (Constraint[0]) {
2504 return C_RegisterClass;
2507 return TargetLowering::getConstraintType(Constraint);