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 "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
38 SITargetLowering::SITargetLowering(TargetMachine &TM,
39 const AMDGPUSubtarget &STI)
40 : AMDGPUTargetLowering(TM, STI) {
41 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
42 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
44 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
45 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
47 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
48 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
50 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
51 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
52 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
54 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
55 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties(STI.getRegisterInfo());
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
71 setOperationAction(ISD::ADDC, MVT::i32, Legal);
72 setOperationAction(ISD::ADDE, MVT::i32, Legal);
73 setOperationAction(ISD::SUBC, MVT::i32, Legal);
74 setOperationAction(ISD::SUBE, MVT::i32, Legal);
76 setOperationAction(ISD::FSIN, MVT::f32, Custom);
77 setOperationAction(ISD::FCOS, MVT::f32, Custom);
79 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
80 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
82 // We need to custom lower vector stores from local memory
83 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
84 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
87 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
88 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
90 setOperationAction(ISD::STORE, MVT::i1, Custom);
91 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
93 setOperationAction(ISD::SELECT, MVT::i64, Custom);
94 setOperationAction(ISD::SELECT, MVT::f64, Promote);
95 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
97 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
98 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
99 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
100 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
102 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
103 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
105 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
107 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
108 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
109 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
122 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
123 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
124 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
127 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
128 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
130 for (MVT VT : MVT::integer_valuetypes()) {
134 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
135 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
139 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
140 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
144 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
145 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
150 for (MVT VT : MVT::integer_vector_valuetypes()) {
151 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
152 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
155 for (MVT VT : MVT::fp_valuetypes())
156 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
158 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
159 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
160 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
161 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
163 setOperationAction(ISD::LOAD, MVT::i1, Custom);
165 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
166 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
167 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
169 // These should use UDIVREM, so set them to expand
170 setOperationAction(ISD::UDIV, MVT::i64, Expand);
171 setOperationAction(ISD::UREM, MVT::i64, Expand);
173 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
174 setOperationAction(ISD::SELECT, MVT::i1, Promote);
176 // We only support LOAD/STORE and vector manipulation ops for vectors
177 // with > 4 elements.
178 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}) {
179 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
183 case ISD::BUILD_VECTOR:
185 case ISD::EXTRACT_VECTOR_ELT:
186 case ISD::INSERT_VECTOR_ELT:
187 case ISD::INSERT_SUBVECTOR:
188 case ISD::EXTRACT_SUBVECTOR:
190 case ISD::CONCAT_VECTORS:
191 setOperationAction(Op, VT, Custom);
194 setOperationAction(Op, VT, Expand);
200 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
201 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
202 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
203 setOperationAction(ISD::FRINT, MVT::f64, Legal);
206 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
207 setOperationAction(ISD::FDIV, MVT::f32, Custom);
208 setOperationAction(ISD::FDIV, MVT::f64, Custom);
210 setTargetDAGCombine(ISD::FADD);
211 setTargetDAGCombine(ISD::FSUB);
212 setTargetDAGCombine(ISD::FMINNUM);
213 setTargetDAGCombine(ISD::FMAXNUM);
214 setTargetDAGCombine(ISD::SMIN);
215 setTargetDAGCombine(ISD::SMAX);
216 setTargetDAGCombine(ISD::UMIN);
217 setTargetDAGCombine(ISD::UMAX);
218 setTargetDAGCombine(ISD::SELECT_CC);
219 setTargetDAGCombine(ISD::SETCC);
220 setTargetDAGCombine(ISD::AND);
221 setTargetDAGCombine(ISD::OR);
222 setTargetDAGCombine(ISD::UINT_TO_FP);
224 // All memory operations. Some folding on the pointer operand is done to help
225 // matching the constant offsets in the addressing modes.
226 setTargetDAGCombine(ISD::LOAD);
227 setTargetDAGCombine(ISD::STORE);
228 setTargetDAGCombine(ISD::ATOMIC_LOAD);
229 setTargetDAGCombine(ISD::ATOMIC_STORE);
230 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
231 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
232 setTargetDAGCombine(ISD::ATOMIC_SWAP);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
244 setSchedulingPreference(Sched::RegPressure);
247 //===----------------------------------------------------------------------===//
248 // TargetLowering queries
249 //===----------------------------------------------------------------------===//
251 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
253 // SI has some legal vector types, but no legal vector operations. Say no
254 // shuffles are legal in order to prefer scalarizing some vector operations.
258 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
259 // Flat instructions do not have offsets, and only have the register
261 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
264 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
265 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
266 // additionally can do r + r + i with addr64. 32-bit has more addressing
267 // mode options. Depending on the resource constant, it can also do
268 // (i64 r0) + (i32 r1) * (i14 i).
270 // Private arrays end up using a scratch buffer most of the time, so also
271 // assume those use MUBUF instructions. Scratch loads / stores are currently
272 // implemented as mubuf instructions with offen bit set, so slightly
273 // different than the normal addr64.
274 if (!isUInt<12>(AM.BaseOffs))
277 // FIXME: Since we can split immediate into soffset and immediate offset,
278 // would it make sense to allow any immediate?
281 case 0: // r + i or just i, depending on HasBaseReg.
284 return true; // We have r + r or r + i.
291 // Allow 2 * r as r + r
292 // Or 2 * r + i is allowed as r + r + i.
294 default: // Don't allow n * r
299 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
300 const AddrMode &AM, Type *Ty,
302 // No global is ever allowed as a base.
307 case AMDGPUAS::GLOBAL_ADDRESS: {
308 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
309 // Assume the we will use FLAT for all global memory accesses
311 // FIXME: This assumption is currently wrong. On VI we still use
312 // MUBUF instructions for the r + i addressing mode. As currently
313 // implemented, the MUBUF instructions only work on buffer < 4GB.
314 // It may be possible to support > 4GB buffers with MUBUF instructions,
315 // by setting the stride value in the resource descriptor which would
316 // increase the size limit to (stride * 4GB). However, this is risky,
317 // because it has never been validated.
318 return isLegalFlatAddressingMode(AM);
321 return isLegalMUBUFAddressingMode(AM);
323 case AMDGPUAS::CONSTANT_ADDRESS: {
324 // If the offset isn't a multiple of 4, it probably isn't going to be
325 // correctly aligned.
326 if (AM.BaseOffs % 4 != 0)
327 return isLegalMUBUFAddressingMode(AM);
329 // There are no SMRD extloads, so if we have to do a small type access we
330 // will use a MUBUF load.
331 // FIXME?: We also need to do this if unaligned, but we don't know the
333 if (DL.getTypeStoreSize(Ty) < 4)
334 return isLegalMUBUFAddressingMode(AM);
336 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
337 // SMRD instructions have an 8-bit, dword offset on SI.
338 if (!isUInt<8>(AM.BaseOffs / 4))
340 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
341 // On CI+, this can also be a 32-bit literal constant offset. If it fits
342 // in 8-bits, it can use a smaller encoding.
343 if (!isUInt<32>(AM.BaseOffs / 4))
345 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
346 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
347 if (!isUInt<20>(AM.BaseOffs))
350 llvm_unreachable("unhandled generation");
352 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
355 if (AM.Scale == 1 && AM.HasBaseReg)
361 case AMDGPUAS::PRIVATE_ADDRESS:
362 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
363 return isLegalMUBUFAddressingMode(AM);
365 case AMDGPUAS::LOCAL_ADDRESS:
366 case AMDGPUAS::REGION_ADDRESS: {
367 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
369 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
370 // an 8-bit dword offset but we don't know the alignment here.
371 if (!isUInt<16>(AM.BaseOffs))
374 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
377 if (AM.Scale == 1 && AM.HasBaseReg)
382 case AMDGPUAS::FLAT_ADDRESS:
383 return isLegalFlatAddressingMode(AM);
386 llvm_unreachable("unhandled address space");
390 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
393 bool *IsFast) const {
397 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
398 // which isn't a simple VT.
399 if (!VT.isSimple() || VT == MVT::Other)
402 // TODO - CI+ supports unaligned memory accesses, but this requires driver
405 // XXX - The only mention I see of this in the ISA manual is for LDS direct
406 // reads the "byte address and must be dword aligned". Is it also true for the
407 // normal loads and stores?
408 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
409 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
410 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
411 // with adjacent offsets.
412 bool AlignedBy4 = (Align % 4 == 0);
414 *IsFast = AlignedBy4;
418 // Smaller than dword value must be aligned.
419 // FIXME: This should be allowed on CI+
420 if (VT.bitsLT(MVT::i32))
423 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
424 // byte-address are ignored, thus forcing Dword alignment.
425 // This applies to private, global, and constant memory.
429 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
432 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
433 unsigned SrcAlign, bool IsMemset,
436 MachineFunction &MF) const {
437 // FIXME: Should account for address space here.
439 // The default fallback uses the private pointer size as a guess for a type to
440 // use. Make sure we switch these to 64-bit accesses.
442 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
445 if (Size >= 8 && DstAlign >= 4)
452 TargetLoweringBase::LegalizeTypeAction
453 SITargetLowering::getPreferredVectorAction(EVT VT) const {
454 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
455 return TypeSplitVector;
457 return TargetLoweringBase::getPreferredVectorAction(VT);
460 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
462 const SIInstrInfo *TII =
463 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
464 return TII->isInlineConstant(Imm);
467 static EVT toIntegerVT(EVT VT) {
469 return VT.changeVectorElementTypeToInteger();
470 return MVT::getIntegerVT(VT.getSizeInBits());
473 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
474 SDLoc SL, SDValue Chain,
475 unsigned Offset, bool Signed) const {
476 const DataLayout &DL = DAG.getDataLayout();
477 MachineFunction &MF = DAG.getMachineFunction();
478 const SIRegisterInfo *TRI =
479 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
480 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
482 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
484 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
485 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
486 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
487 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
488 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
489 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
490 DAG.getConstant(Offset, SL, PtrVT));
491 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
492 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
494 unsigned Align = DL.getABITypeAlignment(Ty);
496 if (VT != MemVT && VT.isFloatingPoint()) {
497 // Do an integer load and convert.
498 // FIXME: This is mostly because load legalization after type legalization
499 // doesn't handle FP extloads.
500 assert(VT.getScalarType() == MVT::f32 &&
501 MemVT.getScalarType() == MVT::f16);
503 EVT IVT = toIntegerVT(VT);
504 EVT MemIVT = toIntegerVT(MemVT);
505 SDValue Load = DAG.getLoad(ISD::UNINDEXED, ISD::ZEXTLOAD,
506 IVT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemIVT,
508 true, // isNonTemporal
512 DAG.getNode(ISD::FP16_TO_FP, SL, VT, Load),
516 return DAG.getMergeValues(Ops, SL);
519 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
520 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
521 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
523 true, // isNonTemporal
528 SDValue SITargetLowering::LowerFormalArguments(
529 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
530 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
531 SmallVectorImpl<SDValue> &InVals) const {
532 const SIRegisterInfo *TRI =
533 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
535 MachineFunction &MF = DAG.getMachineFunction();
536 FunctionType *FType = MF.getFunction()->getFunctionType();
537 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
539 assert(CallConv == CallingConv::C);
541 SmallVector<ISD::InputArg, 16> Splits;
542 BitVector Skipped(Ins.size());
544 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
545 const ISD::InputArg &Arg = Ins[i];
547 // First check if it's a PS input addr
548 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
549 !Arg.Flags.isByVal()) {
551 assert((PSInputNum <= 15) && "Too many PS inputs!");
554 // We can safely skip PS inputs
560 Info->PSInputAddr |= 1 << PSInputNum++;
563 // Second split vertices into their elements
564 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
565 ISD::InputArg NewArg = Arg;
566 NewArg.Flags.setSplit();
567 NewArg.VT = Arg.VT.getVectorElementType();
569 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
570 // three or five element vertex only needs three or five registers,
571 // NOT four or eight.
572 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
573 unsigned NumElements = ParamType->getVectorNumElements();
575 for (unsigned j = 0; j != NumElements; ++j) {
576 Splits.push_back(NewArg);
577 NewArg.PartOffset += NewArg.VT.getStoreSize();
580 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
581 Splits.push_back(Arg);
585 SmallVector<CCValAssign, 16> ArgLocs;
586 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
589 // At least one interpolation mode must be enabled or else the GPU will hang.
590 if (Info->getShaderType() == ShaderType::PIXEL &&
591 (Info->PSInputAddr & 0x7F) == 0) {
592 Info->PSInputAddr |= 1;
593 CCInfo.AllocateReg(AMDGPU::VGPR0);
594 CCInfo.AllocateReg(AMDGPU::VGPR1);
597 // The pointer to the list of arguments is stored in SGPR0, SGPR1
598 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
599 if (Info->getShaderType() == ShaderType::COMPUTE) {
600 if (Subtarget->isAmdHsaOS())
601 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
603 Info->NumUserSGPRs = 4;
605 unsigned InputPtrReg =
606 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
607 unsigned InputPtrRegLo =
608 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
609 unsigned InputPtrRegHi =
610 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
612 unsigned ScratchPtrReg =
613 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
614 unsigned ScratchPtrRegLo =
615 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
616 unsigned ScratchPtrRegHi =
617 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
619 CCInfo.AllocateReg(InputPtrRegLo);
620 CCInfo.AllocateReg(InputPtrRegHi);
621 CCInfo.AllocateReg(ScratchPtrRegLo);
622 CCInfo.AllocateReg(ScratchPtrRegHi);
623 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
624 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
627 if (Info->getShaderType() == ShaderType::COMPUTE) {
628 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
632 AnalyzeFormalArguments(CCInfo, Splits);
634 SmallVector<SDValue, 16> Chains;
636 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
638 const ISD::InputArg &Arg = Ins[i];
640 InVals.push_back(DAG.getUNDEF(Arg.VT));
644 CCValAssign &VA = ArgLocs[ArgIdx++];
645 MVT VT = VA.getLocVT();
649 EVT MemVT = Splits[i].VT;
650 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
651 VA.getLocMemOffset();
652 // The first 36 bytes of the input buffer contains information about
653 // thread group and global sizes.
654 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
655 Offset, Ins[i].Flags.isSExt());
656 Chains.push_back(Arg.getValue(1));
659 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
660 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
661 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
662 // On SI local pointers are just offsets into LDS, so they are always
663 // less than 16-bits. On CI and newer they could potentially be
664 // real pointers, so we can't guarantee their size.
665 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
666 DAG.getValueType(MVT::i16));
669 InVals.push_back(Arg);
670 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
673 assert(VA.isRegLoc() && "Parameter must be in a register!");
675 unsigned Reg = VA.getLocReg();
677 if (VT == MVT::i64) {
678 // For now assume it is a pointer
679 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
680 &AMDGPU::SReg_64RegClass);
681 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
682 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
683 InVals.push_back(Copy);
687 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
689 Reg = MF.addLiveIn(Reg, RC);
690 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
692 if (Arg.VT.isVector()) {
694 // Build a vector from the registers
695 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
696 unsigned NumElements = ParamType->getVectorNumElements();
698 SmallVector<SDValue, 4> Regs;
700 for (unsigned j = 1; j != NumElements; ++j) {
701 Reg = ArgLocs[ArgIdx++].getLocReg();
702 Reg = MF.addLiveIn(Reg, RC);
704 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
705 Regs.push_back(Copy);
708 // Fill up the missing vector elements
709 NumElements = Arg.VT.getVectorNumElements() - NumElements;
710 Regs.append(NumElements, DAG.getUNDEF(VT));
712 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
716 InVals.push_back(Val);
719 if (Info->getShaderType() != ShaderType::COMPUTE) {
720 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
721 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
722 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
728 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
731 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
732 MachineInstr * MI, MachineBasicBlock * BB) const {
734 MachineBasicBlock::iterator I = *MI;
735 const SIInstrInfo *TII =
736 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
738 switch (MI->getOpcode()) {
740 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
743 case AMDGPU::SI_RegisterStorePseudo: {
744 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
745 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
746 MachineInstrBuilder MIB =
747 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
749 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
750 MIB.addOperand(MI->getOperand(i));
752 MI->eraseFromParent();
759 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
760 // This currently forces unfolding various combinations of fsub into fma with
761 // free fneg'd operands. As long as we have fast FMA (controlled by
762 // isFMAFasterThanFMulAndFAdd), we should perform these.
764 // When fma is quarter rate, for f64 where add / sub are at best half rate,
765 // most of these combines appear to be cycle neutral but save on instruction
766 // count / code size.
770 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
772 if (!VT.isVector()) {
775 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
778 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
782 // Answering this is somewhat tricky and depends on the specific device which
783 // have different rates for fma or all f64 operations.
785 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
786 // regardless of which device (although the number of cycles differs between
787 // devices), so it is always profitable for f64.
789 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
790 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
791 // which we can always do even without fused FP ops since it returns the same
792 // result as the separate operations and since it is always full
793 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
794 // however does not support denormals, so we do report fma as faster if we have
795 // a fast fma device and require denormals.
797 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
798 VT = VT.getScalarType();
803 switch (VT.getSimpleVT().SimpleTy) {
805 // This is as fast on some subtargets. However, we always have full rate f32
806 // mad available which returns the same result as the separate operations
807 // which we should prefer over fma. We can't use this if we want to support
808 // denormals, so only report this in these cases.
809 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
819 //===----------------------------------------------------------------------===//
820 // Custom DAG Lowering Operations
821 //===----------------------------------------------------------------------===//
823 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
824 switch (Op.getOpcode()) {
825 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
826 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
827 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
829 SDValue Result = LowerLOAD(Op, DAG);
830 assert((!Result.getNode() ||
831 Result.getNode()->getNumValues() == 2) &&
832 "Load should return a value and a chain");
838 return LowerTrig(Op, DAG);
839 case ISD::SELECT: return LowerSELECT(Op, DAG);
840 case ISD::FDIV: return LowerFDIV(Op, DAG);
841 case ISD::STORE: return LowerSTORE(Op, DAG);
842 case ISD::GlobalAddress: {
843 MachineFunction &MF = DAG.getMachineFunction();
844 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
845 return LowerGlobalAddress(MFI, Op, DAG);
847 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
848 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
853 /// \brief Helper function for LowerBRCOND
854 static SDNode *findUser(SDValue Value, unsigned Opcode) {
856 SDNode *Parent = Value.getNode();
857 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
860 if (I.getUse().get() != Value)
863 if (I->getOpcode() == Opcode)
869 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
872 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
873 unsigned FrameIndex = FINode->getIndex();
875 // A FrameIndex node represents a 32-bit offset into scratch memory. If
876 // the high bit of a frame index offset were to be set, this would mean
877 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
878 // scratch buffer, with 64 being the number of threads per wave.
880 // If we know the machine uses less than 128GB of scratch, then we can
881 // amrk the high bit of the FrameIndex node as known zero,
882 // which is important, because it means in most situations we can
883 // prove that values derived from FrameIndex nodes are non-negative.
884 // This enables us to take advantage of more addressing modes when
885 // accessing scratch buffers, since for scratch reads/writes, the register
886 // offset must always be positive.
888 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
889 if (Subtarget->enableHugeScratchBuffer())
892 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
893 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
896 /// This transforms the control flow intrinsics to get the branch destination as
897 /// last parameter, also switches branch target with BR if the need arise
898 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
899 SelectionDAG &DAG) const {
903 SDNode *Intr = BRCOND.getOperand(1).getNode();
904 SDValue Target = BRCOND.getOperand(2);
905 SDNode *BR = nullptr;
907 if (Intr->getOpcode() == ISD::SETCC) {
908 // As long as we negate the condition everything is fine
909 SDNode *SetCC = Intr;
910 assert(SetCC->getConstantOperandVal(1) == 1);
911 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
913 Intr = SetCC->getOperand(0).getNode();
916 // Get the target from BR if we don't negate the condition
917 BR = findUser(BRCOND, ISD::BR);
918 Target = BR->getOperand(1);
921 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
923 // Build the result and
924 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
926 // operands of the new intrinsic call
927 SmallVector<SDValue, 4> Ops;
928 Ops.push_back(BRCOND.getOperand(0));
929 Ops.append(Intr->op_begin() + 1, Intr->op_end());
930 Ops.push_back(Target);
932 // build the new intrinsic call
933 SDNode *Result = DAG.getNode(
934 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
935 DAG.getVTList(Res), Ops).getNode();
938 // Give the branch instruction our target
943 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
944 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
945 BR = NewBR.getNode();
948 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
950 // Copy the intrinsic results to registers
951 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
952 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
956 Chain = DAG.getCopyToReg(
958 CopyToReg->getOperand(1),
959 SDValue(Result, i - 1),
962 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
965 // Remove the old intrinsic from the chain
966 DAG.ReplaceAllUsesOfValueWith(
967 SDValue(Intr, Intr->getNumValues() - 1),
968 Intr->getOperand(0));
973 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
975 SelectionDAG &DAG) const {
976 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
978 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
979 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
982 const GlobalValue *GV = GSD->getGlobal();
983 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
985 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
986 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
988 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
989 DAG.getConstant(0, DL, MVT::i32));
990 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
991 DAG.getConstant(1, DL, MVT::i32));
993 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
995 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
996 PtrHi, DAG.getConstant(0, DL, MVT::i32),
997 SDValue(Lo.getNode(), 1));
998 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
1001 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1003 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1004 // so we will end up with redundant moves to m0.
1006 // We can't use S_MOV_B32, because there is no way to specify m0 as the
1007 // destination register.
1009 // We have to use them both. Machine cse will combine all the S_MOV_B32
1010 // instructions and the register coalescer eliminate the extra copies.
1011 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1012 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1013 SDValue(M0, 0), SDValue()); // Glue
1014 // A Null SDValue creates
1018 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1019 SelectionDAG &DAG) const {
1020 MachineFunction &MF = DAG.getMachineFunction();
1021 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1022 const SIRegisterInfo *TRI =
1023 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1025 EVT VT = Op.getValueType();
1027 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1029 switch (IntrinsicID) {
1030 case Intrinsic::r600_read_ngroups_x:
1031 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1032 SI::KernelInputOffsets::NGROUPS_X, false);
1033 case Intrinsic::r600_read_ngroups_y:
1034 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1035 SI::KernelInputOffsets::NGROUPS_Y, false);
1036 case Intrinsic::r600_read_ngroups_z:
1037 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1038 SI::KernelInputOffsets::NGROUPS_Z, false);
1039 case Intrinsic::r600_read_global_size_x:
1040 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1041 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1042 case Intrinsic::r600_read_global_size_y:
1043 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1044 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1045 case Intrinsic::r600_read_global_size_z:
1046 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1047 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1048 case Intrinsic::r600_read_local_size_x:
1049 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1050 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
1051 case Intrinsic::r600_read_local_size_y:
1052 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1053 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
1054 case Intrinsic::r600_read_local_size_z:
1055 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1056 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
1058 case Intrinsic::AMDGPU_read_workdim:
1059 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1060 getImplicitParameterOffset(MFI, GRID_DIM), false);
1062 case Intrinsic::r600_read_tgid_x:
1063 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1064 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
1065 case Intrinsic::r600_read_tgid_y:
1066 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1067 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
1068 case Intrinsic::r600_read_tgid_z:
1069 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1070 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
1071 case Intrinsic::r600_read_tidig_x:
1072 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1073 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
1074 case Intrinsic::r600_read_tidig_y:
1075 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1076 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
1077 case Intrinsic::r600_read_tidig_z:
1078 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1079 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
1080 case AMDGPUIntrinsic::SI_load_const: {
1086 MachineMemOperand *MMO = MF.getMachineMemOperand(
1087 MachinePointerInfo(),
1088 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1089 VT.getStoreSize(), 4);
1090 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1091 Op->getVTList(), Ops, VT, MMO);
1093 case AMDGPUIntrinsic::SI_sample:
1094 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1095 case AMDGPUIntrinsic::SI_sampleb:
1096 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1097 case AMDGPUIntrinsic::SI_sampled:
1098 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1099 case AMDGPUIntrinsic::SI_samplel:
1100 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1101 case AMDGPUIntrinsic::SI_vs_load_input:
1102 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1107 case AMDGPUIntrinsic::AMDGPU_fract:
1108 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1109 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1110 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1111 case AMDGPUIntrinsic::SI_fs_constant: {
1112 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1113 SDValue Glue = M0.getValue(1);
1114 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1115 DAG.getConstant(2, DL, MVT::i32), // P0
1116 Op.getOperand(1), Op.getOperand(2), Glue);
1118 case AMDGPUIntrinsic::SI_fs_interp: {
1119 SDValue IJ = Op.getOperand(4);
1120 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1121 DAG.getConstant(0, DL, MVT::i32));
1122 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1123 DAG.getConstant(1, DL, MVT::i32));
1124 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1125 SDValue Glue = M0.getValue(1);
1126 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1127 DAG.getVTList(MVT::f32, MVT::Glue),
1128 I, Op.getOperand(1), Op.getOperand(2), Glue);
1129 Glue = SDValue(P1.getNode(), 1);
1130 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1131 Op.getOperand(1), Op.getOperand(2), Glue);
1134 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1138 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1139 SelectionDAG &DAG) const {
1140 MachineFunction &MF = DAG.getMachineFunction();
1142 SDValue Chain = Op.getOperand(0);
1143 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1145 switch (IntrinsicID) {
1146 case AMDGPUIntrinsic::SI_sendmsg: {
1147 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1148 SDValue Glue = Chain.getValue(1);
1149 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1150 Op.getOperand(2), Glue);
1152 case AMDGPUIntrinsic::SI_tbuffer_store: {
1170 EVT VT = Op.getOperand(3).getValueType();
1172 MachineMemOperand *MMO = MF.getMachineMemOperand(
1173 MachinePointerInfo(),
1174 MachineMemOperand::MOStore,
1175 VT.getStoreSize(), 4);
1176 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1177 Op->getVTList(), Ops, VT, MMO);
1184 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1186 LoadSDNode *Load = cast<LoadSDNode>(Op);
1188 if (Op.getValueType().isVector()) {
1189 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1190 "Custom lowering for non-i32 vectors hasn't been implemented.");
1191 unsigned NumElements = Op.getValueType().getVectorNumElements();
1192 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1193 switch (Load->getAddressSpace()) {
1195 case AMDGPUAS::GLOBAL_ADDRESS:
1196 case AMDGPUAS::PRIVATE_ADDRESS:
1197 // v4 loads are supported for private and global memory.
1198 if (NumElements <= 4)
1201 case AMDGPUAS::LOCAL_ADDRESS:
1202 return ScalarizeVectorLoad(Op, DAG);
1206 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1209 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1211 SelectionDAG &DAG) const {
1212 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1218 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1219 if (Op.getValueType() != MVT::i64)
1223 SDValue Cond = Op.getOperand(0);
1225 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1226 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1228 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1229 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1231 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1232 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1234 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1236 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1237 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1239 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1241 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1242 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1245 // Catch division cases where we can use shortcuts with rcp and rsq
1247 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1249 SDValue LHS = Op.getOperand(0);
1250 SDValue RHS = Op.getOperand(1);
1251 EVT VT = Op.getValueType();
1252 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1254 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1255 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1256 CLHS->isExactlyValue(1.0)) {
1257 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1258 // the CI documentation has a worst case error of 1 ulp.
1259 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1260 // use it as long as we aren't trying to use denormals.
1262 // 1.0 / sqrt(x) -> rsq(x)
1264 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1265 // error seems really high at 2^29 ULP.
1266 if (RHS.getOpcode() == ISD::FSQRT)
1267 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1269 // 1.0 / x -> rcp(x)
1270 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1275 // Turn into multiply by the reciprocal.
1276 // x / y -> x * (1.0 / y)
1277 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1278 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1284 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1285 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1286 if (FastLowered.getNode())
1289 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1290 // selection error for now rather than do something incorrect.
1291 if (Subtarget->hasFP32Denormals())
1295 SDValue LHS = Op.getOperand(0);
1296 SDValue RHS = Op.getOperand(1);
1298 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1300 const APFloat K0Val(BitsToFloat(0x6f800000));
1301 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1303 const APFloat K1Val(BitsToFloat(0x2f800000));
1304 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1306 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1309 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1311 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1313 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1315 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1317 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1319 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1321 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1324 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1325 if (DAG.getTarget().Options.UnsafeFPMath)
1326 return LowerFastFDIV(Op, DAG);
1329 SDValue X = Op.getOperand(0);
1330 SDValue Y = Op.getOperand(1);
1332 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1334 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1336 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1338 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1340 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1342 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1344 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1346 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1348 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1350 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1351 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1353 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1354 NegDivScale0, Mul, DivScale1);
1358 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1359 // Workaround a hardware bug on SI where the condition output from div_scale
1362 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1364 // Figure out if the scale to use for div_fmas.
1365 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1366 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1367 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1368 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1370 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1371 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1374 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1376 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1378 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1379 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1380 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1382 Scale = DivScale1.getValue(1);
1385 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1386 Fma4, Fma3, Mul, Scale);
1388 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1391 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1392 EVT VT = Op.getValueType();
1395 return LowerFDIV32(Op, DAG);
1398 return LowerFDIV64(Op, DAG);
1400 llvm_unreachable("Unexpected type for fdiv");
1403 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1405 StoreSDNode *Store = cast<StoreSDNode>(Op);
1406 EVT VT = Store->getMemoryVT();
1408 // These stores are legal.
1409 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1410 if (VT.isVector() && VT.getVectorNumElements() > 4)
1411 return ScalarizeVectorStore(Op, DAG);
1415 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1419 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1420 return ScalarizeVectorStore(Op, DAG);
1423 return DAG.getTruncStore(Store->getChain(), DL,
1424 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1425 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1430 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1432 EVT VT = Op.getValueType();
1433 SDValue Arg = Op.getOperand(0);
1434 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1435 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1436 DAG.getConstantFP(0.5/M_PI, DL,
1439 switch (Op.getOpcode()) {
1441 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1443 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1445 llvm_unreachable("Wrong trig opcode");
1449 //===----------------------------------------------------------------------===//
1450 // Custom DAG optimizations
1451 //===----------------------------------------------------------------------===//
1453 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1454 DAGCombinerInfo &DCI) const {
1455 EVT VT = N->getValueType(0);
1456 EVT ScalarVT = VT.getScalarType();
1457 if (ScalarVT != MVT::f32)
1460 SelectionDAG &DAG = DCI.DAG;
1463 SDValue Src = N->getOperand(0);
1464 EVT SrcVT = Src.getValueType();
1466 // TODO: We could try to match extracting the higher bytes, which would be
1467 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1468 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1469 // about in practice.
1470 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1471 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1472 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1473 DCI.AddToWorklist(Cvt.getNode());
1478 // We are primarily trying to catch operations on illegal vector types
1479 // before they are expanded.
1480 // For scalars, we can use the more flexible method of checking masked bits
1481 // after legalization.
1482 if (!DCI.isBeforeLegalize() ||
1483 !SrcVT.isVector() ||
1484 SrcVT.getVectorElementType() != MVT::i8) {
1488 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1490 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1492 unsigned NElts = SrcVT.getVectorNumElements();
1493 if (!SrcVT.isSimple() && NElts != 3)
1496 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1497 // prevent a mess from expanding to v4i32 and repacking.
1498 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1499 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1500 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1501 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1502 LoadSDNode *Load = cast<LoadSDNode>(Src);
1504 unsigned AS = Load->getAddressSpace();
1505 unsigned Align = Load->getAlignment();
1506 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1507 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1509 // Don't try to replace the load if we have to expand it due to alignment
1510 // problems. Otherwise we will end up scalarizing the load, and trying to
1511 // repack into the vector for no real reason.
1512 if (Align < ABIAlignment &&
1513 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1517 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1521 Load->getMemOperand());
1523 // Make sure successors of the original load stay after it by updating
1524 // them to use the new Chain.
1525 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1527 SmallVector<SDValue, 4> Elts;
1528 if (RegVT.isVector())
1529 DAG.ExtractVectorElements(NewLoad, Elts);
1531 Elts.push_back(NewLoad);
1533 SmallVector<SDValue, 4> Ops;
1535 unsigned EltIdx = 0;
1536 for (SDValue Elt : Elts) {
1537 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1538 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1539 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1540 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1541 DCI.AddToWorklist(Cvt.getNode());
1548 assert(Ops.size() == NElts);
1550 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1556 /// \brief Return true if the given offset Size in bytes can be folded into
1557 /// the immediate offsets of a memory instruction for the given address space.
1558 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1559 const AMDGPUSubtarget &STI) {
1561 case AMDGPUAS::GLOBAL_ADDRESS: {
1562 // MUBUF instructions a 12-bit offset in bytes.
1563 return isUInt<12>(OffsetSize);
1565 case AMDGPUAS::CONSTANT_ADDRESS: {
1566 // SMRD instructions have an 8-bit offset in dwords on SI and
1567 // a 20-bit offset in bytes on VI.
1568 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1569 return isUInt<20>(OffsetSize);
1571 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1573 case AMDGPUAS::LOCAL_ADDRESS:
1574 case AMDGPUAS::REGION_ADDRESS: {
1575 // The single offset versions have a 16-bit offset in bytes.
1576 return isUInt<16>(OffsetSize);
1578 case AMDGPUAS::PRIVATE_ADDRESS:
1579 // Indirect register addressing does not use any offsets.
1585 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1587 // This is a variant of
1588 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1590 // The normal DAG combiner will do this, but only if the add has one use since
1591 // that would increase the number of instructions.
1593 // This prevents us from seeing a constant offset that can be folded into a
1594 // memory instruction's addressing mode. If we know the resulting add offset of
1595 // a pointer can be folded into an addressing offset, we can replace the pointer
1596 // operand with the add of new constant offset. This eliminates one of the uses,
1597 // and may allow the remaining use to also be simplified.
1599 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1601 DAGCombinerInfo &DCI) const {
1602 SDValue N0 = N->getOperand(0);
1603 SDValue N1 = N->getOperand(1);
1605 if (N0.getOpcode() != ISD::ADD)
1608 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1612 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1616 // If the resulting offset is too large, we can't fold it into the addressing
1618 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1619 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1622 SelectionDAG &DAG = DCI.DAG;
1624 EVT VT = N->getValueType(0);
1626 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1627 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1629 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1632 SDValue SITargetLowering::performAndCombine(SDNode *N,
1633 DAGCombinerInfo &DCI) const {
1634 if (DCI.isBeforeLegalize())
1637 SelectionDAG &DAG = DCI.DAG;
1639 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1640 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1641 SDValue LHS = N->getOperand(0);
1642 SDValue RHS = N->getOperand(1);
1644 if (LHS.getOpcode() == ISD::SETCC &&
1645 RHS.getOpcode() == ISD::SETCC) {
1646 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1647 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1649 SDValue X = LHS.getOperand(0);
1650 SDValue Y = RHS.getOperand(0);
1651 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1654 if (LCC == ISD::SETO) {
1655 if (X != LHS.getOperand(1))
1658 if (RCC == ISD::SETUNE) {
1659 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1660 if (!C1 || !C1->isInfinity() || C1->isNegative())
1663 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1664 SIInstrFlags::N_SUBNORMAL |
1665 SIInstrFlags::N_ZERO |
1666 SIInstrFlags::P_ZERO |
1667 SIInstrFlags::P_SUBNORMAL |
1668 SIInstrFlags::P_NORMAL;
1670 static_assert(((~(SIInstrFlags::S_NAN |
1671 SIInstrFlags::Q_NAN |
1672 SIInstrFlags::N_INFINITY |
1673 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1677 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1678 X, DAG.getConstant(Mask, DL, MVT::i32));
1686 SDValue SITargetLowering::performOrCombine(SDNode *N,
1687 DAGCombinerInfo &DCI) const {
1688 SelectionDAG &DAG = DCI.DAG;
1689 SDValue LHS = N->getOperand(0);
1690 SDValue RHS = N->getOperand(1);
1692 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1693 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1694 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1695 SDValue Src = LHS.getOperand(0);
1696 if (Src != RHS.getOperand(0))
1699 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1700 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1704 // Only 10 bits are used.
1705 static const uint32_t MaxMask = 0x3ff;
1707 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1709 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1710 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1716 SDValue SITargetLowering::performClassCombine(SDNode *N,
1717 DAGCombinerInfo &DCI) const {
1718 SelectionDAG &DAG = DCI.DAG;
1719 SDValue Mask = N->getOperand(1);
1721 // fp_class x, 0 -> false
1722 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1723 if (CMask->isNullValue())
1724 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1730 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1733 return AMDGPUISD::FMAX3;
1735 return AMDGPUISD::SMAX3;
1737 return AMDGPUISD::UMAX3;
1739 return AMDGPUISD::FMIN3;
1741 return AMDGPUISD::SMIN3;
1743 return AMDGPUISD::UMIN3;
1745 llvm_unreachable("Not a min/max opcode");
1749 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1750 DAGCombinerInfo &DCI) const {
1751 SelectionDAG &DAG = DCI.DAG;
1753 unsigned Opc = N->getOpcode();
1754 SDValue Op0 = N->getOperand(0);
1755 SDValue Op1 = N->getOperand(1);
1757 // Only do this if the inner op has one use since this will just increases
1758 // register pressure for no benefit.
1760 // max(max(a, b), c)
1761 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1763 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1771 // max(a, max(b, c))
1772 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1774 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1785 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1786 DAGCombinerInfo &DCI) const {
1787 SelectionDAG &DAG = DCI.DAG;
1790 SDValue LHS = N->getOperand(0);
1791 SDValue RHS = N->getOperand(1);
1792 EVT VT = LHS.getValueType();
1794 if (VT != MVT::f32 && VT != MVT::f64)
1797 // Match isinf pattern
1798 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1799 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1800 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1801 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1805 const APFloat &APF = CRHS->getValueAPF();
1806 if (APF.isInfinity() && !APF.isNegative()) {
1807 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1808 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1809 DAG.getConstant(Mask, SL, MVT::i32));
1816 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1817 DAGCombinerInfo &DCI) const {
1818 SelectionDAG &DAG = DCI.DAG;
1821 switch (N->getOpcode()) {
1823 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1825 return performSetCCCombine(N, DCI);
1826 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1832 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1833 N->getValueType(0) != MVT::f64 &&
1834 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1835 return performMin3Max3Combine(N, DCI);
1839 case AMDGPUISD::CVT_F32_UBYTE0:
1840 case AMDGPUISD::CVT_F32_UBYTE1:
1841 case AMDGPUISD::CVT_F32_UBYTE2:
1842 case AMDGPUISD::CVT_F32_UBYTE3: {
1843 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1845 SDValue Src = N->getOperand(0);
1846 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1848 APInt KnownZero, KnownOne;
1849 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1850 !DCI.isBeforeLegalizeOps());
1851 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1852 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1853 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1854 DCI.CommitTargetLoweringOpt(TLO);
1860 case ISD::UINT_TO_FP: {
1861 return performUCharToFloatCombine(N, DCI);
1864 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1867 EVT VT = N->getValueType(0);
1871 // Only do this if we are not trying to support denormals. v_mad_f32 does
1872 // not support denormals ever.
1873 if (Subtarget->hasFP32Denormals())
1876 SDValue LHS = N->getOperand(0);
1877 SDValue RHS = N->getOperand(1);
1879 // These should really be instruction patterns, but writing patterns with
1880 // source modiifiers is a pain.
1882 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1883 if (LHS.getOpcode() == ISD::FADD) {
1884 SDValue A = LHS.getOperand(0);
1885 if (A == LHS.getOperand(1)) {
1886 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1887 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1891 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1892 if (RHS.getOpcode() == ISD::FADD) {
1893 SDValue A = RHS.getOperand(0);
1894 if (A == RHS.getOperand(1)) {
1895 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1896 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1903 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1906 EVT VT = N->getValueType(0);
1908 // Try to get the fneg to fold into the source modifier. This undoes generic
1909 // DAG combines and folds them into the mad.
1911 // Only do this if we are not trying to support denormals. v_mad_f32 does
1912 // not support denormals ever.
1913 if (VT == MVT::f32 &&
1914 !Subtarget->hasFP32Denormals()) {
1915 SDValue LHS = N->getOperand(0);
1916 SDValue RHS = N->getOperand(1);
1917 if (LHS.getOpcode() == ISD::FADD) {
1918 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1920 SDValue A = LHS.getOperand(0);
1921 if (A == LHS.getOperand(1)) {
1922 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1923 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1925 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1929 if (RHS.getOpcode() == ISD::FADD) {
1930 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1932 SDValue A = RHS.getOperand(0);
1933 if (A == RHS.getOperand(1)) {
1934 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1935 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1947 case ISD::ATOMIC_LOAD:
1948 case ISD::ATOMIC_STORE:
1949 case ISD::ATOMIC_CMP_SWAP:
1950 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1951 case ISD::ATOMIC_SWAP:
1952 case ISD::ATOMIC_LOAD_ADD:
1953 case ISD::ATOMIC_LOAD_SUB:
1954 case ISD::ATOMIC_LOAD_AND:
1955 case ISD::ATOMIC_LOAD_OR:
1956 case ISD::ATOMIC_LOAD_XOR:
1957 case ISD::ATOMIC_LOAD_NAND:
1958 case ISD::ATOMIC_LOAD_MIN:
1959 case ISD::ATOMIC_LOAD_MAX:
1960 case ISD::ATOMIC_LOAD_UMIN:
1961 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1962 if (DCI.isBeforeLegalize())
1965 MemSDNode *MemNode = cast<MemSDNode>(N);
1966 SDValue Ptr = MemNode->getBasePtr();
1968 // TODO: We could also do this for multiplies.
1969 unsigned AS = MemNode->getAddressSpace();
1970 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1971 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1973 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1975 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1976 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1982 return performAndCombine(N, DCI);
1984 return performOrCombine(N, DCI);
1985 case AMDGPUISD::FP_CLASS:
1986 return performClassCombine(N, DCI);
1988 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1991 /// \brief Analyze the possible immediate value Op
1993 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1994 /// and the immediate value if it's a literal immediate
1995 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1997 const SIInstrInfo *TII =
1998 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2000 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2001 if (TII->isInlineConstant(Node->getAPIntValue()))
2004 uint64_t Val = Node->getZExtValue();
2005 return isUInt<32>(Val) ? Val : -1;
2008 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2009 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2012 if (Node->getValueType(0) == MVT::f32)
2013 return FloatToBits(Node->getValueAPF().convertToFloat());
2021 /// \brief Helper function for adjustWritemask
2022 static unsigned SubIdx2Lane(unsigned Idx) {
2025 case AMDGPU::sub0: return 0;
2026 case AMDGPU::sub1: return 1;
2027 case AMDGPU::sub2: return 2;
2028 case AMDGPU::sub3: return 3;
2032 /// \brief Adjust the writemask of MIMG instructions
2033 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2034 SelectionDAG &DAG) const {
2035 SDNode *Users[4] = { };
2037 unsigned OldDmask = Node->getConstantOperandVal(0);
2038 unsigned NewDmask = 0;
2040 // Try to figure out the used register components
2041 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2044 // Abort if we can't understand the usage
2045 if (!I->isMachineOpcode() ||
2046 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2049 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2050 // Note that subregs are packed, i.e. Lane==0 is the first bit set
2051 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2053 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2055 // Set which texture component corresponds to the lane.
2057 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2059 Comp = countTrailingZeros(Dmask);
2060 Dmask &= ~(1 << Comp);
2063 // Abort if we have more than one user per component
2068 NewDmask |= 1 << Comp;
2071 // Abort if there's no change
2072 if (NewDmask == OldDmask)
2075 // Adjust the writemask in the node
2076 std::vector<SDValue> Ops;
2077 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2078 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2079 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2081 // If we only got one lane, replace it with a copy
2082 // (if NewDmask has only one bit set...)
2083 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2084 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2086 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2087 SDLoc(), Users[Lane]->getValueType(0),
2088 SDValue(Node, 0), RC);
2089 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2093 // Update the users of the node with the new indices
2094 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2096 SDNode *User = Users[i];
2100 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2101 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2105 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2106 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2107 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2112 static bool isFrameIndexOp(SDValue Op) {
2113 if (Op.getOpcode() == ISD::AssertZext)
2114 Op = Op.getOperand(0);
2116 return isa<FrameIndexSDNode>(Op);
2119 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2120 /// with frame index operands.
2121 /// LLVM assumes that inputs are to these instructions are registers.
2122 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2123 SelectionDAG &DAG) const {
2125 SmallVector<SDValue, 8> Ops;
2126 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2127 if (!isFrameIndexOp(Node->getOperand(i))) {
2128 Ops.push_back(Node->getOperand(i));
2133 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2134 Node->getOperand(i).getValueType(),
2135 Node->getOperand(i)), 0));
2138 DAG.UpdateNodeOperands(Node, Ops);
2141 /// \brief Fold the instructions after selecting them.
2142 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2143 SelectionDAG &DAG) const {
2144 const SIInstrInfo *TII =
2145 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2147 if (TII->isMIMG(Node->getMachineOpcode()))
2148 adjustWritemask(Node, DAG);
2150 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2151 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2152 legalizeTargetIndependentNode(Node, DAG);
2158 /// \brief Assign the register class depending on the number of
2159 /// bits set in the writemask
2160 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2161 SDNode *Node) const {
2162 const SIInstrInfo *TII =
2163 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2165 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2166 TII->legalizeOperands(MI);
2168 if (TII->isMIMG(MI->getOpcode())) {
2169 unsigned VReg = MI->getOperand(0).getReg();
2170 unsigned Writemask = MI->getOperand(1).getImm();
2171 unsigned BitsSet = 0;
2172 for (unsigned i = 0; i < 4; ++i)
2173 BitsSet += Writemask & (1 << i) ? 1 : 0;
2175 const TargetRegisterClass *RC;
2178 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2179 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2180 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2183 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2184 MI->setDesc(TII->get(NewOpcode));
2185 MRI.setRegClass(VReg, RC);
2189 // Replace unused atomics with the no return version.
2190 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2191 if (NoRetAtomicOp != -1) {
2192 if (!Node->hasAnyUseOfValue(0)) {
2193 MI->setDesc(TII->get(NoRetAtomicOp));
2194 MI->RemoveOperand(0);
2201 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2202 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2203 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2206 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2208 SDValue Ptr) const {
2209 const SIInstrInfo *TII =
2210 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2212 // XXX - Workaround for moveToVALU not handling different register class
2213 // inserts for REG_SEQUENCE.
2215 // Build the half of the subregister with the constants.
2216 const SDValue Ops0[] = {
2217 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2218 buildSMovImm32(DAG, DL, 0),
2219 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2220 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2221 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2224 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2225 MVT::v2i32, Ops0), 0);
2227 // Combine the constants and the pointer.
2228 const SDValue Ops1[] = {
2229 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2231 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2233 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2236 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2238 const SDValue Ops[] = {
2239 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2241 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2242 buildSMovImm32(DAG, DL, 0),
2243 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2244 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2245 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2248 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2253 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2254 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2255 /// of the resource descriptor) to create an offset, which is added to
2256 /// the resource pointer.
2257 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2260 uint32_t RsrcDword1,
2261 uint64_t RsrcDword2And3) const {
2262 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2263 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2265 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2266 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2270 SDValue DataLo = buildSMovImm32(DAG, DL,
2271 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2272 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2274 const SDValue Ops[] = {
2275 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2277 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2279 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2281 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2283 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2286 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2289 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2291 SDValue Ptr) const {
2292 const SIInstrInfo *TII =
2293 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2294 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2297 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2300 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2301 const TargetRegisterClass *RC,
2302 unsigned Reg, EVT VT) const {
2303 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2305 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2306 cast<RegisterSDNode>(VReg)->getReg(), VT);
2309 //===----------------------------------------------------------------------===//
2310 // SI Inline Assembly Support
2311 //===----------------------------------------------------------------------===//
2313 std::pair<unsigned, const TargetRegisterClass *>
2314 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2315 StringRef Constraint,
2317 if (Constraint == "r") {
2318 switch(VT.SimpleTy) {
2319 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2321 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2323 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2327 if (Constraint.size() > 1) {
2328 const TargetRegisterClass *RC = nullptr;
2329 if (Constraint[1] == 'v') {
2330 RC = &AMDGPU::VGPR_32RegClass;
2331 } else if (Constraint[1] == 's') {
2332 RC = &AMDGPU::SGPR_32RegClass;
2337 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2338 if (!Failed && Idx < RC->getNumRegs())
2339 return std::make_pair(RC->getRegister(Idx), RC);
2342 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);