1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "SIISelLowering.h"
23 #include "AMDGPUDiagnosticInfoUnsupported.h"
24 #include "AMDGPUIntrinsicInfo.h"
25 #include "AMDGPUSubtarget.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/ADT/SmallString.h"
39 SITargetLowering::SITargetLowering(TargetMachine &TM,
40 const AMDGPUSubtarget &STI)
41 : AMDGPUTargetLowering(TM, STI) {
42 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
43 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
45 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
46 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
48 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
49 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
51 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
52 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
53 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
55 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
56 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
58 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
59 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
61 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
62 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
64 computeRegisterProperties(STI.getRegisterInfo());
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
69 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
71 setOperationAction(ISD::ADD, MVT::i32, Legal);
72 setOperationAction(ISD::ADDC, MVT::i32, Legal);
73 setOperationAction(ISD::ADDE, MVT::i32, Legal);
74 setOperationAction(ISD::SUBC, MVT::i32, Legal);
75 setOperationAction(ISD::SUBE, MVT::i32, Legal);
77 setOperationAction(ISD::FSIN, MVT::f32, Custom);
78 setOperationAction(ISD::FCOS, MVT::f32, Custom);
80 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
81 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
83 // We need to custom lower vector stores from local memory
84 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
88 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
91 setOperationAction(ISD::STORE, MVT::i1, Custom);
92 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
94 setOperationAction(ISD::SELECT, MVT::i64, Custom);
95 setOperationAction(ISD::SELECT, MVT::f64, Promote);
96 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
98 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
99 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
100 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
101 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
103 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
104 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
106 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
108 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
109 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
110 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
123 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
124 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
128 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
129 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
131 for (MVT VT : MVT::integer_valuetypes()) {
135 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
138 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
140 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
143 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
145 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
148 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
151 for (MVT VT : MVT::integer_vector_valuetypes()) {
152 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
153 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
156 for (MVT VT : MVT::fp_valuetypes())
157 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
159 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
160 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
161 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
162 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
164 setOperationAction(ISD::LOAD, MVT::i1, Custom);
166 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
167 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
168 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
170 // These should use UDIVREM, so set them to expand
171 setOperationAction(ISD::UDIV, MVT::i64, Expand);
172 setOperationAction(ISD::UREM, MVT::i64, Expand);
174 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
175 setOperationAction(ISD::SELECT, MVT::i1, Promote);
177 // We only support LOAD/STORE and vector manipulation ops for vectors
178 // with > 4 elements.
179 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}) {
180 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
184 case ISD::BUILD_VECTOR:
186 case ISD::EXTRACT_VECTOR_ELT:
187 case ISD::INSERT_VECTOR_ELT:
188 case ISD::INSERT_SUBVECTOR:
189 case ISD::EXTRACT_SUBVECTOR:
191 case ISD::CONCAT_VECTORS:
192 setOperationAction(Op, VT, Custom);
195 setOperationAction(Op, VT, Expand);
201 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
202 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
203 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
204 setOperationAction(ISD::FRINT, MVT::f64, Legal);
207 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
208 setOperationAction(ISD::FDIV, MVT::f32, Custom);
209 setOperationAction(ISD::FDIV, MVT::f64, Custom);
211 setTargetDAGCombine(ISD::FADD);
212 setTargetDAGCombine(ISD::FSUB);
213 setTargetDAGCombine(ISD::FMINNUM);
214 setTargetDAGCombine(ISD::FMAXNUM);
215 setTargetDAGCombine(ISD::SMIN);
216 setTargetDAGCombine(ISD::SMAX);
217 setTargetDAGCombine(ISD::UMIN);
218 setTargetDAGCombine(ISD::UMAX);
219 setTargetDAGCombine(ISD::SELECT_CC);
220 setTargetDAGCombine(ISD::SETCC);
221 setTargetDAGCombine(ISD::AND);
222 setTargetDAGCombine(ISD::OR);
223 setTargetDAGCombine(ISD::UINT_TO_FP);
225 // All memory operations. Some folding on the pointer operand is done to help
226 // matching the constant offsets in the addressing modes.
227 setTargetDAGCombine(ISD::LOAD);
228 setTargetDAGCombine(ISD::STORE);
229 setTargetDAGCombine(ISD::ATOMIC_LOAD);
230 setTargetDAGCombine(ISD::ATOMIC_STORE);
231 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
232 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
233 setTargetDAGCombine(ISD::ATOMIC_SWAP);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
245 setSchedulingPreference(Sched::RegPressure);
248 //===----------------------------------------------------------------------===//
249 // TargetLowering queries
250 //===----------------------------------------------------------------------===//
252 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
254 // SI has some legal vector types, but no legal vector operations. Say no
255 // shuffles are legal in order to prefer scalarizing some vector operations.
259 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
260 // Flat instructions do not have offsets, and only have the register
262 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
265 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
266 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
267 // additionally can do r + r + i with addr64. 32-bit has more addressing
268 // mode options. Depending on the resource constant, it can also do
269 // (i64 r0) + (i32 r1) * (i14 i).
271 // Private arrays end up using a scratch buffer most of the time, so also
272 // assume those use MUBUF instructions. Scratch loads / stores are currently
273 // implemented as mubuf instructions with offen bit set, so slightly
274 // different than the normal addr64.
275 if (!isUInt<12>(AM.BaseOffs))
278 // FIXME: Since we can split immediate into soffset and immediate offset,
279 // would it make sense to allow any immediate?
282 case 0: // r + i or just i, depending on HasBaseReg.
285 return true; // We have r + r or r + i.
292 // Allow 2 * r as r + r
293 // Or 2 * r + i is allowed as r + r + i.
295 default: // Don't allow n * r
300 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
301 const AddrMode &AM, Type *Ty,
303 // No global is ever allowed as a base.
308 case AMDGPUAS::GLOBAL_ADDRESS: {
309 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
310 // Assume the we will use FLAT for all global memory accesses
312 // FIXME: This assumption is currently wrong. On VI we still use
313 // MUBUF instructions for the r + i addressing mode. As currently
314 // implemented, the MUBUF instructions only work on buffer < 4GB.
315 // It may be possible to support > 4GB buffers with MUBUF instructions,
316 // by setting the stride value in the resource descriptor which would
317 // increase the size limit to (stride * 4GB). However, this is risky,
318 // because it has never been validated.
319 return isLegalFlatAddressingMode(AM);
322 return isLegalMUBUFAddressingMode(AM);
324 case AMDGPUAS::CONSTANT_ADDRESS: {
325 // If the offset isn't a multiple of 4, it probably isn't going to be
326 // correctly aligned.
327 if (AM.BaseOffs % 4 != 0)
328 return isLegalMUBUFAddressingMode(AM);
330 // There are no SMRD extloads, so if we have to do a small type access we
331 // will use a MUBUF load.
332 // FIXME?: We also need to do this if unaligned, but we don't know the
334 if (DL.getTypeStoreSize(Ty) < 4)
335 return isLegalMUBUFAddressingMode(AM);
337 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
338 // SMRD instructions have an 8-bit, dword offset on SI.
339 if (!isUInt<8>(AM.BaseOffs / 4))
341 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
342 // On CI+, this can also be a 32-bit literal constant offset. If it fits
343 // in 8-bits, it can use a smaller encoding.
344 if (!isUInt<32>(AM.BaseOffs / 4))
346 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
347 // On VI, these use the SMEM format and the offset is 20-bit in bytes.
348 if (!isUInt<20>(AM.BaseOffs))
351 llvm_unreachable("unhandled generation");
353 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
356 if (AM.Scale == 1 && AM.HasBaseReg)
362 case AMDGPUAS::PRIVATE_ADDRESS:
363 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
364 return isLegalMUBUFAddressingMode(AM);
366 case AMDGPUAS::LOCAL_ADDRESS:
367 case AMDGPUAS::REGION_ADDRESS: {
368 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
370 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
371 // an 8-bit dword offset but we don't know the alignment here.
372 if (!isUInt<16>(AM.BaseOffs))
375 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
378 if (AM.Scale == 1 && AM.HasBaseReg)
383 case AMDGPUAS::FLAT_ADDRESS:
384 return isLegalFlatAddressingMode(AM);
387 llvm_unreachable("unhandled address space");
391 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
394 bool *IsFast) const {
398 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
399 // which isn't a simple VT.
400 if (!VT.isSimple() || VT == MVT::Other)
403 // TODO - CI+ supports unaligned memory accesses, but this requires driver
406 // XXX - The only mention I see of this in the ISA manual is for LDS direct
407 // reads the "byte address and must be dword aligned". Is it also true for the
408 // normal loads and stores?
409 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
410 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
411 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
412 // with adjacent offsets.
413 bool AlignedBy4 = (Align % 4 == 0);
415 *IsFast = AlignedBy4;
419 // Smaller than dword value must be aligned.
420 // FIXME: This should be allowed on CI+
421 if (VT.bitsLT(MVT::i32))
424 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
425 // byte-address are ignored, thus forcing Dword alignment.
426 // This applies to private, global, and constant memory.
430 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
433 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
434 unsigned SrcAlign, bool IsMemset,
437 MachineFunction &MF) const {
438 // FIXME: Should account for address space here.
440 // The default fallback uses the private pointer size as a guess for a type to
441 // use. Make sure we switch these to 64-bit accesses.
443 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
446 if (Size >= 8 && DstAlign >= 4)
453 TargetLoweringBase::LegalizeTypeAction
454 SITargetLowering::getPreferredVectorAction(EVT VT) const {
455 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
456 return TypeSplitVector;
458 return TargetLoweringBase::getPreferredVectorAction(VT);
461 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
463 const SIInstrInfo *TII =
464 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
465 return TII->isInlineConstant(Imm);
468 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
469 SDLoc SL, SDValue Chain,
470 unsigned Offset, bool Signed) const {
471 const DataLayout &DL = DAG.getDataLayout();
472 MachineFunction &MF = DAG.getMachineFunction();
473 const SIRegisterInfo *TRI =
474 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
475 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
477 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
479 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
480 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
481 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
482 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
483 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
484 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
485 DAG.getConstant(Offset, SL, PtrVT));
486 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
487 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
489 unsigned Align = DL.getABITypeAlignment(Ty);
491 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
492 if (MemVT.isFloatingPoint())
493 ExtTy = ISD::EXTLOAD;
495 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
496 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
498 true, // isNonTemporal
503 SDValue SITargetLowering::LowerFormalArguments(
504 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
505 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
506 SmallVectorImpl<SDValue> &InVals) const {
507 const SIRegisterInfo *TRI =
508 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
510 MachineFunction &MF = DAG.getMachineFunction();
511 FunctionType *FType = MF.getFunction()->getFunctionType();
512 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
514 if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) {
515 const Function *Fn = MF.getFunction();
516 DiagnosticInfoUnsupported NoGraphicsHSA(*Fn, "non-compute shaders with HSA");
517 DAG.getContext()->diagnose(NoGraphicsHSA);
521 // FIXME: We currently assume all calling conventions are kernels.
523 SmallVector<ISD::InputArg, 16> Splits;
524 BitVector Skipped(Ins.size());
526 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
527 const ISD::InputArg &Arg = Ins[i];
529 // First check if it's a PS input addr
530 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
531 !Arg.Flags.isByVal()) {
533 assert((PSInputNum <= 15) && "Too many PS inputs!");
536 // We can safely skip PS inputs
542 Info->PSInputAddr |= 1 << PSInputNum++;
545 // Second split vertices into their elements
546 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
547 ISD::InputArg NewArg = Arg;
548 NewArg.Flags.setSplit();
549 NewArg.VT = Arg.VT.getVectorElementType();
551 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
552 // three or five element vertex only needs three or five registers,
553 // NOT four or eight.
554 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
555 unsigned NumElements = ParamType->getVectorNumElements();
557 for (unsigned j = 0; j != NumElements; ++j) {
558 Splits.push_back(NewArg);
559 NewArg.PartOffset += NewArg.VT.getStoreSize();
562 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
563 Splits.push_back(Arg);
567 SmallVector<CCValAssign, 16> ArgLocs;
568 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
571 // At least one interpolation mode must be enabled or else the GPU will hang.
572 if (Info->getShaderType() == ShaderType::PIXEL &&
573 (Info->PSInputAddr & 0x7F) == 0) {
574 Info->PSInputAddr |= 1;
575 CCInfo.AllocateReg(AMDGPU::VGPR0);
576 CCInfo.AllocateReg(AMDGPU::VGPR1);
579 // The pointer to the list of arguments is stored in SGPR0, SGPR1
580 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
581 if (Info->getShaderType() == ShaderType::COMPUTE) {
582 if (Subtarget->isAmdHsaOS())
583 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
585 Info->NumUserSGPRs = 4;
587 unsigned InputPtrReg =
588 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
589 unsigned InputPtrRegLo =
590 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
591 unsigned InputPtrRegHi =
592 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
594 unsigned ScratchPtrReg =
595 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
596 unsigned ScratchPtrRegLo =
597 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
598 unsigned ScratchPtrRegHi =
599 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
601 CCInfo.AllocateReg(InputPtrRegLo);
602 CCInfo.AllocateReg(InputPtrRegHi);
603 CCInfo.AllocateReg(ScratchPtrRegLo);
604 CCInfo.AllocateReg(ScratchPtrRegHi);
605 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
606 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
609 if (Info->getShaderType() == ShaderType::COMPUTE) {
610 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
614 AnalyzeFormalArguments(CCInfo, Splits);
616 SmallVector<SDValue, 16> Chains;
618 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
620 const ISD::InputArg &Arg = Ins[i];
622 InVals.push_back(DAG.getUNDEF(Arg.VT));
626 CCValAssign &VA = ArgLocs[ArgIdx++];
627 MVT VT = VA.getLocVT();
631 EVT MemVT = Splits[i].VT;
632 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
633 VA.getLocMemOffset();
634 // The first 36 bytes of the input buffer contains information about
635 // thread group and global sizes.
636 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
637 Offset, Ins[i].Flags.isSExt());
638 Chains.push_back(Arg.getValue(1));
641 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
642 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
643 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
644 // On SI local pointers are just offsets into LDS, so they are always
645 // less than 16-bits. On CI and newer they could potentially be
646 // real pointers, so we can't guarantee their size.
647 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
648 DAG.getValueType(MVT::i16));
651 InVals.push_back(Arg);
652 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
655 assert(VA.isRegLoc() && "Parameter must be in a register!");
657 unsigned Reg = VA.getLocReg();
659 if (VT == MVT::i64) {
660 // For now assume it is a pointer
661 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
662 &AMDGPU::SReg_64RegClass);
663 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
664 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
665 InVals.push_back(Copy);
669 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
671 Reg = MF.addLiveIn(Reg, RC);
672 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
674 if (Arg.VT.isVector()) {
676 // Build a vector from the registers
677 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
678 unsigned NumElements = ParamType->getVectorNumElements();
680 SmallVector<SDValue, 4> Regs;
682 for (unsigned j = 1; j != NumElements; ++j) {
683 Reg = ArgLocs[ArgIdx++].getLocReg();
684 Reg = MF.addLiveIn(Reg, RC);
686 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
687 Regs.push_back(Copy);
690 // Fill up the missing vector elements
691 NumElements = Arg.VT.getVectorNumElements() - NumElements;
692 Regs.append(NumElements, DAG.getUNDEF(VT));
694 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
698 InVals.push_back(Val);
701 if (Info->getShaderType() != ShaderType::COMPUTE) {
702 unsigned ScratchIdx = CCInfo.getFirstUnallocated(makeArrayRef(
703 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
704 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
710 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
713 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
714 MachineInstr * MI, MachineBasicBlock * BB) const {
716 MachineBasicBlock::iterator I = *MI;
717 const SIInstrInfo *TII =
718 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
720 switch (MI->getOpcode()) {
722 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
725 case AMDGPU::SI_RegisterStorePseudo: {
726 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
727 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
728 MachineInstrBuilder MIB =
729 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
731 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
732 MIB.addOperand(MI->getOperand(i));
734 MI->eraseFromParent();
741 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
742 // This currently forces unfolding various combinations of fsub into fma with
743 // free fneg'd operands. As long as we have fast FMA (controlled by
744 // isFMAFasterThanFMulAndFAdd), we should perform these.
746 // When fma is quarter rate, for f64 where add / sub are at best half rate,
747 // most of these combines appear to be cycle neutral but save on instruction
748 // count / code size.
752 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
754 if (!VT.isVector()) {
757 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
760 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
764 // Answering this is somewhat tricky and depends on the specific device which
765 // have different rates for fma or all f64 operations.
767 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
768 // regardless of which device (although the number of cycles differs between
769 // devices), so it is always profitable for f64.
771 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
772 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
773 // which we can always do even without fused FP ops since it returns the same
774 // result as the separate operations and since it is always full
775 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
776 // however does not support denormals, so we do report fma as faster if we have
777 // a fast fma device and require denormals.
779 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
780 VT = VT.getScalarType();
785 switch (VT.getSimpleVT().SimpleTy) {
787 // This is as fast on some subtargets. However, we always have full rate f32
788 // mad available which returns the same result as the separate operations
789 // which we should prefer over fma. We can't use this if we want to support
790 // denormals, so only report this in these cases.
791 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
801 //===----------------------------------------------------------------------===//
802 // Custom DAG Lowering Operations
803 //===----------------------------------------------------------------------===//
805 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
806 switch (Op.getOpcode()) {
807 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
808 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
809 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
811 SDValue Result = LowerLOAD(Op, DAG);
812 assert((!Result.getNode() ||
813 Result.getNode()->getNumValues() == 2) &&
814 "Load should return a value and a chain");
820 return LowerTrig(Op, DAG);
821 case ISD::SELECT: return LowerSELECT(Op, DAG);
822 case ISD::FDIV: return LowerFDIV(Op, DAG);
823 case ISD::STORE: return LowerSTORE(Op, DAG);
824 case ISD::GlobalAddress: {
825 MachineFunction &MF = DAG.getMachineFunction();
826 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
827 return LowerGlobalAddress(MFI, Op, DAG);
829 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
830 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
835 /// \brief Helper function for LowerBRCOND
836 static SDNode *findUser(SDValue Value, unsigned Opcode) {
838 SDNode *Parent = Value.getNode();
839 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
842 if (I.getUse().get() != Value)
845 if (I->getOpcode() == Opcode)
851 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
854 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
855 unsigned FrameIndex = FINode->getIndex();
857 // A FrameIndex node represents a 32-bit offset into scratch memory. If
858 // the high bit of a frame index offset were to be set, this would mean
859 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
860 // scratch buffer, with 64 being the number of threads per wave.
862 // If we know the machine uses less than 128GB of scratch, then we can
863 // amrk the high bit of the FrameIndex node as known zero,
864 // which is important, because it means in most situations we can
865 // prove that values derived from FrameIndex nodes are non-negative.
866 // This enables us to take advantage of more addressing modes when
867 // accessing scratch buffers, since for scratch reads/writes, the register
868 // offset must always be positive.
870 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
871 if (Subtarget->enableHugeScratchBuffer())
874 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
875 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
878 /// This transforms the control flow intrinsics to get the branch destination as
879 /// last parameter, also switches branch target with BR if the need arise
880 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
881 SelectionDAG &DAG) const {
885 SDNode *Intr = BRCOND.getOperand(1).getNode();
886 SDValue Target = BRCOND.getOperand(2);
887 SDNode *BR = nullptr;
889 if (Intr->getOpcode() == ISD::SETCC) {
890 // As long as we negate the condition everything is fine
891 SDNode *SetCC = Intr;
892 assert(SetCC->getConstantOperandVal(1) == 1);
893 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
895 Intr = SetCC->getOperand(0).getNode();
898 // Get the target from BR if we don't negate the condition
899 BR = findUser(BRCOND, ISD::BR);
900 Target = BR->getOperand(1);
903 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
905 // Build the result and
906 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
908 // operands of the new intrinsic call
909 SmallVector<SDValue, 4> Ops;
910 Ops.push_back(BRCOND.getOperand(0));
911 Ops.append(Intr->op_begin() + 1, Intr->op_end());
912 Ops.push_back(Target);
914 // build the new intrinsic call
915 SDNode *Result = DAG.getNode(
916 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
917 DAG.getVTList(Res), Ops).getNode();
920 // Give the branch instruction our target
925 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
926 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
927 BR = NewBR.getNode();
930 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
932 // Copy the intrinsic results to registers
933 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
934 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
938 Chain = DAG.getCopyToReg(
940 CopyToReg->getOperand(1),
941 SDValue(Result, i - 1),
944 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
947 // Remove the old intrinsic from the chain
948 DAG.ReplaceAllUsesOfValueWith(
949 SDValue(Intr, Intr->getNumValues() - 1),
950 Intr->getOperand(0));
955 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
957 SelectionDAG &DAG) const {
958 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
960 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
961 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
964 const GlobalValue *GV = GSD->getGlobal();
965 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
967 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
968 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
970 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
971 DAG.getConstant(0, DL, MVT::i32));
972 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
973 DAG.getConstant(1, DL, MVT::i32));
975 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
977 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
978 PtrHi, DAG.getConstant(0, DL, MVT::i32),
979 SDValue(Lo.getNode(), 1));
980 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
983 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
985 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
986 // so we will end up with redundant moves to m0.
988 // We can't use S_MOV_B32, because there is no way to specify m0 as the
989 // destination register.
991 // We have to use them both. Machine cse will combine all the S_MOV_B32
992 // instructions and the register coalescer eliminate the extra copies.
993 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
994 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
995 SDValue(M0, 0), SDValue()); // Glue
996 // A Null SDValue creates
1000 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1001 SelectionDAG &DAG) const {
1002 MachineFunction &MF = DAG.getMachineFunction();
1003 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1004 const SIRegisterInfo *TRI =
1005 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1007 EVT VT = Op.getValueType();
1009 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1011 // TODO: Should this propagate fast-math-flags?
1013 switch (IntrinsicID) {
1014 case Intrinsic::r600_read_ngroups_x:
1015 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1016 SI::KernelInputOffsets::NGROUPS_X, false);
1017 case Intrinsic::r600_read_ngroups_y:
1018 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1019 SI::KernelInputOffsets::NGROUPS_Y, false);
1020 case Intrinsic::r600_read_ngroups_z:
1021 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1022 SI::KernelInputOffsets::NGROUPS_Z, false);
1023 case Intrinsic::r600_read_global_size_x:
1024 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1025 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1026 case Intrinsic::r600_read_global_size_y:
1027 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1028 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1029 case Intrinsic::r600_read_global_size_z:
1030 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1031 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1032 case Intrinsic::r600_read_local_size_x:
1033 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1034 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
1035 case Intrinsic::r600_read_local_size_y:
1036 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1037 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
1038 case Intrinsic::r600_read_local_size_z:
1039 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1040 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
1042 case Intrinsic::AMDGPU_read_workdim:
1043 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1044 getImplicitParameterOffset(MFI, GRID_DIM), false);
1046 case Intrinsic::r600_read_tgid_x:
1047 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1048 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
1049 case Intrinsic::r600_read_tgid_y:
1050 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1051 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
1052 case Intrinsic::r600_read_tgid_z:
1053 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1054 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
1055 case Intrinsic::r600_read_tidig_x:
1056 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1057 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
1058 case Intrinsic::r600_read_tidig_y:
1059 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1060 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
1061 case Intrinsic::r600_read_tidig_z:
1062 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1063 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
1064 case AMDGPUIntrinsic::SI_load_const: {
1070 MachineMemOperand *MMO = MF.getMachineMemOperand(
1071 MachinePointerInfo(),
1072 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1073 VT.getStoreSize(), 4);
1074 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1075 Op->getVTList(), Ops, VT, MMO);
1077 case AMDGPUIntrinsic::SI_sample:
1078 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1079 case AMDGPUIntrinsic::SI_sampleb:
1080 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1081 case AMDGPUIntrinsic::SI_sampled:
1082 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1083 case AMDGPUIntrinsic::SI_samplel:
1084 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1085 case AMDGPUIntrinsic::SI_vs_load_input:
1086 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1091 case AMDGPUIntrinsic::AMDGPU_fract:
1092 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1093 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1094 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1095 case AMDGPUIntrinsic::SI_fs_constant: {
1096 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1097 SDValue Glue = M0.getValue(1);
1098 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1099 DAG.getConstant(2, DL, MVT::i32), // P0
1100 Op.getOperand(1), Op.getOperand(2), Glue);
1102 case AMDGPUIntrinsic::SI_packf16:
1103 if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1104 return DAG.getUNDEF(MVT::i32);
1106 case AMDGPUIntrinsic::SI_fs_interp: {
1107 SDValue IJ = Op.getOperand(4);
1108 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1109 DAG.getConstant(0, DL, MVT::i32));
1110 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1111 DAG.getConstant(1, DL, MVT::i32));
1112 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1113 SDValue Glue = M0.getValue(1);
1114 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1115 DAG.getVTList(MVT::f32, MVT::Glue),
1116 I, Op.getOperand(1), Op.getOperand(2), Glue);
1117 Glue = SDValue(P1.getNode(), 1);
1118 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1119 Op.getOperand(1), Op.getOperand(2), Glue);
1122 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1126 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1127 SelectionDAG &DAG) const {
1128 MachineFunction &MF = DAG.getMachineFunction();
1130 SDValue Chain = Op.getOperand(0);
1131 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1133 switch (IntrinsicID) {
1134 case AMDGPUIntrinsic::SI_sendmsg: {
1135 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1136 SDValue Glue = Chain.getValue(1);
1137 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1138 Op.getOperand(2), Glue);
1140 case AMDGPUIntrinsic::SI_tbuffer_store: {
1158 EVT VT = Op.getOperand(3).getValueType();
1160 MachineMemOperand *MMO = MF.getMachineMemOperand(
1161 MachinePointerInfo(),
1162 MachineMemOperand::MOStore,
1163 VT.getStoreSize(), 4);
1164 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1165 Op->getVTList(), Ops, VT, MMO);
1172 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1174 LoadSDNode *Load = cast<LoadSDNode>(Op);
1176 if (Op.getValueType().isVector()) {
1177 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1178 "Custom lowering for non-i32 vectors hasn't been implemented.");
1179 unsigned NumElements = Op.getValueType().getVectorNumElements();
1180 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1182 switch (Load->getAddressSpace()) {
1184 case AMDGPUAS::GLOBAL_ADDRESS:
1185 case AMDGPUAS::PRIVATE_ADDRESS:
1186 if (NumElements >= 8)
1187 return SplitVectorLoad(Op, DAG);
1189 // v4 loads are supported for private and global memory.
1190 if (NumElements <= 4)
1193 case AMDGPUAS::LOCAL_ADDRESS:
1194 // If properly aligned, if we split we might be able to use ds_read_b64.
1195 return SplitVectorLoad(Op, DAG);
1199 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1202 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1204 SelectionDAG &DAG) const {
1205 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1211 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1212 if (Op.getValueType() != MVT::i64)
1216 SDValue Cond = Op.getOperand(0);
1218 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1219 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1221 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1222 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1224 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1225 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1227 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1229 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1230 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1232 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1234 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1235 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1238 // Catch division cases where we can use shortcuts with rcp and rsq
1240 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1242 SDValue LHS = Op.getOperand(0);
1243 SDValue RHS = Op.getOperand(1);
1244 EVT VT = Op.getValueType();
1245 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1247 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1248 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1249 CLHS->isExactlyValue(1.0)) {
1250 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1251 // the CI documentation has a worst case error of 1 ulp.
1252 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1253 // use it as long as we aren't trying to use denormals.
1255 // 1.0 / sqrt(x) -> rsq(x)
1257 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1258 // error seems really high at 2^29 ULP.
1259 if (RHS.getOpcode() == ISD::FSQRT)
1260 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1262 // 1.0 / x -> rcp(x)
1263 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1268 // Turn into multiply by the reciprocal.
1269 // x / y -> x * (1.0 / y)
1271 Flags.setUnsafeAlgebra(true);
1272 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1273 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1279 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1280 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1281 if (FastLowered.getNode())
1284 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1285 // selection error for now rather than do something incorrect.
1286 if (Subtarget->hasFP32Denormals())
1290 SDValue LHS = Op.getOperand(0);
1291 SDValue RHS = Op.getOperand(1);
1293 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1295 const APFloat K0Val(BitsToFloat(0x6f800000));
1296 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1298 const APFloat K1Val(BitsToFloat(0x2f800000));
1299 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1301 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1304 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1306 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1308 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1310 // TODO: Should this propagate fast-math-flags?
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 SplitVectorStore(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 // TODO: Should this propagate fast-math-flags?
1432 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1433 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1434 DAG.getConstantFP(0.5/M_PI, DL,
1437 switch (Op.getOpcode()) {
1439 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1441 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1443 llvm_unreachable("Wrong trig opcode");
1447 //===----------------------------------------------------------------------===//
1448 // Custom DAG optimizations
1449 //===----------------------------------------------------------------------===//
1451 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1452 DAGCombinerInfo &DCI) const {
1453 EVT VT = N->getValueType(0);
1454 EVT ScalarVT = VT.getScalarType();
1455 if (ScalarVT != MVT::f32)
1458 SelectionDAG &DAG = DCI.DAG;
1461 SDValue Src = N->getOperand(0);
1462 EVT SrcVT = Src.getValueType();
1464 // TODO: We could try to match extracting the higher bytes, which would be
1465 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1466 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1467 // about in practice.
1468 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1469 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1470 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1471 DCI.AddToWorklist(Cvt.getNode());
1476 // We are primarily trying to catch operations on illegal vector types
1477 // before they are expanded.
1478 // For scalars, we can use the more flexible method of checking masked bits
1479 // after legalization.
1480 if (!DCI.isBeforeLegalize() ||
1481 !SrcVT.isVector() ||
1482 SrcVT.getVectorElementType() != MVT::i8) {
1486 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1488 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1490 unsigned NElts = SrcVT.getVectorNumElements();
1491 if (!SrcVT.isSimple() && NElts != 3)
1494 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1495 // prevent a mess from expanding to v4i32 and repacking.
1496 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1497 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1498 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1499 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1500 LoadSDNode *Load = cast<LoadSDNode>(Src);
1502 unsigned AS = Load->getAddressSpace();
1503 unsigned Align = Load->getAlignment();
1504 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1505 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1507 // Don't try to replace the load if we have to expand it due to alignment
1508 // problems. Otherwise we will end up scalarizing the load, and trying to
1509 // repack into the vector for no real reason.
1510 if (Align < ABIAlignment &&
1511 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1515 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1519 Load->getMemOperand());
1521 // Make sure successors of the original load stay after it by updating
1522 // them to use the new Chain.
1523 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1525 SmallVector<SDValue, 4> Elts;
1526 if (RegVT.isVector())
1527 DAG.ExtractVectorElements(NewLoad, Elts);
1529 Elts.push_back(NewLoad);
1531 SmallVector<SDValue, 4> Ops;
1533 unsigned EltIdx = 0;
1534 for (SDValue Elt : Elts) {
1535 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1536 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1537 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1538 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1539 DCI.AddToWorklist(Cvt.getNode());
1546 assert(Ops.size() == NElts);
1548 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1554 /// \brief Return true if the given offset Size in bytes can be folded into
1555 /// the immediate offsets of a memory instruction for the given address space.
1556 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1557 const AMDGPUSubtarget &STI) {
1559 case AMDGPUAS::GLOBAL_ADDRESS: {
1560 // MUBUF instructions a 12-bit offset in bytes.
1561 return isUInt<12>(OffsetSize);
1563 case AMDGPUAS::CONSTANT_ADDRESS: {
1564 // SMRD instructions have an 8-bit offset in dwords on SI and
1565 // a 20-bit offset in bytes on VI.
1566 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1567 return isUInt<20>(OffsetSize);
1569 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1571 case AMDGPUAS::LOCAL_ADDRESS:
1572 case AMDGPUAS::REGION_ADDRESS: {
1573 // The single offset versions have a 16-bit offset in bytes.
1574 return isUInt<16>(OffsetSize);
1576 case AMDGPUAS::PRIVATE_ADDRESS:
1577 // Indirect register addressing does not use any offsets.
1583 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1585 // This is a variant of
1586 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1588 // The normal DAG combiner will do this, but only if the add has one use since
1589 // that would increase the number of instructions.
1591 // This prevents us from seeing a constant offset that can be folded into a
1592 // memory instruction's addressing mode. If we know the resulting add offset of
1593 // a pointer can be folded into an addressing offset, we can replace the pointer
1594 // operand with the add of new constant offset. This eliminates one of the uses,
1595 // and may allow the remaining use to also be simplified.
1597 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1599 DAGCombinerInfo &DCI) const {
1600 SDValue N0 = N->getOperand(0);
1601 SDValue N1 = N->getOperand(1);
1603 if (N0.getOpcode() != ISD::ADD)
1606 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1610 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1614 // If the resulting offset is too large, we can't fold it into the addressing
1616 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1617 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1620 SelectionDAG &DAG = DCI.DAG;
1622 EVT VT = N->getValueType(0);
1624 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1625 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1627 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1630 SDValue SITargetLowering::performAndCombine(SDNode *N,
1631 DAGCombinerInfo &DCI) const {
1632 if (DCI.isBeforeLegalize())
1635 SelectionDAG &DAG = DCI.DAG;
1637 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1638 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1639 SDValue LHS = N->getOperand(0);
1640 SDValue RHS = N->getOperand(1);
1642 if (LHS.getOpcode() == ISD::SETCC &&
1643 RHS.getOpcode() == ISD::SETCC) {
1644 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1645 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1647 SDValue X = LHS.getOperand(0);
1648 SDValue Y = RHS.getOperand(0);
1649 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1652 if (LCC == ISD::SETO) {
1653 if (X != LHS.getOperand(1))
1656 if (RCC == ISD::SETUNE) {
1657 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1658 if (!C1 || !C1->isInfinity() || C1->isNegative())
1661 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1662 SIInstrFlags::N_SUBNORMAL |
1663 SIInstrFlags::N_ZERO |
1664 SIInstrFlags::P_ZERO |
1665 SIInstrFlags::P_SUBNORMAL |
1666 SIInstrFlags::P_NORMAL;
1668 static_assert(((~(SIInstrFlags::S_NAN |
1669 SIInstrFlags::Q_NAN |
1670 SIInstrFlags::N_INFINITY |
1671 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1675 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1676 X, DAG.getConstant(Mask, DL, MVT::i32));
1684 SDValue SITargetLowering::performOrCombine(SDNode *N,
1685 DAGCombinerInfo &DCI) const {
1686 SelectionDAG &DAG = DCI.DAG;
1687 SDValue LHS = N->getOperand(0);
1688 SDValue RHS = N->getOperand(1);
1690 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1691 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1692 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1693 SDValue Src = LHS.getOperand(0);
1694 if (Src != RHS.getOperand(0))
1697 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1698 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1702 // Only 10 bits are used.
1703 static const uint32_t MaxMask = 0x3ff;
1705 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1707 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1708 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1714 SDValue SITargetLowering::performClassCombine(SDNode *N,
1715 DAGCombinerInfo &DCI) const {
1716 SelectionDAG &DAG = DCI.DAG;
1717 SDValue Mask = N->getOperand(1);
1719 // fp_class x, 0 -> false
1720 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1721 if (CMask->isNullValue())
1722 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1728 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1731 return AMDGPUISD::FMAX3;
1733 return AMDGPUISD::SMAX3;
1735 return AMDGPUISD::UMAX3;
1737 return AMDGPUISD::FMIN3;
1739 return AMDGPUISD::SMIN3;
1741 return AMDGPUISD::UMIN3;
1743 llvm_unreachable("Not a min/max opcode");
1747 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1748 DAGCombinerInfo &DCI) const {
1749 SelectionDAG &DAG = DCI.DAG;
1751 unsigned Opc = N->getOpcode();
1752 SDValue Op0 = N->getOperand(0);
1753 SDValue Op1 = N->getOperand(1);
1755 // Only do this if the inner op has one use since this will just increases
1756 // register pressure for no benefit.
1758 // max(max(a, b), c)
1759 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1761 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1769 // max(a, max(b, c))
1770 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1772 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1783 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1784 DAGCombinerInfo &DCI) const {
1785 SelectionDAG &DAG = DCI.DAG;
1788 SDValue LHS = N->getOperand(0);
1789 SDValue RHS = N->getOperand(1);
1790 EVT VT = LHS.getValueType();
1792 if (VT != MVT::f32 && VT != MVT::f64)
1795 // Match isinf pattern
1796 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1797 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1798 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1799 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1803 const APFloat &APF = CRHS->getValueAPF();
1804 if (APF.isInfinity() && !APF.isNegative()) {
1805 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1806 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1807 DAG.getConstant(Mask, SL, MVT::i32));
1814 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1815 DAGCombinerInfo &DCI) const {
1816 SelectionDAG &DAG = DCI.DAG;
1819 switch (N->getOpcode()) {
1821 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1823 return performSetCCCombine(N, DCI);
1824 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1830 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1831 N->getValueType(0) != MVT::f64 &&
1832 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1833 return performMin3Max3Combine(N, DCI);
1837 case AMDGPUISD::CVT_F32_UBYTE0:
1838 case AMDGPUISD::CVT_F32_UBYTE1:
1839 case AMDGPUISD::CVT_F32_UBYTE2:
1840 case AMDGPUISD::CVT_F32_UBYTE3: {
1841 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1843 SDValue Src = N->getOperand(0);
1844 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1846 APInt KnownZero, KnownOne;
1847 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1848 !DCI.isBeforeLegalizeOps());
1849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1850 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1851 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1852 DCI.CommitTargetLoweringOpt(TLO);
1858 case ISD::UINT_TO_FP: {
1859 return performUCharToFloatCombine(N, DCI);
1862 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1865 EVT VT = N->getValueType(0);
1869 // Only do this if we are not trying to support denormals. v_mad_f32 does
1870 // not support denormals ever.
1871 if (Subtarget->hasFP32Denormals())
1874 SDValue LHS = N->getOperand(0);
1875 SDValue RHS = N->getOperand(1);
1877 // These should really be instruction patterns, but writing patterns with
1878 // source modiifiers is a pain.
1880 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1881 if (LHS.getOpcode() == ISD::FADD) {
1882 SDValue A = LHS.getOperand(0);
1883 if (A == LHS.getOperand(1)) {
1884 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1885 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1889 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1890 if (RHS.getOpcode() == ISD::FADD) {
1891 SDValue A = RHS.getOperand(0);
1892 if (A == RHS.getOperand(1)) {
1893 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1894 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1901 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1904 EVT VT = N->getValueType(0);
1906 // Try to get the fneg to fold into the source modifier. This undoes generic
1907 // DAG combines and folds them into the mad.
1909 // Only do this if we are not trying to support denormals. v_mad_f32 does
1910 // not support denormals ever.
1911 if (VT == MVT::f32 &&
1912 !Subtarget->hasFP32Denormals()) {
1913 SDValue LHS = N->getOperand(0);
1914 SDValue RHS = N->getOperand(1);
1915 if (LHS.getOpcode() == ISD::FADD) {
1916 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1918 SDValue A = LHS.getOperand(0);
1919 if (A == LHS.getOperand(1)) {
1920 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1921 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1923 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1927 if (RHS.getOpcode() == ISD::FADD) {
1928 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1930 SDValue A = RHS.getOperand(0);
1931 if (A == RHS.getOperand(1)) {
1932 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1933 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1945 case ISD::ATOMIC_LOAD:
1946 case ISD::ATOMIC_STORE:
1947 case ISD::ATOMIC_CMP_SWAP:
1948 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1949 case ISD::ATOMIC_SWAP:
1950 case ISD::ATOMIC_LOAD_ADD:
1951 case ISD::ATOMIC_LOAD_SUB:
1952 case ISD::ATOMIC_LOAD_AND:
1953 case ISD::ATOMIC_LOAD_OR:
1954 case ISD::ATOMIC_LOAD_XOR:
1955 case ISD::ATOMIC_LOAD_NAND:
1956 case ISD::ATOMIC_LOAD_MIN:
1957 case ISD::ATOMIC_LOAD_MAX:
1958 case ISD::ATOMIC_LOAD_UMIN:
1959 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1960 if (DCI.isBeforeLegalize())
1963 MemSDNode *MemNode = cast<MemSDNode>(N);
1964 SDValue Ptr = MemNode->getBasePtr();
1966 // TODO: We could also do this for multiplies.
1967 unsigned AS = MemNode->getAddressSpace();
1968 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1969 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1971 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1973 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1974 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1980 return performAndCombine(N, DCI);
1982 return performOrCombine(N, DCI);
1983 case AMDGPUISD::FP_CLASS:
1984 return performClassCombine(N, DCI);
1986 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1989 /// \brief Analyze the possible immediate value Op
1991 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1992 /// and the immediate value if it's a literal immediate
1993 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1995 const SIInstrInfo *TII =
1996 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1998 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1999 if (TII->isInlineConstant(Node->getAPIntValue()))
2002 uint64_t Val = Node->getZExtValue();
2003 return isUInt<32>(Val) ? Val : -1;
2006 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2007 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2010 if (Node->getValueType(0) == MVT::f32)
2011 return FloatToBits(Node->getValueAPF().convertToFloat());
2019 /// \brief Helper function for adjustWritemask
2020 static unsigned SubIdx2Lane(unsigned Idx) {
2023 case AMDGPU::sub0: return 0;
2024 case AMDGPU::sub1: return 1;
2025 case AMDGPU::sub2: return 2;
2026 case AMDGPU::sub3: return 3;
2030 /// \brief Adjust the writemask of MIMG instructions
2031 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2032 SelectionDAG &DAG) const {
2033 SDNode *Users[4] = { };
2035 unsigned OldDmask = Node->getConstantOperandVal(0);
2036 unsigned NewDmask = 0;
2038 // Try to figure out the used register components
2039 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2042 // Abort if we can't understand the usage
2043 if (!I->isMachineOpcode() ||
2044 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2047 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2048 // Note that subregs are packed, i.e. Lane==0 is the first bit set
2049 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2051 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2053 // Set which texture component corresponds to the lane.
2055 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2057 Comp = countTrailingZeros(Dmask);
2058 Dmask &= ~(1 << Comp);
2061 // Abort if we have more than one user per component
2066 NewDmask |= 1 << Comp;
2069 // Abort if there's no change
2070 if (NewDmask == OldDmask)
2073 // Adjust the writemask in the node
2074 std::vector<SDValue> Ops;
2075 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2076 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2077 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2079 // If we only got one lane, replace it with a copy
2080 // (if NewDmask has only one bit set...)
2081 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2082 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2084 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2085 SDLoc(), Users[Lane]->getValueType(0),
2086 SDValue(Node, 0), RC);
2087 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2091 // Update the users of the node with the new indices
2092 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2094 SDNode *User = Users[i];
2098 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2099 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2103 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2104 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2105 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2110 static bool isFrameIndexOp(SDValue Op) {
2111 if (Op.getOpcode() == ISD::AssertZext)
2112 Op = Op.getOperand(0);
2114 return isa<FrameIndexSDNode>(Op);
2117 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2118 /// with frame index operands.
2119 /// LLVM assumes that inputs are to these instructions are registers.
2120 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2121 SelectionDAG &DAG) const {
2123 SmallVector<SDValue, 8> Ops;
2124 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2125 if (!isFrameIndexOp(Node->getOperand(i))) {
2126 Ops.push_back(Node->getOperand(i));
2131 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2132 Node->getOperand(i).getValueType(),
2133 Node->getOperand(i)), 0));
2136 DAG.UpdateNodeOperands(Node, Ops);
2139 /// \brief Fold the instructions after selecting them.
2140 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2141 SelectionDAG &DAG) const {
2142 const SIInstrInfo *TII =
2143 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2145 if (TII->isMIMG(Node->getMachineOpcode()))
2146 adjustWritemask(Node, DAG);
2148 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2149 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2150 legalizeTargetIndependentNode(Node, DAG);
2156 /// \brief Assign the register class depending on the number of
2157 /// bits set in the writemask
2158 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2159 SDNode *Node) const {
2160 const SIInstrInfo *TII =
2161 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2163 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2165 if (TII->isVOP3(MI->getOpcode())) {
2166 // Make sure constant bus requirements are respected.
2167 TII->legalizeOperandsVOP3(MRI, MI);
2171 if (TII->isMIMG(*MI)) {
2172 unsigned VReg = MI->getOperand(0).getReg();
2173 unsigned Writemask = MI->getOperand(1).getImm();
2174 unsigned BitsSet = 0;
2175 for (unsigned i = 0; i < 4; ++i)
2176 BitsSet += Writemask & (1 << i) ? 1 : 0;
2178 const TargetRegisterClass *RC;
2181 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2182 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2183 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2186 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2187 MI->setDesc(TII->get(NewOpcode));
2188 MRI.setRegClass(VReg, RC);
2192 // Replace unused atomics with the no return version.
2193 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2194 if (NoRetAtomicOp != -1) {
2195 if (!Node->hasAnyUseOfValue(0)) {
2196 MI->setDesc(TII->get(NoRetAtomicOp));
2197 MI->RemoveOperand(0);
2204 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2205 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2206 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2209 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2211 SDValue Ptr) const {
2212 const SIInstrInfo *TII =
2213 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2215 // Build the half of the subregister with the constants before building the
2216 // full 128-bit register. If we are building multiple resource descriptors,
2217 // this will allow CSEing of the 2-component register.
2218 const SDValue Ops0[] = {
2219 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2220 buildSMovImm32(DAG, DL, 0),
2221 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2222 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2223 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2226 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2227 MVT::v2i32, Ops0), 0);
2229 // Combine the constants and the pointer.
2230 const SDValue Ops1[] = {
2231 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2233 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2235 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2238 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2241 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2242 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2243 /// of the resource descriptor) to create an offset, which is added to
2244 /// the resource pointer.
2245 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2248 uint32_t RsrcDword1,
2249 uint64_t RsrcDword2And3) const {
2250 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2251 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2253 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2254 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2258 SDValue DataLo = buildSMovImm32(DAG, DL,
2259 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2260 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2262 const SDValue Ops[] = {
2263 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2265 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2267 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2269 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2271 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2274 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2277 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2279 SDValue Ptr) const {
2280 const SIInstrInfo *TII =
2281 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2283 return buildRSRC(DAG, DL, Ptr, 0, TII->getScratchRsrcWords23());
2286 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2287 const TargetRegisterClass *RC,
2288 unsigned Reg, EVT VT) const {
2289 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2291 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2292 cast<RegisterSDNode>(VReg)->getReg(), VT);
2295 //===----------------------------------------------------------------------===//
2296 // SI Inline Assembly Support
2297 //===----------------------------------------------------------------------===//
2299 std::pair<unsigned, const TargetRegisterClass *>
2300 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2301 StringRef Constraint,
2303 if (Constraint == "r") {
2304 switch(VT.SimpleTy) {
2305 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2307 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2309 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2313 if (Constraint.size() > 1) {
2314 const TargetRegisterClass *RC = nullptr;
2315 if (Constraint[1] == 'v') {
2316 RC = &AMDGPU::VGPR_32RegClass;
2317 } else if (Constraint[1] == 's') {
2318 RC = &AMDGPU::SGPR_32RegClass;
2323 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2324 if (!Failed && Idx < RC->getNumRegs())
2325 return std::make_pair(RC->getRegister(Idx), RC);
2328 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);