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 return Align % 4 == 0;
415 // Smaller than dword value must be aligned.
416 // FIXME: This should be allowed on CI+
417 if (VT.bitsLT(MVT::i32))
420 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
421 // byte-address are ignored, thus forcing Dword alignment.
422 // This applies to private, global, and constant memory.
426 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
429 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
430 unsigned SrcAlign, bool IsMemset,
433 MachineFunction &MF) const {
434 // FIXME: Should account for address space here.
436 // The default fallback uses the private pointer size as a guess for a type to
437 // use. Make sure we switch these to 64-bit accesses.
439 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
442 if (Size >= 8 && DstAlign >= 4)
449 TargetLoweringBase::LegalizeTypeAction
450 SITargetLowering::getPreferredVectorAction(EVT VT) const {
451 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
452 return TypeSplitVector;
454 return TargetLoweringBase::getPreferredVectorAction(VT);
457 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
459 const SIInstrInfo *TII =
460 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
461 return TII->isInlineConstant(Imm);
464 static EVT toIntegerVT(EVT VT) {
466 return VT.changeVectorElementTypeToInteger();
467 return MVT::getIntegerVT(VT.getSizeInBits());
470 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
471 SDLoc SL, SDValue Chain,
472 unsigned Offset, bool Signed) const {
473 const DataLayout &DL = DAG.getDataLayout();
474 MachineFunction &MF = DAG.getMachineFunction();
475 const SIRegisterInfo *TRI =
476 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
477 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
479 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
481 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
482 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
483 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
484 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
485 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
486 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
487 DAG.getConstant(Offset, SL, PtrVT));
488 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
489 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
491 unsigned Align = DL.getABITypeAlignment(Ty);
493 if (VT != MemVT && VT.isFloatingPoint()) {
494 // Do an integer load and convert.
495 // FIXME: This is mostly because load legalization after type legalization
496 // doesn't handle FP extloads.
497 assert(VT.getScalarType() == MVT::f32 &&
498 MemVT.getScalarType() == MVT::f16);
500 EVT IVT = toIntegerVT(VT);
501 EVT MemIVT = toIntegerVT(MemVT);
502 SDValue Load = DAG.getLoad(ISD::UNINDEXED, ISD::ZEXTLOAD,
503 IVT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemIVT,
505 true, // isNonTemporal
509 DAG.getNode(ISD::FP16_TO_FP, SL, VT, Load),
513 return DAG.getMergeValues(Ops, SL);
516 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
517 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
518 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
520 true, // isNonTemporal
525 SDValue SITargetLowering::LowerFormalArguments(
526 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
527 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
528 SmallVectorImpl<SDValue> &InVals) const {
529 const SIRegisterInfo *TRI =
530 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
532 MachineFunction &MF = DAG.getMachineFunction();
533 FunctionType *FType = MF.getFunction()->getFunctionType();
534 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
536 assert(CallConv == CallingConv::C);
538 SmallVector<ISD::InputArg, 16> Splits;
539 BitVector Skipped(Ins.size());
541 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
542 const ISD::InputArg &Arg = Ins[i];
544 // First check if it's a PS input addr
545 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
546 !Arg.Flags.isByVal()) {
548 assert((PSInputNum <= 15) && "Too many PS inputs!");
551 // We can safely skip PS inputs
557 Info->PSInputAddr |= 1 << PSInputNum++;
560 // Second split vertices into their elements
561 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
562 ISD::InputArg NewArg = Arg;
563 NewArg.Flags.setSplit();
564 NewArg.VT = Arg.VT.getVectorElementType();
566 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
567 // three or five element vertex only needs three or five registers,
568 // NOT four or eight.
569 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
570 unsigned NumElements = ParamType->getVectorNumElements();
572 for (unsigned j = 0; j != NumElements; ++j) {
573 Splits.push_back(NewArg);
574 NewArg.PartOffset += NewArg.VT.getStoreSize();
577 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
578 Splits.push_back(Arg);
582 SmallVector<CCValAssign, 16> ArgLocs;
583 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
586 // At least one interpolation mode must be enabled or else the GPU will hang.
587 if (Info->getShaderType() == ShaderType::PIXEL &&
588 (Info->PSInputAddr & 0x7F) == 0) {
589 Info->PSInputAddr |= 1;
590 CCInfo.AllocateReg(AMDGPU::VGPR0);
591 CCInfo.AllocateReg(AMDGPU::VGPR1);
594 // The pointer to the list of arguments is stored in SGPR0, SGPR1
595 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
596 if (Info->getShaderType() == ShaderType::COMPUTE) {
597 if (Subtarget->isAmdHsaOS())
598 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
600 Info->NumUserSGPRs = 4;
602 unsigned InputPtrReg =
603 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
604 unsigned InputPtrRegLo =
605 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
606 unsigned InputPtrRegHi =
607 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
609 unsigned ScratchPtrReg =
610 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
611 unsigned ScratchPtrRegLo =
612 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
613 unsigned ScratchPtrRegHi =
614 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
616 CCInfo.AllocateReg(InputPtrRegLo);
617 CCInfo.AllocateReg(InputPtrRegHi);
618 CCInfo.AllocateReg(ScratchPtrRegLo);
619 CCInfo.AllocateReg(ScratchPtrRegHi);
620 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
621 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
624 if (Info->getShaderType() == ShaderType::COMPUTE) {
625 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
629 AnalyzeFormalArguments(CCInfo, Splits);
631 SmallVector<SDValue, 16> Chains;
633 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
635 const ISD::InputArg &Arg = Ins[i];
637 InVals.push_back(DAG.getUNDEF(Arg.VT));
641 CCValAssign &VA = ArgLocs[ArgIdx++];
642 MVT VT = VA.getLocVT();
646 EVT MemVT = Splits[i].VT;
647 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
648 VA.getLocMemOffset();
649 // The first 36 bytes of the input buffer contains information about
650 // thread group and global sizes.
651 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
652 Offset, Ins[i].Flags.isSExt());
653 Chains.push_back(Arg.getValue(1));
656 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
657 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
658 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
659 // On SI local pointers are just offsets into LDS, so they are always
660 // less than 16-bits. On CI and newer they could potentially be
661 // real pointers, so we can't guarantee their size.
662 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
663 DAG.getValueType(MVT::i16));
666 InVals.push_back(Arg);
667 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
670 assert(VA.isRegLoc() && "Parameter must be in a register!");
672 unsigned Reg = VA.getLocReg();
674 if (VT == MVT::i64) {
675 // For now assume it is a pointer
676 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
677 &AMDGPU::SReg_64RegClass);
678 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
679 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
680 InVals.push_back(Copy);
684 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
686 Reg = MF.addLiveIn(Reg, RC);
687 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
689 if (Arg.VT.isVector()) {
691 // Build a vector from the registers
692 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
693 unsigned NumElements = ParamType->getVectorNumElements();
695 SmallVector<SDValue, 4> Regs;
697 for (unsigned j = 1; j != NumElements; ++j) {
698 Reg = ArgLocs[ArgIdx++].getLocReg();
699 Reg = MF.addLiveIn(Reg, RC);
701 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
702 Regs.push_back(Copy);
705 // Fill up the missing vector elements
706 NumElements = Arg.VT.getVectorNumElements() - NumElements;
707 Regs.append(NumElements, DAG.getUNDEF(VT));
709 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
713 InVals.push_back(Val);
716 if (Info->getShaderType() != ShaderType::COMPUTE) {
717 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
718 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
719 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
725 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
728 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
729 MachineInstr * MI, MachineBasicBlock * BB) const {
731 MachineBasicBlock::iterator I = *MI;
732 const SIInstrInfo *TII =
733 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
735 switch (MI->getOpcode()) {
737 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
740 case AMDGPU::SI_RegisterStorePseudo: {
741 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
742 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
743 MachineInstrBuilder MIB =
744 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
746 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
747 MIB.addOperand(MI->getOperand(i));
749 MI->eraseFromParent();
756 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
757 // This currently forces unfolding various combinations of fsub into fma with
758 // free fneg'd operands. As long as we have fast FMA (controlled by
759 // isFMAFasterThanFMulAndFAdd), we should perform these.
761 // When fma is quarter rate, for f64 where add / sub are at best half rate,
762 // most of these combines appear to be cycle neutral but save on instruction
763 // count / code size.
767 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
769 if (!VT.isVector()) {
772 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
775 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
779 // Answering this is somewhat tricky and depends on the specific device which
780 // have different rates for fma or all f64 operations.
782 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
783 // regardless of which device (although the number of cycles differs between
784 // devices), so it is always profitable for f64.
786 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
787 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
788 // which we can always do even without fused FP ops since it returns the same
789 // result as the separate operations and since it is always full
790 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
791 // however does not support denormals, so we do report fma as faster if we have
792 // a fast fma device and require denormals.
794 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
795 VT = VT.getScalarType();
800 switch (VT.getSimpleVT().SimpleTy) {
802 // This is as fast on some subtargets. However, we always have full rate f32
803 // mad available which returns the same result as the separate operations
804 // which we should prefer over fma. We can't use this if we want to support
805 // denormals, so only report this in these cases.
806 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
816 //===----------------------------------------------------------------------===//
817 // Custom DAG Lowering Operations
818 //===----------------------------------------------------------------------===//
820 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
821 switch (Op.getOpcode()) {
822 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
823 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
824 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
826 SDValue Result = LowerLOAD(Op, DAG);
827 assert((!Result.getNode() ||
828 Result.getNode()->getNumValues() == 2) &&
829 "Load should return a value and a chain");
835 return LowerTrig(Op, DAG);
836 case ISD::SELECT: return LowerSELECT(Op, DAG);
837 case ISD::FDIV: return LowerFDIV(Op, DAG);
838 case ISD::STORE: return LowerSTORE(Op, DAG);
839 case ISD::GlobalAddress: {
840 MachineFunction &MF = DAG.getMachineFunction();
841 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
842 return LowerGlobalAddress(MFI, Op, DAG);
844 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
845 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
850 /// \brief Helper function for LowerBRCOND
851 static SDNode *findUser(SDValue Value, unsigned Opcode) {
853 SDNode *Parent = Value.getNode();
854 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
857 if (I.getUse().get() != Value)
860 if (I->getOpcode() == Opcode)
866 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
869 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
870 unsigned FrameIndex = FINode->getIndex();
872 // A FrameIndex node represents a 32-bit offset into scratch memory. If
873 // the high bit of a frame index offset were to be set, this would mean
874 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
875 // scratch buffer, with 64 being the number of threads per wave.
877 // If we know the machine uses less than 128GB of scratch, then we can
878 // amrk the high bit of the FrameIndex node as known zero,
879 // which is important, because it means in most situations we can
880 // prove that values derived from FrameIndex nodes are non-negative.
881 // This enables us to take advantage of more addressing modes when
882 // accessing scratch buffers, since for scratch reads/writes, the register
883 // offset must always be positive.
885 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
886 if (Subtarget->enableHugeScratchBuffer())
889 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
890 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
893 /// This transforms the control flow intrinsics to get the branch destination as
894 /// last parameter, also switches branch target with BR if the need arise
895 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
896 SelectionDAG &DAG) const {
900 SDNode *Intr = BRCOND.getOperand(1).getNode();
901 SDValue Target = BRCOND.getOperand(2);
902 SDNode *BR = nullptr;
904 if (Intr->getOpcode() == ISD::SETCC) {
905 // As long as we negate the condition everything is fine
906 SDNode *SetCC = Intr;
907 assert(SetCC->getConstantOperandVal(1) == 1);
908 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
910 Intr = SetCC->getOperand(0).getNode();
913 // Get the target from BR if we don't negate the condition
914 BR = findUser(BRCOND, ISD::BR);
915 Target = BR->getOperand(1);
918 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
920 // Build the result and
921 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
923 // operands of the new intrinsic call
924 SmallVector<SDValue, 4> Ops;
925 Ops.push_back(BRCOND.getOperand(0));
926 Ops.append(Intr->op_begin() + 1, Intr->op_end());
927 Ops.push_back(Target);
929 // build the new intrinsic call
930 SDNode *Result = DAG.getNode(
931 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
932 DAG.getVTList(Res), Ops).getNode();
935 // Give the branch instruction our target
940 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
941 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
942 BR = NewBR.getNode();
945 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
947 // Copy the intrinsic results to registers
948 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
949 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
953 Chain = DAG.getCopyToReg(
955 CopyToReg->getOperand(1),
956 SDValue(Result, i - 1),
959 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
962 // Remove the old intrinsic from the chain
963 DAG.ReplaceAllUsesOfValueWith(
964 SDValue(Intr, Intr->getNumValues() - 1),
965 Intr->getOperand(0));
970 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
972 SelectionDAG &DAG) const {
973 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
975 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
976 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
979 const GlobalValue *GV = GSD->getGlobal();
980 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
982 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
983 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
985 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
986 DAG.getConstant(0, DL, MVT::i32));
987 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
988 DAG.getConstant(1, DL, MVT::i32));
990 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
992 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
993 PtrHi, DAG.getConstant(0, DL, MVT::i32),
994 SDValue(Lo.getNode(), 1));
995 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
998 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1000 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1001 // so we will end up with redundant moves to m0.
1003 // We can't use S_MOV_B32, because there is no way to specify m0 as the
1004 // destination register.
1006 // We have to use them both. Machine cse will combine all the S_MOV_B32
1007 // instructions and the register coalescer eliminate the extra copies.
1008 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1009 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1010 SDValue(M0, 0), SDValue()); // Glue
1011 // A Null SDValue creates
1015 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1016 SelectionDAG &DAG) const {
1017 MachineFunction &MF = DAG.getMachineFunction();
1018 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1019 const SIRegisterInfo *TRI =
1020 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1022 EVT VT = Op.getValueType();
1024 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1026 switch (IntrinsicID) {
1027 case Intrinsic::r600_read_ngroups_x:
1028 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1029 SI::KernelInputOffsets::NGROUPS_X, false);
1030 case Intrinsic::r600_read_ngroups_y:
1031 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1032 SI::KernelInputOffsets::NGROUPS_Y, false);
1033 case Intrinsic::r600_read_ngroups_z:
1034 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1035 SI::KernelInputOffsets::NGROUPS_Z, false);
1036 case Intrinsic::r600_read_global_size_x:
1037 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1038 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1039 case Intrinsic::r600_read_global_size_y:
1040 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1041 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1042 case Intrinsic::r600_read_global_size_z:
1043 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1044 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1045 case Intrinsic::r600_read_local_size_x:
1046 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1047 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
1048 case Intrinsic::r600_read_local_size_y:
1049 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1050 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
1051 case Intrinsic::r600_read_local_size_z:
1052 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1053 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
1055 case Intrinsic::AMDGPU_read_workdim:
1056 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1057 getImplicitParameterOffset(MFI, GRID_DIM), false);
1059 case Intrinsic::r600_read_tgid_x:
1060 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1061 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
1062 case Intrinsic::r600_read_tgid_y:
1063 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1064 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
1065 case Intrinsic::r600_read_tgid_z:
1066 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1067 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
1068 case Intrinsic::r600_read_tidig_x:
1069 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1070 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
1071 case Intrinsic::r600_read_tidig_y:
1072 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1073 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
1074 case Intrinsic::r600_read_tidig_z:
1075 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1076 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
1077 case AMDGPUIntrinsic::SI_load_const: {
1083 MachineMemOperand *MMO = MF.getMachineMemOperand(
1084 MachinePointerInfo(),
1085 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1086 VT.getStoreSize(), 4);
1087 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1088 Op->getVTList(), Ops, VT, MMO);
1090 case AMDGPUIntrinsic::SI_sample:
1091 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1092 case AMDGPUIntrinsic::SI_sampleb:
1093 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1094 case AMDGPUIntrinsic::SI_sampled:
1095 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1096 case AMDGPUIntrinsic::SI_samplel:
1097 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1098 case AMDGPUIntrinsic::SI_vs_load_input:
1099 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1104 case AMDGPUIntrinsic::AMDGPU_fract:
1105 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1106 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1107 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1108 case AMDGPUIntrinsic::SI_fs_constant: {
1109 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1110 SDValue Glue = M0.getValue(1);
1111 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1112 DAG.getConstant(2, DL, MVT::i32), // P0
1113 Op.getOperand(1), Op.getOperand(2), Glue);
1115 case AMDGPUIntrinsic::SI_fs_interp: {
1116 SDValue IJ = Op.getOperand(4);
1117 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1118 DAG.getConstant(0, DL, MVT::i32));
1119 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1120 DAG.getConstant(1, DL, MVT::i32));
1121 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1122 SDValue Glue = M0.getValue(1);
1123 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1124 DAG.getVTList(MVT::f32, MVT::Glue),
1125 I, Op.getOperand(1), Op.getOperand(2), Glue);
1126 Glue = SDValue(P1.getNode(), 1);
1127 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1128 Op.getOperand(1), Op.getOperand(2), Glue);
1131 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1135 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1136 SelectionDAG &DAG) const {
1137 MachineFunction &MF = DAG.getMachineFunction();
1139 SDValue Chain = Op.getOperand(0);
1140 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1142 switch (IntrinsicID) {
1143 case AMDGPUIntrinsic::SI_sendmsg: {
1144 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1145 SDValue Glue = Chain.getValue(1);
1146 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1147 Op.getOperand(2), Glue);
1149 case AMDGPUIntrinsic::SI_tbuffer_store: {
1167 EVT VT = Op.getOperand(3).getValueType();
1169 MachineMemOperand *MMO = MF.getMachineMemOperand(
1170 MachinePointerInfo(),
1171 MachineMemOperand::MOStore,
1172 VT.getStoreSize(), 4);
1173 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1174 Op->getVTList(), Ops, VT, MMO);
1181 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1183 LoadSDNode *Load = cast<LoadSDNode>(Op);
1185 if (Op.getValueType().isVector()) {
1186 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1187 "Custom lowering for non-i32 vectors hasn't been implemented.");
1188 unsigned NumElements = Op.getValueType().getVectorNumElements();
1189 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1190 switch (Load->getAddressSpace()) {
1192 case AMDGPUAS::GLOBAL_ADDRESS:
1193 case AMDGPUAS::PRIVATE_ADDRESS:
1194 // v4 loads are supported for private and global memory.
1195 if (NumElements <= 4)
1198 case AMDGPUAS::LOCAL_ADDRESS:
1199 return ScalarizeVectorLoad(Op, DAG);
1203 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1206 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1208 SelectionDAG &DAG) const {
1209 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1215 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1216 if (Op.getValueType() != MVT::i64)
1220 SDValue Cond = Op.getOperand(0);
1222 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1223 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1225 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1226 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1228 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1229 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1231 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1233 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1234 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1236 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1238 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1239 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1242 // Catch division cases where we can use shortcuts with rcp and rsq
1244 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1246 SDValue LHS = Op.getOperand(0);
1247 SDValue RHS = Op.getOperand(1);
1248 EVT VT = Op.getValueType();
1249 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1251 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1252 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1253 CLHS->isExactlyValue(1.0)) {
1254 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1255 // the CI documentation has a worst case error of 1 ulp.
1256 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1257 // use it as long as we aren't trying to use denormals.
1259 // 1.0 / sqrt(x) -> rsq(x)
1261 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1262 // error seems really high at 2^29 ULP.
1263 if (RHS.getOpcode() == ISD::FSQRT)
1264 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1266 // 1.0 / x -> rcp(x)
1267 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1272 // Turn into multiply by the reciprocal.
1273 // x / y -> x * (1.0 / y)
1274 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1275 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1281 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1282 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1283 if (FastLowered.getNode())
1286 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1287 // selection error for now rather than do something incorrect.
1288 if (Subtarget->hasFP32Denormals())
1292 SDValue LHS = Op.getOperand(0);
1293 SDValue RHS = Op.getOperand(1);
1295 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1297 const APFloat K0Val(BitsToFloat(0x6f800000));
1298 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1300 const APFloat K1Val(BitsToFloat(0x2f800000));
1301 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1303 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1306 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1308 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1310 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1312 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1314 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1316 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1318 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1321 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1322 if (DAG.getTarget().Options.UnsafeFPMath)
1323 return LowerFastFDIV(Op, DAG);
1326 SDValue X = Op.getOperand(0);
1327 SDValue Y = Op.getOperand(1);
1329 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1331 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1333 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1335 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1337 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1339 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1341 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1343 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1345 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1347 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1348 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1350 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1351 NegDivScale0, Mul, DivScale1);
1355 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1356 // Workaround a hardware bug on SI where the condition output from div_scale
1359 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1361 // Figure out if the scale to use for div_fmas.
1362 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1363 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1364 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1365 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1367 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1368 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1371 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1373 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1375 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1376 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1377 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1379 Scale = DivScale1.getValue(1);
1382 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1383 Fma4, Fma3, Mul, Scale);
1385 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1388 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1389 EVT VT = Op.getValueType();
1392 return LowerFDIV32(Op, DAG);
1395 return LowerFDIV64(Op, DAG);
1397 llvm_unreachable("Unexpected type for fdiv");
1400 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1402 StoreSDNode *Store = cast<StoreSDNode>(Op);
1403 EVT VT = Store->getMemoryVT();
1405 // These stores are legal.
1406 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1407 if (VT.isVector() && VT.getVectorNumElements() > 4)
1408 return ScalarizeVectorStore(Op, DAG);
1412 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1416 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1417 return ScalarizeVectorStore(Op, DAG);
1420 return DAG.getTruncStore(Store->getChain(), DL,
1421 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1422 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1427 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1429 EVT VT = Op.getValueType();
1430 SDValue Arg = Op.getOperand(0);
1431 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1432 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1433 DAG.getConstantFP(0.5/M_PI, DL,
1436 switch (Op.getOpcode()) {
1438 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1440 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1442 llvm_unreachable("Wrong trig opcode");
1446 //===----------------------------------------------------------------------===//
1447 // Custom DAG optimizations
1448 //===----------------------------------------------------------------------===//
1450 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1451 DAGCombinerInfo &DCI) const {
1452 EVT VT = N->getValueType(0);
1453 EVT ScalarVT = VT.getScalarType();
1454 if (ScalarVT != MVT::f32)
1457 SelectionDAG &DAG = DCI.DAG;
1460 SDValue Src = N->getOperand(0);
1461 EVT SrcVT = Src.getValueType();
1463 // TODO: We could try to match extracting the higher bytes, which would be
1464 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1465 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1466 // about in practice.
1467 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1468 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1469 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1470 DCI.AddToWorklist(Cvt.getNode());
1475 // We are primarily trying to catch operations on illegal vector types
1476 // before they are expanded.
1477 // For scalars, we can use the more flexible method of checking masked bits
1478 // after legalization.
1479 if (!DCI.isBeforeLegalize() ||
1480 !SrcVT.isVector() ||
1481 SrcVT.getVectorElementType() != MVT::i8) {
1485 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1487 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1489 unsigned NElts = SrcVT.getVectorNumElements();
1490 if (!SrcVT.isSimple() && NElts != 3)
1493 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1494 // prevent a mess from expanding to v4i32 and repacking.
1495 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1496 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1497 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1498 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1499 LoadSDNode *Load = cast<LoadSDNode>(Src);
1501 unsigned AS = Load->getAddressSpace();
1502 unsigned Align = Load->getAlignment();
1503 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1504 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1506 // Don't try to replace the load if we have to expand it due to alignment
1507 // problems. Otherwise we will end up scalarizing the load, and trying to
1508 // repack into the vector for no real reason.
1509 if (Align < ABIAlignment &&
1510 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1514 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1518 Load->getMemOperand());
1520 // Make sure successors of the original load stay after it by updating
1521 // them to use the new Chain.
1522 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1524 SmallVector<SDValue, 4> Elts;
1525 if (RegVT.isVector())
1526 DAG.ExtractVectorElements(NewLoad, Elts);
1528 Elts.push_back(NewLoad);
1530 SmallVector<SDValue, 4> Ops;
1532 unsigned EltIdx = 0;
1533 for (SDValue Elt : Elts) {
1534 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1535 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1536 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1537 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1538 DCI.AddToWorklist(Cvt.getNode());
1545 assert(Ops.size() == NElts);
1547 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1553 /// \brief Return true if the given offset Size in bytes can be folded into
1554 /// the immediate offsets of a memory instruction for the given address space.
1555 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1556 const AMDGPUSubtarget &STI) {
1558 case AMDGPUAS::GLOBAL_ADDRESS: {
1559 // MUBUF instructions a 12-bit offset in bytes.
1560 return isUInt<12>(OffsetSize);
1562 case AMDGPUAS::CONSTANT_ADDRESS: {
1563 // SMRD instructions have an 8-bit offset in dwords on SI and
1564 // a 20-bit offset in bytes on VI.
1565 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1566 return isUInt<20>(OffsetSize);
1568 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1570 case AMDGPUAS::LOCAL_ADDRESS:
1571 case AMDGPUAS::REGION_ADDRESS: {
1572 // The single offset versions have a 16-bit offset in bytes.
1573 return isUInt<16>(OffsetSize);
1575 case AMDGPUAS::PRIVATE_ADDRESS:
1576 // Indirect register addressing does not use any offsets.
1582 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1584 // This is a variant of
1585 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1587 // The normal DAG combiner will do this, but only if the add has one use since
1588 // that would increase the number of instructions.
1590 // This prevents us from seeing a constant offset that can be folded into a
1591 // memory instruction's addressing mode. If we know the resulting add offset of
1592 // a pointer can be folded into an addressing offset, we can replace the pointer
1593 // operand with the add of new constant offset. This eliminates one of the uses,
1594 // and may allow the remaining use to also be simplified.
1596 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1598 DAGCombinerInfo &DCI) const {
1599 SDValue N0 = N->getOperand(0);
1600 SDValue N1 = N->getOperand(1);
1602 if (N0.getOpcode() != ISD::ADD)
1605 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1609 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1613 // If the resulting offset is too large, we can't fold it into the addressing
1615 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1616 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1619 SelectionDAG &DAG = DCI.DAG;
1621 EVT VT = N->getValueType(0);
1623 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1624 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1626 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1629 SDValue SITargetLowering::performAndCombine(SDNode *N,
1630 DAGCombinerInfo &DCI) const {
1631 if (DCI.isBeforeLegalize())
1634 SelectionDAG &DAG = DCI.DAG;
1636 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1637 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1638 SDValue LHS = N->getOperand(0);
1639 SDValue RHS = N->getOperand(1);
1641 if (LHS.getOpcode() == ISD::SETCC &&
1642 RHS.getOpcode() == ISD::SETCC) {
1643 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1644 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1646 SDValue X = LHS.getOperand(0);
1647 SDValue Y = RHS.getOperand(0);
1648 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1651 if (LCC == ISD::SETO) {
1652 if (X != LHS.getOperand(1))
1655 if (RCC == ISD::SETUNE) {
1656 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1657 if (!C1 || !C1->isInfinity() || C1->isNegative())
1660 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1661 SIInstrFlags::N_SUBNORMAL |
1662 SIInstrFlags::N_ZERO |
1663 SIInstrFlags::P_ZERO |
1664 SIInstrFlags::P_SUBNORMAL |
1665 SIInstrFlags::P_NORMAL;
1667 static_assert(((~(SIInstrFlags::S_NAN |
1668 SIInstrFlags::Q_NAN |
1669 SIInstrFlags::N_INFINITY |
1670 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1674 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1675 X, DAG.getConstant(Mask, DL, MVT::i32));
1683 SDValue SITargetLowering::performOrCombine(SDNode *N,
1684 DAGCombinerInfo &DCI) const {
1685 SelectionDAG &DAG = DCI.DAG;
1686 SDValue LHS = N->getOperand(0);
1687 SDValue RHS = N->getOperand(1);
1689 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1690 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1691 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1692 SDValue Src = LHS.getOperand(0);
1693 if (Src != RHS.getOperand(0))
1696 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1697 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1701 // Only 10 bits are used.
1702 static const uint32_t MaxMask = 0x3ff;
1704 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1706 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1707 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1713 SDValue SITargetLowering::performClassCombine(SDNode *N,
1714 DAGCombinerInfo &DCI) const {
1715 SelectionDAG &DAG = DCI.DAG;
1716 SDValue Mask = N->getOperand(1);
1718 // fp_class x, 0 -> false
1719 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1720 if (CMask->isNullValue())
1721 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1727 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1730 return AMDGPUISD::FMAX3;
1732 return AMDGPUISD::SMAX3;
1734 return AMDGPUISD::UMAX3;
1736 return AMDGPUISD::FMIN3;
1738 return AMDGPUISD::SMIN3;
1740 return AMDGPUISD::UMIN3;
1742 llvm_unreachable("Not a min/max opcode");
1746 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1747 DAGCombinerInfo &DCI) const {
1748 SelectionDAG &DAG = DCI.DAG;
1750 unsigned Opc = N->getOpcode();
1751 SDValue Op0 = N->getOperand(0);
1752 SDValue Op1 = N->getOperand(1);
1754 // Only do this if the inner op has one use since this will just increases
1755 // register pressure for no benefit.
1757 // max(max(a, b), c)
1758 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1760 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1768 // max(a, max(b, c))
1769 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1771 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1782 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1783 DAGCombinerInfo &DCI) const {
1784 SelectionDAG &DAG = DCI.DAG;
1787 SDValue LHS = N->getOperand(0);
1788 SDValue RHS = N->getOperand(1);
1789 EVT VT = LHS.getValueType();
1791 if (VT != MVT::f32 && VT != MVT::f64)
1794 // Match isinf pattern
1795 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1796 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1797 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1798 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1802 const APFloat &APF = CRHS->getValueAPF();
1803 if (APF.isInfinity() && !APF.isNegative()) {
1804 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1805 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1806 DAG.getConstant(Mask, SL, MVT::i32));
1813 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1814 DAGCombinerInfo &DCI) const {
1815 SelectionDAG &DAG = DCI.DAG;
1818 switch (N->getOpcode()) {
1820 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1822 return performSetCCCombine(N, DCI);
1823 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1829 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1830 N->getValueType(0) != MVT::f64 &&
1831 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1832 return performMin3Max3Combine(N, DCI);
1836 case AMDGPUISD::CVT_F32_UBYTE0:
1837 case AMDGPUISD::CVT_F32_UBYTE1:
1838 case AMDGPUISD::CVT_F32_UBYTE2:
1839 case AMDGPUISD::CVT_F32_UBYTE3: {
1840 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1842 SDValue Src = N->getOperand(0);
1843 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1845 APInt KnownZero, KnownOne;
1846 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1847 !DCI.isBeforeLegalizeOps());
1848 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1849 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1850 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1851 DCI.CommitTargetLoweringOpt(TLO);
1857 case ISD::UINT_TO_FP: {
1858 return performUCharToFloatCombine(N, DCI);
1861 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1864 EVT VT = N->getValueType(0);
1868 // Only do this if we are not trying to support denormals. v_mad_f32 does
1869 // not support denormals ever.
1870 if (Subtarget->hasFP32Denormals())
1873 SDValue LHS = N->getOperand(0);
1874 SDValue RHS = N->getOperand(1);
1876 // These should really be instruction patterns, but writing patterns with
1877 // source modiifiers is a pain.
1879 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1880 if (LHS.getOpcode() == ISD::FADD) {
1881 SDValue A = LHS.getOperand(0);
1882 if (A == LHS.getOperand(1)) {
1883 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1884 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1888 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1889 if (RHS.getOpcode() == ISD::FADD) {
1890 SDValue A = RHS.getOperand(0);
1891 if (A == RHS.getOperand(1)) {
1892 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1893 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1900 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1903 EVT VT = N->getValueType(0);
1905 // Try to get the fneg to fold into the source modifier. This undoes generic
1906 // DAG combines and folds them into the mad.
1908 // Only do this if we are not trying to support denormals. v_mad_f32 does
1909 // not support denormals ever.
1910 if (VT == MVT::f32 &&
1911 !Subtarget->hasFP32Denormals()) {
1912 SDValue LHS = N->getOperand(0);
1913 SDValue RHS = N->getOperand(1);
1914 if (LHS.getOpcode() == ISD::FADD) {
1915 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1917 SDValue A = LHS.getOperand(0);
1918 if (A == LHS.getOperand(1)) {
1919 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1920 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1922 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1926 if (RHS.getOpcode() == ISD::FADD) {
1927 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1929 SDValue A = RHS.getOperand(0);
1930 if (A == RHS.getOperand(1)) {
1931 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1932 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1944 case ISD::ATOMIC_LOAD:
1945 case ISD::ATOMIC_STORE:
1946 case ISD::ATOMIC_CMP_SWAP:
1947 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1948 case ISD::ATOMIC_SWAP:
1949 case ISD::ATOMIC_LOAD_ADD:
1950 case ISD::ATOMIC_LOAD_SUB:
1951 case ISD::ATOMIC_LOAD_AND:
1952 case ISD::ATOMIC_LOAD_OR:
1953 case ISD::ATOMIC_LOAD_XOR:
1954 case ISD::ATOMIC_LOAD_NAND:
1955 case ISD::ATOMIC_LOAD_MIN:
1956 case ISD::ATOMIC_LOAD_MAX:
1957 case ISD::ATOMIC_LOAD_UMIN:
1958 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1959 if (DCI.isBeforeLegalize())
1962 MemSDNode *MemNode = cast<MemSDNode>(N);
1963 SDValue Ptr = MemNode->getBasePtr();
1965 // TODO: We could also do this for multiplies.
1966 unsigned AS = MemNode->getAddressSpace();
1967 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1968 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1970 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1972 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1973 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1979 return performAndCombine(N, DCI);
1981 return performOrCombine(N, DCI);
1982 case AMDGPUISD::FP_CLASS:
1983 return performClassCombine(N, DCI);
1985 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1988 /// \brief Analyze the possible immediate value Op
1990 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1991 /// and the immediate value if it's a literal immediate
1992 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1994 const SIInstrInfo *TII =
1995 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1997 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1998 if (TII->isInlineConstant(Node->getAPIntValue()))
2001 uint64_t Val = Node->getZExtValue();
2002 return isUInt<32>(Val) ? Val : -1;
2005 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2006 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2009 if (Node->getValueType(0) == MVT::f32)
2010 return FloatToBits(Node->getValueAPF().convertToFloat());
2018 /// \brief Helper function for adjustWritemask
2019 static unsigned SubIdx2Lane(unsigned Idx) {
2022 case AMDGPU::sub0: return 0;
2023 case AMDGPU::sub1: return 1;
2024 case AMDGPU::sub2: return 2;
2025 case AMDGPU::sub3: return 3;
2029 /// \brief Adjust the writemask of MIMG instructions
2030 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2031 SelectionDAG &DAG) const {
2032 SDNode *Users[4] = { };
2034 unsigned OldDmask = Node->getConstantOperandVal(0);
2035 unsigned NewDmask = 0;
2037 // Try to figure out the used register components
2038 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2041 // Abort if we can't understand the usage
2042 if (!I->isMachineOpcode() ||
2043 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2046 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2047 // Note that subregs are packed, i.e. Lane==0 is the first bit set
2048 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2050 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2052 // Set which texture component corresponds to the lane.
2054 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2056 Comp = countTrailingZeros(Dmask);
2057 Dmask &= ~(1 << Comp);
2060 // Abort if we have more than one user per component
2065 NewDmask |= 1 << Comp;
2068 // Abort if there's no change
2069 if (NewDmask == OldDmask)
2072 // Adjust the writemask in the node
2073 std::vector<SDValue> Ops;
2074 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2075 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2076 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2078 // If we only got one lane, replace it with a copy
2079 // (if NewDmask has only one bit set...)
2080 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2081 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2083 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2084 SDLoc(), Users[Lane]->getValueType(0),
2085 SDValue(Node, 0), RC);
2086 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2090 // Update the users of the node with the new indices
2091 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2093 SDNode *User = Users[i];
2097 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2098 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2102 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2103 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2104 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2109 static bool isFrameIndexOp(SDValue Op) {
2110 if (Op.getOpcode() == ISD::AssertZext)
2111 Op = Op.getOperand(0);
2113 return isa<FrameIndexSDNode>(Op);
2116 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2117 /// with frame index operands.
2118 /// LLVM assumes that inputs are to these instructions are registers.
2119 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2120 SelectionDAG &DAG) const {
2122 SmallVector<SDValue, 8> Ops;
2123 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2124 if (!isFrameIndexOp(Node->getOperand(i))) {
2125 Ops.push_back(Node->getOperand(i));
2130 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2131 Node->getOperand(i).getValueType(),
2132 Node->getOperand(i)), 0));
2135 DAG.UpdateNodeOperands(Node, Ops);
2138 /// \brief Fold the instructions after selecting them.
2139 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2140 SelectionDAG &DAG) const {
2141 const SIInstrInfo *TII =
2142 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2144 if (TII->isMIMG(Node->getMachineOpcode()))
2145 adjustWritemask(Node, DAG);
2147 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2148 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2149 legalizeTargetIndependentNode(Node, DAG);
2155 /// \brief Assign the register class depending on the number of
2156 /// bits set in the writemask
2157 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2158 SDNode *Node) const {
2159 const SIInstrInfo *TII =
2160 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2162 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2163 TII->legalizeOperands(MI);
2165 if (TII->isMIMG(MI->getOpcode())) {
2166 unsigned VReg = MI->getOperand(0).getReg();
2167 unsigned Writemask = MI->getOperand(1).getImm();
2168 unsigned BitsSet = 0;
2169 for (unsigned i = 0; i < 4; ++i)
2170 BitsSet += Writemask & (1 << i) ? 1 : 0;
2172 const TargetRegisterClass *RC;
2175 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2176 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2177 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2180 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2181 MI->setDesc(TII->get(NewOpcode));
2182 MRI.setRegClass(VReg, RC);
2186 // Replace unused atomics with the no return version.
2187 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2188 if (NoRetAtomicOp != -1) {
2189 if (!Node->hasAnyUseOfValue(0)) {
2190 MI->setDesc(TII->get(NoRetAtomicOp));
2191 MI->RemoveOperand(0);
2198 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2199 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2200 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2203 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2205 SDValue Ptr) const {
2206 const SIInstrInfo *TII =
2207 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2209 // XXX - Workaround for moveToVALU not handling different register class
2210 // inserts for REG_SEQUENCE.
2212 // Build the half of the subregister with the constants.
2213 const SDValue Ops0[] = {
2214 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2215 buildSMovImm32(DAG, DL, 0),
2216 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2217 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2218 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2221 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2222 MVT::v2i32, Ops0), 0);
2224 // Combine the constants and the pointer.
2225 const SDValue Ops1[] = {
2226 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2228 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2230 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2233 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2235 const SDValue Ops[] = {
2236 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2238 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2239 buildSMovImm32(DAG, DL, 0),
2240 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2241 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2242 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2245 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2250 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2251 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2252 /// of the resource descriptor) to create an offset, which is added to
2253 /// the resource pointer.
2254 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2257 uint32_t RsrcDword1,
2258 uint64_t RsrcDword2And3) const {
2259 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2260 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2262 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2263 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2267 SDValue DataLo = buildSMovImm32(DAG, DL,
2268 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2269 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2271 const SDValue Ops[] = {
2272 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2274 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2276 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2278 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2280 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2283 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2286 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2288 SDValue Ptr) const {
2289 const SIInstrInfo *TII =
2290 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2291 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2294 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2297 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2298 const TargetRegisterClass *RC,
2299 unsigned Reg, EVT VT) const {
2300 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2302 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2303 cast<RegisterSDNode>(VReg)->getReg(), VT);
2306 //===----------------------------------------------------------------------===//
2307 // SI Inline Assembly Support
2308 //===----------------------------------------------------------------------===//
2310 std::pair<unsigned, const TargetRegisterClass *>
2311 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2312 StringRef Constraint,
2314 if (Constraint == "r") {
2315 switch(VT.SimpleTy) {
2316 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2318 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2320 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2324 if (Constraint.size() > 1) {
2325 const TargetRegisterClass *RC = nullptr;
2326 if (Constraint[1] == 'v') {
2327 RC = &AMDGPU::VGPR_32RegClass;
2328 } else if (Constraint[1] == 's') {
2329 RC = &AMDGPU::SGPR_32RegClass;
2334 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2335 if (!Failed && Idx < RC->getNumRegs())
2336 return std::make_pair(RC->getRegister(Idx), RC);
2339 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);