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::v16i16, Expand);
162 setOperationAction(ISD::LOAD, MVT::i1, Custom);
164 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
168 // These should use UDIVREM, so set them to expand
169 setOperationAction(ISD::UDIV, MVT::i64, Expand);
170 setOperationAction(ISD::UREM, MVT::i64, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
173 setOperationAction(ISD::SELECT, MVT::i1, Promote);
175 // We only support LOAD/STORE and vector manipulation ops for vectors
176 // with > 4 elements.
177 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}) {
178 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
182 case ISD::BUILD_VECTOR:
184 case ISD::EXTRACT_VECTOR_ELT:
185 case ISD::INSERT_VECTOR_ELT:
186 case ISD::INSERT_SUBVECTOR:
187 case ISD::EXTRACT_SUBVECTOR:
189 case ISD::CONCAT_VECTORS:
190 setOperationAction(Op, VT, Custom);
193 setOperationAction(Op, VT, Expand);
199 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
200 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
202 setOperationAction(ISD::FRINT, MVT::f64, Legal);
205 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
206 setOperationAction(ISD::FDIV, MVT::f32, Custom);
207 setOperationAction(ISD::FDIV, MVT::f64, Custom);
209 setTargetDAGCombine(ISD::FADD);
210 setTargetDAGCombine(ISD::FSUB);
211 setTargetDAGCombine(ISD::FMINNUM);
212 setTargetDAGCombine(ISD::FMAXNUM);
213 setTargetDAGCombine(ISD::SMIN);
214 setTargetDAGCombine(ISD::SMAX);
215 setTargetDAGCombine(ISD::UMIN);
216 setTargetDAGCombine(ISD::UMAX);
217 setTargetDAGCombine(ISD::SELECT_CC);
218 setTargetDAGCombine(ISD::SETCC);
219 setTargetDAGCombine(ISD::AND);
220 setTargetDAGCombine(ISD::OR);
221 setTargetDAGCombine(ISD::UINT_TO_FP);
223 // All memory operations. Some folding on the pointer operand is done to help
224 // matching the constant offsets in the addressing modes.
225 setTargetDAGCombine(ISD::LOAD);
226 setTargetDAGCombine(ISD::STORE);
227 setTargetDAGCombine(ISD::ATOMIC_LOAD);
228 setTargetDAGCombine(ISD::ATOMIC_STORE);
229 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
230 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
231 setTargetDAGCombine(ISD::ATOMIC_SWAP);
232 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
243 setSchedulingPreference(Sched::RegPressure);
246 //===----------------------------------------------------------------------===//
247 // TargetLowering queries
248 //===----------------------------------------------------------------------===//
250 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
252 // SI has some legal vector types, but no legal vector operations. Say no
253 // shuffles are legal in order to prefer scalarizing some vector operations.
257 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
258 const AddrMode &AM, Type *Ty,
260 // No global is ever allowed as a base.
265 case AMDGPUAS::GLOBAL_ADDRESS:
266 case AMDGPUAS::CONSTANT_ADDRESS: // XXX - Should we assume SMRD instructions?
267 case AMDGPUAS::PRIVATE_ADDRESS:
268 case AMDGPUAS::UNKNOWN_ADDRESS_SPACE: {
269 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
270 // additionally can do r + r + i with addr64. 32-bit has more addressing
271 // mode options. Depending on the resource constant, it can also do
272 // (i64 r0) + (i32 r1) * (i14 i).
274 // SMRD instructions have an 8-bit, dword offset.
276 // Assume nonunifom access, since the address space isn't enough to know
277 // what instruction we will use, and since we don't know if this is a load
278 // or store and scalar stores are only available on VI.
280 // We also know if we are doing an extload, we can't do a scalar load.
282 // Private arrays end up using a scratch buffer most of the time, so also
283 // assume those use MUBUF instructions. Scratch loads / stores are currently
284 // implemented as mubuf instructions with offen bit set, so slightly
285 // different than the normal addr64.
286 if (!isUInt<12>(AM.BaseOffs))
289 // FIXME: Since we can split immediate into soffset and immediate offset,
290 // would it make sense to allow any immediate?
293 case 0: // r + i or just i, depending on HasBaseReg.
296 return true; // We have r + r or r + i.
303 // Allow 2 * r as r + r
304 // Or 2 * r + i is allowed as r + r + i.
306 default: // Don't allow n * r
310 case AMDGPUAS::LOCAL_ADDRESS:
311 case AMDGPUAS::REGION_ADDRESS: {
312 // Basic, single offset DS instructions allow a 16-bit unsigned immediate
314 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
315 // an 8-bit dword offset but we don't know the alignment here.
316 if (!isUInt<16>(AM.BaseOffs))
319 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
322 if (AM.Scale == 1 && AM.HasBaseReg)
327 case AMDGPUAS::FLAT_ADDRESS: {
328 // Flat instructions do not have offsets, and only have the register
330 return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
333 llvm_unreachable("unhandled address space");
337 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
340 bool *IsFast) const {
344 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
345 // which isn't a simple VT.
346 if (!VT.isSimple() || VT == MVT::Other)
349 // TODO - CI+ supports unaligned memory accesses, but this requires driver
352 // XXX - The only mention I see of this in the ISA manual is for LDS direct
353 // reads the "byte address and must be dword aligned". Is it also true for the
354 // normal loads and stores?
355 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
356 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
357 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
358 // with adjacent offsets.
359 return Align % 4 == 0;
362 // Smaller than dword value must be aligned.
363 // FIXME: This should be allowed on CI+
364 if (VT.bitsLT(MVT::i32))
367 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
368 // byte-address are ignored, thus forcing Dword alignment.
369 // This applies to private, global, and constant memory.
373 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
376 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
377 unsigned SrcAlign, bool IsMemset,
380 MachineFunction &MF) const {
381 // FIXME: Should account for address space here.
383 // The default fallback uses the private pointer size as a guess for a type to
384 // use. Make sure we switch these to 64-bit accesses.
386 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
389 if (Size >= 8 && DstAlign >= 4)
396 TargetLoweringBase::LegalizeTypeAction
397 SITargetLowering::getPreferredVectorAction(EVT VT) const {
398 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
399 return TypeSplitVector;
401 return TargetLoweringBase::getPreferredVectorAction(VT);
404 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
406 const SIInstrInfo *TII =
407 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
408 return TII->isInlineConstant(Imm);
411 static EVT toIntegerVT(EVT VT) {
413 return VT.changeVectorElementTypeToInteger();
414 return MVT::getIntegerVT(VT.getSizeInBits());
417 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
418 SDLoc SL, SDValue Chain,
419 unsigned Offset, bool Signed) const {
420 const DataLayout &DL = DAG.getDataLayout();
421 MachineFunction &MF = DAG.getMachineFunction();
422 const SIRegisterInfo *TRI =
423 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
424 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
426 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
428 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
429 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
430 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
431 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
432 MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
433 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
434 DAG.getConstant(Offset, SL, PtrVT));
435 SDValue PtrOffset = DAG.getUNDEF(PtrVT);
436 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
438 unsigned Align = DL.getABITypeAlignment(Ty);
440 if (VT != MemVT && VT.isFloatingPoint()) {
441 // Do an integer load and convert.
442 // FIXME: This is mostly because load legalization after type legalization
443 // doesn't handle FP extloads.
444 assert(VT.getScalarType() == MVT::f32 &&
445 MemVT.getScalarType() == MVT::f16);
447 EVT IVT = toIntegerVT(VT);
448 EVT MemIVT = toIntegerVT(MemVT);
449 SDValue Load = DAG.getLoad(ISD::UNINDEXED, ISD::ZEXTLOAD,
450 IVT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemIVT,
452 true, // isNonTemporal
456 DAG.getNode(ISD::FP16_TO_FP, SL, VT, Load),
460 return DAG.getMergeValues(Ops, SL);
463 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
464 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
465 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
467 true, // isNonTemporal
472 SDValue SITargetLowering::LowerFormalArguments(
473 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
474 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
475 SmallVectorImpl<SDValue> &InVals) const {
476 const SIRegisterInfo *TRI =
477 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
479 MachineFunction &MF = DAG.getMachineFunction();
480 FunctionType *FType = MF.getFunction()->getFunctionType();
481 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
483 assert(CallConv == CallingConv::C);
485 SmallVector<ISD::InputArg, 16> Splits;
486 BitVector Skipped(Ins.size());
488 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
489 const ISD::InputArg &Arg = Ins[i];
491 // First check if it's a PS input addr
492 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
493 !Arg.Flags.isByVal()) {
495 assert((PSInputNum <= 15) && "Too many PS inputs!");
498 // We can savely skip PS inputs
504 Info->PSInputAddr |= 1 << PSInputNum++;
507 // Second split vertices into their elements
508 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
509 ISD::InputArg NewArg = Arg;
510 NewArg.Flags.setSplit();
511 NewArg.VT = Arg.VT.getVectorElementType();
513 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
514 // three or five element vertex only needs three or five registers,
515 // NOT four or eigth.
516 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
517 unsigned NumElements = ParamType->getVectorNumElements();
519 for (unsigned j = 0; j != NumElements; ++j) {
520 Splits.push_back(NewArg);
521 NewArg.PartOffset += NewArg.VT.getStoreSize();
524 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
525 Splits.push_back(Arg);
529 SmallVector<CCValAssign, 16> ArgLocs;
530 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
533 // At least one interpolation mode must be enabled or else the GPU will hang.
534 if (Info->getShaderType() == ShaderType::PIXEL &&
535 (Info->PSInputAddr & 0x7F) == 0) {
536 Info->PSInputAddr |= 1;
537 CCInfo.AllocateReg(AMDGPU::VGPR0);
538 CCInfo.AllocateReg(AMDGPU::VGPR1);
541 // The pointer to the list of arguments is stored in SGPR0, SGPR1
542 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
543 if (Info->getShaderType() == ShaderType::COMPUTE) {
544 if (Subtarget->isAmdHsaOS())
545 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
547 Info->NumUserSGPRs = 4;
549 unsigned InputPtrReg =
550 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
551 unsigned InputPtrRegLo =
552 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
553 unsigned InputPtrRegHi =
554 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
556 unsigned ScratchPtrReg =
557 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
558 unsigned ScratchPtrRegLo =
559 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
560 unsigned ScratchPtrRegHi =
561 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
563 CCInfo.AllocateReg(InputPtrRegLo);
564 CCInfo.AllocateReg(InputPtrRegHi);
565 CCInfo.AllocateReg(ScratchPtrRegLo);
566 CCInfo.AllocateReg(ScratchPtrRegHi);
567 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
568 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
571 if (Info->getShaderType() == ShaderType::COMPUTE) {
572 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
576 AnalyzeFormalArguments(CCInfo, Splits);
578 SmallVector<SDValue, 16> Chains;
580 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
582 const ISD::InputArg &Arg = Ins[i];
584 InVals.push_back(DAG.getUNDEF(Arg.VT));
588 CCValAssign &VA = ArgLocs[ArgIdx++];
589 MVT VT = VA.getLocVT();
593 EVT MemVT = Splits[i].VT;
594 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
595 VA.getLocMemOffset();
596 // The first 36 bytes of the input buffer contains information about
597 // thread group and global sizes.
598 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, Chain,
599 Offset, Ins[i].Flags.isSExt());
600 Chains.push_back(Arg.getValue(1));
602 const PointerType *ParamTy =
603 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
604 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
605 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
606 // On SI local pointers are just offsets into LDS, so they are always
607 // less than 16-bits. On CI and newer they could potentially be
608 // real pointers, so we can't guarantee their size.
609 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
610 DAG.getValueType(MVT::i16));
613 InVals.push_back(Arg);
614 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
617 assert(VA.isRegLoc() && "Parameter must be in a register!");
619 unsigned Reg = VA.getLocReg();
621 if (VT == MVT::i64) {
622 // For now assume it is a pointer
623 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
624 &AMDGPU::SReg_64RegClass);
625 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
626 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
627 InVals.push_back(Copy);
631 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
633 Reg = MF.addLiveIn(Reg, RC);
634 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
636 if (Arg.VT.isVector()) {
638 // Build a vector from the registers
639 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
640 unsigned NumElements = ParamType->getVectorNumElements();
642 SmallVector<SDValue, 4> Regs;
644 for (unsigned j = 1; j != NumElements; ++j) {
645 Reg = ArgLocs[ArgIdx++].getLocReg();
646 Reg = MF.addLiveIn(Reg, RC);
648 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
649 Regs.push_back(Copy);
652 // Fill up the missing vector elements
653 NumElements = Arg.VT.getVectorNumElements() - NumElements;
654 Regs.append(NumElements, DAG.getUNDEF(VT));
656 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
660 InVals.push_back(Val);
663 if (Info->getShaderType() != ShaderType::COMPUTE) {
664 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
665 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
666 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
672 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
675 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
676 MachineInstr * MI, MachineBasicBlock * BB) const {
678 MachineBasicBlock::iterator I = *MI;
679 const SIInstrInfo *TII =
680 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
682 switch (MI->getOpcode()) {
684 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
687 case AMDGPU::SI_RegisterStorePseudo: {
688 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
689 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
690 MachineInstrBuilder MIB =
691 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
693 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
694 MIB.addOperand(MI->getOperand(i));
696 MI->eraseFromParent();
703 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
704 // This currently forces unfolding various combinations of fsub into fma with
705 // free fneg'd operands. As long as we have fast FMA (controlled by
706 // isFMAFasterThanFMulAndFAdd), we should perform these.
708 // When fma is quarter rate, for f64 where add / sub are at best half rate,
709 // most of these combines appear to be cycle neutral but save on instruction
710 // count / code size.
714 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
716 if (!VT.isVector()) {
719 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
722 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
726 // Answering this is somewhat tricky and depends on the specific device which
727 // have different rates for fma or all f64 operations.
729 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
730 // regardless of which device (although the number of cycles differs between
731 // devices), so it is always profitable for f64.
733 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
734 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
735 // which we can always do even without fused FP ops since it returns the same
736 // result as the separate operations and since it is always full
737 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
738 // however does not support denormals, so we do report fma as faster if we have
739 // a fast fma device and require denormals.
741 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
742 VT = VT.getScalarType();
747 switch (VT.getSimpleVT().SimpleTy) {
749 // This is as fast on some subtargets. However, we always have full rate f32
750 // mad available which returns the same result as the separate operations
751 // which we should prefer over fma. We can't use this if we want to support
752 // denormals, so only report this in these cases.
753 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
763 //===----------------------------------------------------------------------===//
764 // Custom DAG Lowering Operations
765 //===----------------------------------------------------------------------===//
767 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
768 switch (Op.getOpcode()) {
769 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
770 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
771 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
773 SDValue Result = LowerLOAD(Op, DAG);
774 assert((!Result.getNode() ||
775 Result.getNode()->getNumValues() == 2) &&
776 "Load should return a value and a chain");
782 return LowerTrig(Op, DAG);
783 case ISD::SELECT: return LowerSELECT(Op, DAG);
784 case ISD::FDIV: return LowerFDIV(Op, DAG);
785 case ISD::STORE: return LowerSTORE(Op, DAG);
786 case ISD::GlobalAddress: {
787 MachineFunction &MF = DAG.getMachineFunction();
788 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
789 return LowerGlobalAddress(MFI, Op, DAG);
791 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
792 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
797 /// \brief Helper function for LowerBRCOND
798 static SDNode *findUser(SDValue Value, unsigned Opcode) {
800 SDNode *Parent = Value.getNode();
801 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
804 if (I.getUse().get() != Value)
807 if (I->getOpcode() == Opcode)
813 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
816 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
817 unsigned FrameIndex = FINode->getIndex();
819 // A FrameIndex node represents a 32-bit offset into scratch memory. If
820 // the high bit of a frame index offset were to be set, this would mean
821 // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
822 // scratch buffer, with 64 being the number of threads per wave.
824 // If we know the machine uses less than 128GB of scratch, then we can
825 // amrk the high bit of the FrameIndex node as known zero,
826 // which is important, because it means in most situations we can
827 // prove that values derived from FrameIndex nodes are non-negative.
828 // This enables us to take advantage of more addressing modes when
829 // accessing scratch buffers, since for scratch reads/writes, the register
830 // offset must always be positive.
832 SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
833 if (Subtarget->enableHugeScratchBuffer())
836 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
837 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
840 /// This transforms the control flow intrinsics to get the branch destination as
841 /// last parameter, also switches branch target with BR if the need arise
842 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
843 SelectionDAG &DAG) const {
847 SDNode *Intr = BRCOND.getOperand(1).getNode();
848 SDValue Target = BRCOND.getOperand(2);
849 SDNode *BR = nullptr;
851 if (Intr->getOpcode() == ISD::SETCC) {
852 // As long as we negate the condition everything is fine
853 SDNode *SetCC = Intr;
854 assert(SetCC->getConstantOperandVal(1) == 1);
855 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
857 Intr = SetCC->getOperand(0).getNode();
860 // Get the target from BR if we don't negate the condition
861 BR = findUser(BRCOND, ISD::BR);
862 Target = BR->getOperand(1);
865 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
867 // Build the result and
868 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
870 // operands of the new intrinsic call
871 SmallVector<SDValue, 4> Ops;
872 Ops.push_back(BRCOND.getOperand(0));
873 Ops.append(Intr->op_begin() + 1, Intr->op_end());
874 Ops.push_back(Target);
876 // build the new intrinsic call
877 SDNode *Result = DAG.getNode(
878 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
879 DAG.getVTList(Res), Ops).getNode();
882 // Give the branch instruction our target
887 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
888 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
889 BR = NewBR.getNode();
892 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
894 // Copy the intrinsic results to registers
895 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
896 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
900 Chain = DAG.getCopyToReg(
902 CopyToReg->getOperand(1),
903 SDValue(Result, i - 1),
906 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
909 // Remove the old intrinsic from the chain
910 DAG.ReplaceAllUsesOfValueWith(
911 SDValue(Intr, Intr->getNumValues() - 1),
912 Intr->getOperand(0));
917 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
919 SelectionDAG &DAG) const {
920 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
922 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
923 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
926 const GlobalValue *GV = GSD->getGlobal();
927 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
929 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
930 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
932 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
933 DAG.getConstant(0, DL, MVT::i32));
934 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
935 DAG.getConstant(1, DL, MVT::i32));
937 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
939 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
940 PtrHi, DAG.getConstant(0, DL, MVT::i32),
941 SDValue(Lo.getNode(), 1));
942 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
945 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
947 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
948 // so we will end up with redundant moves to m0.
950 // We can't use S_MOV_B32, because there is no way to specify m0 as the
951 // destination register.
953 // We have to use them both. Machine cse will combine all the S_MOV_B32
954 // instructions and the register coalescer eliminate the extra copies.
955 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
956 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
957 SDValue(M0, 0), SDValue()); // Glue
958 // A Null SDValue creates
962 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
963 SelectionDAG &DAG) const {
964 MachineFunction &MF = DAG.getMachineFunction();
965 auto MFI = MF.getInfo<SIMachineFunctionInfo>();
966 const SIRegisterInfo *TRI =
967 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
969 EVT VT = Op.getValueType();
971 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
973 switch (IntrinsicID) {
974 case Intrinsic::r600_read_ngroups_x:
975 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
976 SI::KernelInputOffsets::NGROUPS_X, false);
977 case Intrinsic::r600_read_ngroups_y:
978 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
979 SI::KernelInputOffsets::NGROUPS_Y, false);
980 case Intrinsic::r600_read_ngroups_z:
981 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
982 SI::KernelInputOffsets::NGROUPS_Z, false);
983 case Intrinsic::r600_read_global_size_x:
984 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
985 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
986 case Intrinsic::r600_read_global_size_y:
987 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
988 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
989 case Intrinsic::r600_read_global_size_z:
990 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
991 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
992 case Intrinsic::r600_read_local_size_x:
993 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
994 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
995 case Intrinsic::r600_read_local_size_y:
996 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
997 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
998 case Intrinsic::r600_read_local_size_z:
999 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1000 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
1002 case Intrinsic::AMDGPU_read_workdim:
1003 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1004 getImplicitParameterOffset(MFI, GRID_DIM), false);
1006 case Intrinsic::r600_read_tgid_x:
1007 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1008 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
1009 case Intrinsic::r600_read_tgid_y:
1010 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1011 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
1012 case Intrinsic::r600_read_tgid_z:
1013 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1014 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
1015 case Intrinsic::r600_read_tidig_x:
1016 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1017 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
1018 case Intrinsic::r600_read_tidig_y:
1019 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1020 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
1021 case Intrinsic::r600_read_tidig_z:
1022 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1023 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
1024 case AMDGPUIntrinsic::SI_load_const: {
1030 MachineMemOperand *MMO = MF.getMachineMemOperand(
1031 MachinePointerInfo(),
1032 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1033 VT.getStoreSize(), 4);
1034 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1035 Op->getVTList(), Ops, VT, MMO);
1037 case AMDGPUIntrinsic::SI_sample:
1038 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1039 case AMDGPUIntrinsic::SI_sampleb:
1040 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1041 case AMDGPUIntrinsic::SI_sampled:
1042 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1043 case AMDGPUIntrinsic::SI_samplel:
1044 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1045 case AMDGPUIntrinsic::SI_vs_load_input:
1046 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1051 case AMDGPUIntrinsic::AMDGPU_fract:
1052 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1053 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1054 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1055 case AMDGPUIntrinsic::SI_fs_constant: {
1056 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1057 SDValue Glue = M0.getValue(1);
1058 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1059 DAG.getConstant(2, DL, MVT::i32), // P0
1060 Op.getOperand(1), Op.getOperand(2), Glue);
1062 case AMDGPUIntrinsic::SI_fs_interp: {
1063 SDValue IJ = Op.getOperand(4);
1064 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1065 DAG.getConstant(0, DL, MVT::i32));
1066 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1067 DAG.getConstant(1, DL, MVT::i32));
1068 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1069 SDValue Glue = M0.getValue(1);
1070 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1071 DAG.getVTList(MVT::f32, MVT::Glue),
1072 I, Op.getOperand(1), Op.getOperand(2), Glue);
1073 Glue = SDValue(P1.getNode(), 1);
1074 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1075 Op.getOperand(1), Op.getOperand(2), Glue);
1078 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1082 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1083 SelectionDAG &DAG) const {
1084 MachineFunction &MF = DAG.getMachineFunction();
1086 SDValue Chain = Op.getOperand(0);
1087 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1089 switch (IntrinsicID) {
1090 case AMDGPUIntrinsic::SI_sendmsg: {
1091 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1092 SDValue Glue = Chain.getValue(1);
1093 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1094 Op.getOperand(2), Glue);
1096 case AMDGPUIntrinsic::SI_tbuffer_store: {
1114 EVT VT = Op.getOperand(3).getValueType();
1116 MachineMemOperand *MMO = MF.getMachineMemOperand(
1117 MachinePointerInfo(),
1118 MachineMemOperand::MOStore,
1119 VT.getStoreSize(), 4);
1120 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1121 Op->getVTList(), Ops, VT, MMO);
1128 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1130 LoadSDNode *Load = cast<LoadSDNode>(Op);
1132 if (Op.getValueType().isVector()) {
1133 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1134 "Custom lowering for non-i32 vectors hasn't been implemented.");
1135 unsigned NumElements = Op.getValueType().getVectorNumElements();
1136 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1137 switch (Load->getAddressSpace()) {
1139 case AMDGPUAS::GLOBAL_ADDRESS:
1140 case AMDGPUAS::PRIVATE_ADDRESS:
1141 // v4 loads are supported for private and global memory.
1142 if (NumElements <= 4)
1145 case AMDGPUAS::LOCAL_ADDRESS:
1146 return ScalarizeVectorLoad(Op, DAG);
1150 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1153 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1155 SelectionDAG &DAG) const {
1156 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1162 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1163 if (Op.getValueType() != MVT::i64)
1167 SDValue Cond = Op.getOperand(0);
1169 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1170 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1172 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1173 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1175 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1176 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1178 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1180 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1181 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1183 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1185 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1186 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1189 // Catch division cases where we can use shortcuts with rcp and rsq
1191 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1193 SDValue LHS = Op.getOperand(0);
1194 SDValue RHS = Op.getOperand(1);
1195 EVT VT = Op.getValueType();
1196 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1198 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1199 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1200 CLHS->isExactlyValue(1.0)) {
1201 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1202 // the CI documentation has a worst case error of 1 ulp.
1203 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1204 // use it as long as we aren't trying to use denormals.
1206 // 1.0 / sqrt(x) -> rsq(x)
1208 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1209 // error seems really high at 2^29 ULP.
1210 if (RHS.getOpcode() == ISD::FSQRT)
1211 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1213 // 1.0 / x -> rcp(x)
1214 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1219 // Turn into multiply by the reciprocal.
1220 // x / y -> x * (1.0 / y)
1221 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1222 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1228 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1229 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1230 if (FastLowered.getNode())
1233 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1234 // selection error for now rather than do something incorrect.
1235 if (Subtarget->hasFP32Denormals())
1239 SDValue LHS = Op.getOperand(0);
1240 SDValue RHS = Op.getOperand(1);
1242 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1244 const APFloat K0Val(BitsToFloat(0x6f800000));
1245 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1247 const APFloat K1Val(BitsToFloat(0x2f800000));
1248 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1250 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1253 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1255 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1257 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1259 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1261 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1263 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1265 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1268 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1269 if (DAG.getTarget().Options.UnsafeFPMath)
1270 return LowerFastFDIV(Op, DAG);
1273 SDValue X = Op.getOperand(0);
1274 SDValue Y = Op.getOperand(1);
1276 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1278 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1280 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1282 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1284 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1286 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1288 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1290 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1292 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1294 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1295 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1297 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1298 NegDivScale0, Mul, DivScale1);
1302 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1303 // Workaround a hardware bug on SI where the condition output from div_scale
1306 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1308 // Figure out if the scale to use for div_fmas.
1309 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1310 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1311 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1312 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1314 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1315 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1318 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1320 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1322 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1323 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1324 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1326 Scale = DivScale1.getValue(1);
1329 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1330 Fma4, Fma3, Mul, Scale);
1332 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1335 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1336 EVT VT = Op.getValueType();
1339 return LowerFDIV32(Op, DAG);
1342 return LowerFDIV64(Op, DAG);
1344 llvm_unreachable("Unexpected type for fdiv");
1347 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1349 StoreSDNode *Store = cast<StoreSDNode>(Op);
1350 EVT VT = Store->getMemoryVT();
1352 // These stores are legal.
1353 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1354 if (VT.isVector() && VT.getVectorNumElements() > 4)
1355 return ScalarizeVectorStore(Op, DAG);
1359 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1363 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1364 return ScalarizeVectorStore(Op, DAG);
1367 return DAG.getTruncStore(Store->getChain(), DL,
1368 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1369 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1374 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1376 EVT VT = Op.getValueType();
1377 SDValue Arg = Op.getOperand(0);
1378 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1379 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1380 DAG.getConstantFP(0.5/M_PI, DL,
1383 switch (Op.getOpcode()) {
1385 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1387 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1389 llvm_unreachable("Wrong trig opcode");
1393 //===----------------------------------------------------------------------===//
1394 // Custom DAG optimizations
1395 //===----------------------------------------------------------------------===//
1397 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1398 DAGCombinerInfo &DCI) const {
1399 EVT VT = N->getValueType(0);
1400 EVT ScalarVT = VT.getScalarType();
1401 if (ScalarVT != MVT::f32)
1404 SelectionDAG &DAG = DCI.DAG;
1407 SDValue Src = N->getOperand(0);
1408 EVT SrcVT = Src.getValueType();
1410 // TODO: We could try to match extracting the higher bytes, which would be
1411 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1412 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1413 // about in practice.
1414 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1415 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1416 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1417 DCI.AddToWorklist(Cvt.getNode());
1422 // We are primarily trying to catch operations on illegal vector types
1423 // before they are expanded.
1424 // For scalars, we can use the more flexible method of checking masked bits
1425 // after legalization.
1426 if (!DCI.isBeforeLegalize() ||
1427 !SrcVT.isVector() ||
1428 SrcVT.getVectorElementType() != MVT::i8) {
1432 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1434 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1436 unsigned NElts = SrcVT.getVectorNumElements();
1437 if (!SrcVT.isSimple() && NElts != 3)
1440 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1441 // prevent a mess from expanding to v4i32 and repacking.
1442 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1443 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1444 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1445 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1446 LoadSDNode *Load = cast<LoadSDNode>(Src);
1448 unsigned AS = Load->getAddressSpace();
1449 unsigned Align = Load->getAlignment();
1450 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1451 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1453 // Don't try to replace the load if we have to expand it due to alignment
1454 // problems. Otherwise we will end up scalarizing the load, and trying to
1455 // repack into the vector for no real reason.
1456 if (Align < ABIAlignment &&
1457 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1461 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1465 Load->getMemOperand());
1467 // Make sure successors of the original load stay after it by updating
1468 // them to use the new Chain.
1469 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1471 SmallVector<SDValue, 4> Elts;
1472 if (RegVT.isVector())
1473 DAG.ExtractVectorElements(NewLoad, Elts);
1475 Elts.push_back(NewLoad);
1477 SmallVector<SDValue, 4> Ops;
1479 unsigned EltIdx = 0;
1480 for (SDValue Elt : Elts) {
1481 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1482 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1483 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1484 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1485 DCI.AddToWorklist(Cvt.getNode());
1492 assert(Ops.size() == NElts);
1494 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1500 /// \brief Return true if the given offset Size in bytes can be folded into
1501 /// the immediate offsets of a memory instruction for the given address space.
1502 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1503 const AMDGPUSubtarget &STI) {
1505 case AMDGPUAS::GLOBAL_ADDRESS: {
1506 // MUBUF instructions a 12-bit offset in bytes.
1507 return isUInt<12>(OffsetSize);
1509 case AMDGPUAS::CONSTANT_ADDRESS: {
1510 // SMRD instructions have an 8-bit offset in dwords on SI and
1511 // a 20-bit offset in bytes on VI.
1512 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1513 return isUInt<20>(OffsetSize);
1515 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1517 case AMDGPUAS::LOCAL_ADDRESS:
1518 case AMDGPUAS::REGION_ADDRESS: {
1519 // The single offset versions have a 16-bit offset in bytes.
1520 return isUInt<16>(OffsetSize);
1522 case AMDGPUAS::PRIVATE_ADDRESS:
1523 // Indirect register addressing does not use any offsets.
1529 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1531 // This is a variant of
1532 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1534 // The normal DAG combiner will do this, but only if the add has one use since
1535 // that would increase the number of instructions.
1537 // This prevents us from seeing a constant offset that can be folded into a
1538 // memory instruction's addressing mode. If we know the resulting add offset of
1539 // a pointer can be folded into an addressing offset, we can replace the pointer
1540 // operand with the add of new constant offset. This eliminates one of the uses,
1541 // and may allow the remaining use to also be simplified.
1543 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1545 DAGCombinerInfo &DCI) const {
1546 SDValue N0 = N->getOperand(0);
1547 SDValue N1 = N->getOperand(1);
1549 if (N0.getOpcode() != ISD::ADD)
1552 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1556 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1560 // If the resulting offset is too large, we can't fold it into the addressing
1562 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1563 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1566 SelectionDAG &DAG = DCI.DAG;
1568 EVT VT = N->getValueType(0);
1570 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1571 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1573 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1576 SDValue SITargetLowering::performAndCombine(SDNode *N,
1577 DAGCombinerInfo &DCI) const {
1578 if (DCI.isBeforeLegalize())
1581 SelectionDAG &DAG = DCI.DAG;
1583 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1584 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1585 SDValue LHS = N->getOperand(0);
1586 SDValue RHS = N->getOperand(1);
1588 if (LHS.getOpcode() == ISD::SETCC &&
1589 RHS.getOpcode() == ISD::SETCC) {
1590 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1591 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1593 SDValue X = LHS.getOperand(0);
1594 SDValue Y = RHS.getOperand(0);
1595 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1598 if (LCC == ISD::SETO) {
1599 if (X != LHS.getOperand(1))
1602 if (RCC == ISD::SETUNE) {
1603 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1604 if (!C1 || !C1->isInfinity() || C1->isNegative())
1607 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1608 SIInstrFlags::N_SUBNORMAL |
1609 SIInstrFlags::N_ZERO |
1610 SIInstrFlags::P_ZERO |
1611 SIInstrFlags::P_SUBNORMAL |
1612 SIInstrFlags::P_NORMAL;
1614 static_assert(((~(SIInstrFlags::S_NAN |
1615 SIInstrFlags::Q_NAN |
1616 SIInstrFlags::N_INFINITY |
1617 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1621 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1622 X, DAG.getConstant(Mask, DL, MVT::i32));
1630 SDValue SITargetLowering::performOrCombine(SDNode *N,
1631 DAGCombinerInfo &DCI) const {
1632 SelectionDAG &DAG = DCI.DAG;
1633 SDValue LHS = N->getOperand(0);
1634 SDValue RHS = N->getOperand(1);
1636 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1637 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1638 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1639 SDValue Src = LHS.getOperand(0);
1640 if (Src != RHS.getOperand(0))
1643 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1644 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1648 // Only 10 bits are used.
1649 static const uint32_t MaxMask = 0x3ff;
1651 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1653 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1654 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1660 SDValue SITargetLowering::performClassCombine(SDNode *N,
1661 DAGCombinerInfo &DCI) const {
1662 SelectionDAG &DAG = DCI.DAG;
1663 SDValue Mask = N->getOperand(1);
1665 // fp_class x, 0 -> false
1666 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1667 if (CMask->isNullValue())
1668 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1674 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1677 return AMDGPUISD::FMAX3;
1679 return AMDGPUISD::SMAX3;
1681 return AMDGPUISD::UMAX3;
1683 return AMDGPUISD::FMIN3;
1685 return AMDGPUISD::SMIN3;
1687 return AMDGPUISD::UMIN3;
1689 llvm_unreachable("Not a min/max opcode");
1693 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1694 DAGCombinerInfo &DCI) const {
1695 SelectionDAG &DAG = DCI.DAG;
1697 unsigned Opc = N->getOpcode();
1698 SDValue Op0 = N->getOperand(0);
1699 SDValue Op1 = N->getOperand(1);
1701 // Only do this if the inner op has one use since this will just increases
1702 // register pressure for no benefit.
1704 // max(max(a, b), c)
1705 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1707 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1715 // max(a, max(b, c))
1716 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1718 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1729 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1730 DAGCombinerInfo &DCI) const {
1731 SelectionDAG &DAG = DCI.DAG;
1734 SDValue LHS = N->getOperand(0);
1735 SDValue RHS = N->getOperand(1);
1736 EVT VT = LHS.getValueType();
1738 if (VT != MVT::f32 && VT != MVT::f64)
1741 // Match isinf pattern
1742 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1743 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1744 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1745 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1749 const APFloat &APF = CRHS->getValueAPF();
1750 if (APF.isInfinity() && !APF.isNegative()) {
1751 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1752 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1753 DAG.getConstant(Mask, SL, MVT::i32));
1760 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1761 DAGCombinerInfo &DCI) const {
1762 SelectionDAG &DAG = DCI.DAG;
1765 switch (N->getOpcode()) {
1767 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1769 return performSetCCCombine(N, DCI);
1770 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1776 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1777 N->getValueType(0) != MVT::f64 &&
1778 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1779 return performMin3Max3Combine(N, DCI);
1783 case AMDGPUISD::CVT_F32_UBYTE0:
1784 case AMDGPUISD::CVT_F32_UBYTE1:
1785 case AMDGPUISD::CVT_F32_UBYTE2:
1786 case AMDGPUISD::CVT_F32_UBYTE3: {
1787 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1789 SDValue Src = N->getOperand(0);
1790 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1792 APInt KnownZero, KnownOne;
1793 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1794 !DCI.isBeforeLegalizeOps());
1795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1797 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1798 DCI.CommitTargetLoweringOpt(TLO);
1804 case ISD::UINT_TO_FP: {
1805 return performUCharToFloatCombine(N, DCI);
1808 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1811 EVT VT = N->getValueType(0);
1815 // Only do this if we are not trying to support denormals. v_mad_f32 does
1816 // not support denormals ever.
1817 if (Subtarget->hasFP32Denormals())
1820 SDValue LHS = N->getOperand(0);
1821 SDValue RHS = N->getOperand(1);
1823 // These should really be instruction patterns, but writing patterns with
1824 // source modiifiers is a pain.
1826 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1827 if (LHS.getOpcode() == ISD::FADD) {
1828 SDValue A = LHS.getOperand(0);
1829 if (A == LHS.getOperand(1)) {
1830 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1831 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1835 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1836 if (RHS.getOpcode() == ISD::FADD) {
1837 SDValue A = RHS.getOperand(0);
1838 if (A == RHS.getOperand(1)) {
1839 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1840 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1847 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1850 EVT VT = N->getValueType(0);
1852 // Try to get the fneg to fold into the source modifier. This undoes generic
1853 // DAG combines and folds them into the mad.
1855 // Only do this if we are not trying to support denormals. v_mad_f32 does
1856 // not support denormals ever.
1857 if (VT == MVT::f32 &&
1858 !Subtarget->hasFP32Denormals()) {
1859 SDValue LHS = N->getOperand(0);
1860 SDValue RHS = N->getOperand(1);
1861 if (LHS.getOpcode() == ISD::FADD) {
1862 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1864 SDValue A = LHS.getOperand(0);
1865 if (A == LHS.getOperand(1)) {
1866 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1867 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1869 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1873 if (RHS.getOpcode() == ISD::FADD) {
1874 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1876 SDValue A = RHS.getOperand(0);
1877 if (A == RHS.getOperand(1)) {
1878 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1879 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1891 case ISD::ATOMIC_LOAD:
1892 case ISD::ATOMIC_STORE:
1893 case ISD::ATOMIC_CMP_SWAP:
1894 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1895 case ISD::ATOMIC_SWAP:
1896 case ISD::ATOMIC_LOAD_ADD:
1897 case ISD::ATOMIC_LOAD_SUB:
1898 case ISD::ATOMIC_LOAD_AND:
1899 case ISD::ATOMIC_LOAD_OR:
1900 case ISD::ATOMIC_LOAD_XOR:
1901 case ISD::ATOMIC_LOAD_NAND:
1902 case ISD::ATOMIC_LOAD_MIN:
1903 case ISD::ATOMIC_LOAD_MAX:
1904 case ISD::ATOMIC_LOAD_UMIN:
1905 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1906 if (DCI.isBeforeLegalize())
1909 MemSDNode *MemNode = cast<MemSDNode>(N);
1910 SDValue Ptr = MemNode->getBasePtr();
1912 // TODO: We could also do this for multiplies.
1913 unsigned AS = MemNode->getAddressSpace();
1914 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1915 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1917 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1919 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1920 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1926 return performAndCombine(N, DCI);
1928 return performOrCombine(N, DCI);
1929 case AMDGPUISD::FP_CLASS:
1930 return performClassCombine(N, DCI);
1932 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1935 /// \brief Analyze the possible immediate value Op
1937 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1938 /// and the immediate value if it's a literal immediate
1939 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1941 const SIInstrInfo *TII =
1942 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1944 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1945 if (TII->isInlineConstant(Node->getAPIntValue()))
1948 uint64_t Val = Node->getZExtValue();
1949 return isUInt<32>(Val) ? Val : -1;
1952 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1953 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1956 if (Node->getValueType(0) == MVT::f32)
1957 return FloatToBits(Node->getValueAPF().convertToFloat());
1965 /// \brief Helper function for adjustWritemask
1966 static unsigned SubIdx2Lane(unsigned Idx) {
1969 case AMDGPU::sub0: return 0;
1970 case AMDGPU::sub1: return 1;
1971 case AMDGPU::sub2: return 2;
1972 case AMDGPU::sub3: return 3;
1976 /// \brief Adjust the writemask of MIMG instructions
1977 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1978 SelectionDAG &DAG) const {
1979 SDNode *Users[4] = { };
1981 unsigned OldDmask = Node->getConstantOperandVal(0);
1982 unsigned NewDmask = 0;
1984 // Try to figure out the used register components
1985 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1988 // Abort if we can't understand the usage
1989 if (!I->isMachineOpcode() ||
1990 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1993 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1994 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1995 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1997 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1999 // Set which texture component corresponds to the lane.
2001 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2003 Comp = countTrailingZeros(Dmask);
2004 Dmask &= ~(1 << Comp);
2007 // Abort if we have more than one user per component
2012 NewDmask |= 1 << Comp;
2015 // Abort if there's no change
2016 if (NewDmask == OldDmask)
2019 // Adjust the writemask in the node
2020 std::vector<SDValue> Ops;
2021 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2022 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2023 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2025 // If we only got one lane, replace it with a copy
2026 // (if NewDmask has only one bit set...)
2027 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2028 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2030 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2031 SDLoc(), Users[Lane]->getValueType(0),
2032 SDValue(Node, 0), RC);
2033 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2037 // Update the users of the node with the new indices
2038 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2040 SDNode *User = Users[i];
2044 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2045 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2049 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2050 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2051 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2056 static bool isFrameIndexOp(SDValue Op) {
2057 if (Op.getOpcode() == ISD::AssertZext)
2058 Op = Op.getOperand(0);
2060 return isa<FrameIndexSDNode>(Op);
2063 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2064 /// with frame index operands.
2065 /// LLVM assumes that inputs are to these instructions are registers.
2066 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2067 SelectionDAG &DAG) const {
2069 SmallVector<SDValue, 8> Ops;
2070 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2071 if (!isFrameIndexOp(Node->getOperand(i))) {
2072 Ops.push_back(Node->getOperand(i));
2077 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2078 Node->getOperand(i).getValueType(),
2079 Node->getOperand(i)), 0));
2082 DAG.UpdateNodeOperands(Node, Ops);
2085 /// \brief Fold the instructions after selecting them.
2086 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2087 SelectionDAG &DAG) const {
2088 const SIInstrInfo *TII =
2089 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2091 if (TII->isMIMG(Node->getMachineOpcode()))
2092 adjustWritemask(Node, DAG);
2094 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2095 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2096 legalizeTargetIndependentNode(Node, DAG);
2102 /// \brief Assign the register class depending on the number of
2103 /// bits set in the writemask
2104 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2105 SDNode *Node) const {
2106 const SIInstrInfo *TII =
2107 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2109 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2110 TII->legalizeOperands(MI);
2112 if (TII->isMIMG(MI->getOpcode())) {
2113 unsigned VReg = MI->getOperand(0).getReg();
2114 unsigned Writemask = MI->getOperand(1).getImm();
2115 unsigned BitsSet = 0;
2116 for (unsigned i = 0; i < 4; ++i)
2117 BitsSet += Writemask & (1 << i) ? 1 : 0;
2119 const TargetRegisterClass *RC;
2122 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2123 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2124 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2127 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2128 MI->setDesc(TII->get(NewOpcode));
2129 MRI.setRegClass(VReg, RC);
2133 // Replace unused atomics with the no return version.
2134 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2135 if (NoRetAtomicOp != -1) {
2136 if (!Node->hasAnyUseOfValue(0)) {
2137 MI->setDesc(TII->get(NoRetAtomicOp));
2138 MI->RemoveOperand(0);
2145 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2146 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2147 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2150 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2152 SDValue Ptr) const {
2153 const SIInstrInfo *TII =
2154 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2156 // XXX - Workaround for moveToVALU not handling different register class
2157 // inserts for REG_SEQUENCE.
2159 // Build the half of the subregister with the constants.
2160 const SDValue Ops0[] = {
2161 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2162 buildSMovImm32(DAG, DL, 0),
2163 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2164 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2165 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2168 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2169 MVT::v2i32, Ops0), 0);
2171 // Combine the constants and the pointer.
2172 const SDValue Ops1[] = {
2173 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2175 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2177 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2180 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2182 const SDValue Ops[] = {
2183 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2185 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2186 buildSMovImm32(DAG, DL, 0),
2187 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2188 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2189 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2192 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2197 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2198 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2199 /// of the resource descriptor) to create an offset, which is added to the
2200 /// resource ponter.
2201 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2204 uint32_t RsrcDword1,
2205 uint64_t RsrcDword2And3) const {
2206 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2207 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2209 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2210 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2214 SDValue DataLo = buildSMovImm32(DAG, DL,
2215 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2216 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2218 const SDValue Ops[] = {
2219 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2221 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2223 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2225 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2227 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2230 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2233 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2235 SDValue Ptr) const {
2236 const SIInstrInfo *TII =
2237 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2238 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2241 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2244 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2245 const TargetRegisterClass *RC,
2246 unsigned Reg, EVT VT) const {
2247 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2249 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2250 cast<RegisterSDNode>(VReg)->getReg(), VT);
2253 //===----------------------------------------------------------------------===//
2254 // SI Inline Assembly Support
2255 //===----------------------------------------------------------------------===//
2257 std::pair<unsigned, const TargetRegisterClass *>
2258 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2259 StringRef Constraint,
2261 if (Constraint == "r") {
2262 switch(VT.SimpleTy) {
2263 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2265 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2267 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2271 if (Constraint.size() > 1) {
2272 const TargetRegisterClass *RC = nullptr;
2273 if (Constraint[1] == 'v') {
2274 RC = &AMDGPU::VGPR_32RegClass;
2275 } else if (Constraint[1] == 's') {
2276 RC = &AMDGPU::SGPR_32RegClass;
2281 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2282 if (!Failed && Idx < RC->getNumRegs())
2283 return std::make_pair(RC->getRegister(Idx), RC);
2286 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);