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
455 return DAG.getNode(ISD::FP16_TO_FP, SL, VT, Load);
458 ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
459 return DAG.getLoad(ISD::UNINDEXED, ExtTy,
460 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
462 true, // isNonTemporal
467 SDValue SITargetLowering::LowerFormalArguments(
468 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
469 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
470 SmallVectorImpl<SDValue> &InVals) const {
471 const SIRegisterInfo *TRI =
472 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
474 MachineFunction &MF = DAG.getMachineFunction();
475 FunctionType *FType = MF.getFunction()->getFunctionType();
476 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
478 assert(CallConv == CallingConv::C);
480 SmallVector<ISD::InputArg, 16> Splits;
481 BitVector Skipped(Ins.size());
483 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
484 const ISD::InputArg &Arg = Ins[i];
486 // First check if it's a PS input addr
487 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
488 !Arg.Flags.isByVal()) {
490 assert((PSInputNum <= 15) && "Too many PS inputs!");
493 // We can savely skip PS inputs
499 Info->PSInputAddr |= 1 << PSInputNum++;
502 // Second split vertices into their elements
503 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
504 ISD::InputArg NewArg = Arg;
505 NewArg.Flags.setSplit();
506 NewArg.VT = Arg.VT.getVectorElementType();
508 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
509 // three or five element vertex only needs three or five registers,
510 // NOT four or eigth.
511 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
512 unsigned NumElements = ParamType->getVectorNumElements();
514 for (unsigned j = 0; j != NumElements; ++j) {
515 Splits.push_back(NewArg);
516 NewArg.PartOffset += NewArg.VT.getStoreSize();
519 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
520 Splits.push_back(Arg);
524 SmallVector<CCValAssign, 16> ArgLocs;
525 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
528 // At least one interpolation mode must be enabled or else the GPU will hang.
529 if (Info->getShaderType() == ShaderType::PIXEL &&
530 (Info->PSInputAddr & 0x7F) == 0) {
531 Info->PSInputAddr |= 1;
532 CCInfo.AllocateReg(AMDGPU::VGPR0);
533 CCInfo.AllocateReg(AMDGPU::VGPR1);
536 // The pointer to the list of arguments is stored in SGPR0, SGPR1
537 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
538 if (Info->getShaderType() == ShaderType::COMPUTE) {
539 if (Subtarget->isAmdHsaOS())
540 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
542 Info->NumUserSGPRs = 4;
544 unsigned InputPtrReg =
545 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
546 unsigned InputPtrRegLo =
547 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
548 unsigned InputPtrRegHi =
549 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
551 unsigned ScratchPtrReg =
552 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
553 unsigned ScratchPtrRegLo =
554 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
555 unsigned ScratchPtrRegHi =
556 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
558 CCInfo.AllocateReg(InputPtrRegLo);
559 CCInfo.AllocateReg(InputPtrRegHi);
560 CCInfo.AllocateReg(ScratchPtrRegLo);
561 CCInfo.AllocateReg(ScratchPtrRegHi);
562 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
563 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
566 if (Info->getShaderType() == ShaderType::COMPUTE) {
567 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
571 AnalyzeFormalArguments(CCInfo, Splits);
573 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
575 const ISD::InputArg &Arg = Ins[i];
577 InVals.push_back(DAG.getUNDEF(Arg.VT));
581 CCValAssign &VA = ArgLocs[ArgIdx++];
582 MVT VT = VA.getLocVT();
586 EVT MemVT = Splits[i].VT;
587 const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
588 VA.getLocMemOffset();
589 // The first 36 bytes of the input buffer contains information about
590 // thread group and global sizes.
591 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
592 Offset, Ins[i].Flags.isSExt());
594 const PointerType *ParamTy =
595 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
596 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
597 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
598 // On SI local pointers are just offsets into LDS, so they are always
599 // less than 16-bits. On CI and newer they could potentially be
600 // real pointers, so we can't guarantee their size.
601 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
602 DAG.getValueType(MVT::i16));
605 InVals.push_back(Arg);
606 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
609 assert(VA.isRegLoc() && "Parameter must be in a register!");
611 unsigned Reg = VA.getLocReg();
613 if (VT == MVT::i64) {
614 // For now assume it is a pointer
615 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
616 &AMDGPU::SReg_64RegClass);
617 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
618 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
622 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
624 Reg = MF.addLiveIn(Reg, RC);
625 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
627 if (Arg.VT.isVector()) {
629 // Build a vector from the registers
630 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
631 unsigned NumElements = ParamType->getVectorNumElements();
633 SmallVector<SDValue, 4> Regs;
635 for (unsigned j = 1; j != NumElements; ++j) {
636 Reg = ArgLocs[ArgIdx++].getLocReg();
637 Reg = MF.addLiveIn(Reg, RC);
638 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
641 // Fill up the missing vector elements
642 NumElements = Arg.VT.getVectorNumElements() - NumElements;
643 Regs.append(NumElements, DAG.getUNDEF(VT));
645 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
649 InVals.push_back(Val);
652 if (Info->getShaderType() != ShaderType::COMPUTE) {
653 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
654 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
655 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
660 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
661 MachineInstr * MI, MachineBasicBlock * BB) const {
663 MachineBasicBlock::iterator I = *MI;
664 const SIInstrInfo *TII =
665 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
667 switch (MI->getOpcode()) {
669 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
672 case AMDGPU::SI_RegisterStorePseudo: {
673 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
674 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
675 MachineInstrBuilder MIB =
676 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
678 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
679 MIB.addOperand(MI->getOperand(i));
681 MI->eraseFromParent();
688 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
689 // This currently forces unfolding various combinations of fsub into fma with
690 // free fneg'd operands. As long as we have fast FMA (controlled by
691 // isFMAFasterThanFMulAndFAdd), we should perform these.
693 // When fma is quarter rate, for f64 where add / sub are at best half rate,
694 // most of these combines appear to be cycle neutral but save on instruction
695 // count / code size.
699 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
701 if (!VT.isVector()) {
704 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
707 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &) const {
711 // Answering this is somewhat tricky and depends on the specific device which
712 // have different rates for fma or all f64 operations.
714 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
715 // regardless of which device (although the number of cycles differs between
716 // devices), so it is always profitable for f64.
718 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
719 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
720 // which we can always do even without fused FP ops since it returns the same
721 // result as the separate operations and since it is always full
722 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
723 // however does not support denormals, so we do report fma as faster if we have
724 // a fast fma device and require denormals.
726 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
727 VT = VT.getScalarType();
732 switch (VT.getSimpleVT().SimpleTy) {
734 // This is as fast on some subtargets. However, we always have full rate f32
735 // mad available which returns the same result as the separate operations
736 // which we should prefer over fma. We can't use this if we want to support
737 // denormals, so only report this in these cases.
738 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
748 //===----------------------------------------------------------------------===//
749 // Custom DAG Lowering Operations
750 //===----------------------------------------------------------------------===//
752 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
753 switch (Op.getOpcode()) {
754 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
755 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
756 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
758 SDValue Result = LowerLOAD(Op, DAG);
759 assert((!Result.getNode() ||
760 Result.getNode()->getNumValues() == 2) &&
761 "Load should return a value and a chain");
767 return LowerTrig(Op, DAG);
768 case ISD::SELECT: return LowerSELECT(Op, DAG);
769 case ISD::FDIV: return LowerFDIV(Op, DAG);
770 case ISD::STORE: return LowerSTORE(Op, DAG);
771 case ISD::GlobalAddress: {
772 MachineFunction &MF = DAG.getMachineFunction();
773 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
774 return LowerGlobalAddress(MFI, Op, DAG);
776 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
777 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
782 /// \brief Helper function for LowerBRCOND
783 static SDNode *findUser(SDValue Value, unsigned Opcode) {
785 SDNode *Parent = Value.getNode();
786 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
789 if (I.getUse().get() != Value)
792 if (I->getOpcode() == Opcode)
798 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
800 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
801 unsigned FrameIndex = FINode->getIndex();
803 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
806 /// This transforms the control flow intrinsics to get the branch destination as
807 /// last parameter, also switches branch target with BR if the need arise
808 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
809 SelectionDAG &DAG) const {
813 SDNode *Intr = BRCOND.getOperand(1).getNode();
814 SDValue Target = BRCOND.getOperand(2);
815 SDNode *BR = nullptr;
817 if (Intr->getOpcode() == ISD::SETCC) {
818 // As long as we negate the condition everything is fine
819 SDNode *SetCC = Intr;
820 assert(SetCC->getConstantOperandVal(1) == 1);
821 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
823 Intr = SetCC->getOperand(0).getNode();
826 // Get the target from BR if we don't negate the condition
827 BR = findUser(BRCOND, ISD::BR);
828 Target = BR->getOperand(1);
831 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
833 // Build the result and
834 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
836 // operands of the new intrinsic call
837 SmallVector<SDValue, 4> Ops;
838 Ops.push_back(BRCOND.getOperand(0));
839 Ops.append(Intr->op_begin() + 1, Intr->op_end());
840 Ops.push_back(Target);
842 // build the new intrinsic call
843 SDNode *Result = DAG.getNode(
844 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
845 DAG.getVTList(Res), Ops).getNode();
848 // Give the branch instruction our target
853 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
854 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
855 BR = NewBR.getNode();
858 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
860 // Copy the intrinsic results to registers
861 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
862 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
866 Chain = DAG.getCopyToReg(
868 CopyToReg->getOperand(1),
869 SDValue(Result, i - 1),
872 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
875 // Remove the old intrinsic from the chain
876 DAG.ReplaceAllUsesOfValueWith(
877 SDValue(Intr, Intr->getNumValues() - 1),
878 Intr->getOperand(0));
883 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
885 SelectionDAG &DAG) const {
886 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
888 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
889 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
892 const GlobalValue *GV = GSD->getGlobal();
893 MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
895 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
896 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
898 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
899 DAG.getConstant(0, DL, MVT::i32));
900 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
901 DAG.getConstant(1, DL, MVT::i32));
903 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
905 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
906 PtrHi, DAG.getConstant(0, DL, MVT::i32),
907 SDValue(Lo.getNode(), 1));
908 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
911 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
913 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
914 // so we will end up with redundant moves to m0.
916 // We can't use S_MOV_B32, because there is no way to specify m0 as the
917 // destination register.
919 // We have to use them both. Machine cse will combine all the S_MOV_B32
920 // instructions and the register coalescer eliminate the extra copies.
921 SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
922 return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
923 SDValue(M0, 0), SDValue()); // Glue
924 // A Null SDValue creates
928 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
929 SelectionDAG &DAG) const {
930 MachineFunction &MF = DAG.getMachineFunction();
931 const SIRegisterInfo *TRI =
932 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
934 EVT VT = Op.getValueType();
936 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
938 switch (IntrinsicID) {
939 case Intrinsic::r600_read_ngroups_x:
940 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
941 SI::KernelInputOffsets::NGROUPS_X, false);
942 case Intrinsic::r600_read_ngroups_y:
943 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
944 SI::KernelInputOffsets::NGROUPS_Y, false);
945 case Intrinsic::r600_read_ngroups_z:
946 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
947 SI::KernelInputOffsets::NGROUPS_Z, false);
948 case Intrinsic::r600_read_global_size_x:
949 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
950 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
951 case Intrinsic::r600_read_global_size_y:
952 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
953 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
954 case Intrinsic::r600_read_global_size_z:
955 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
956 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
957 case Intrinsic::r600_read_local_size_x:
958 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
959 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
960 case Intrinsic::r600_read_local_size_y:
961 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
962 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
963 case Intrinsic::r600_read_local_size_z:
964 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
965 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
967 case Intrinsic::AMDGPU_read_workdim:
968 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
969 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
972 case Intrinsic::r600_read_tgid_x:
973 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
974 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
975 case Intrinsic::r600_read_tgid_y:
976 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
977 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
978 case Intrinsic::r600_read_tgid_z:
979 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
980 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
981 case Intrinsic::r600_read_tidig_x:
982 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
983 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
984 case Intrinsic::r600_read_tidig_y:
985 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
986 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
987 case Intrinsic::r600_read_tidig_z:
988 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
989 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
990 case AMDGPUIntrinsic::SI_load_const: {
996 MachineMemOperand *MMO = MF.getMachineMemOperand(
997 MachinePointerInfo(),
998 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
999 VT.getStoreSize(), 4);
1000 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1001 Op->getVTList(), Ops, VT, MMO);
1003 case AMDGPUIntrinsic::SI_sample:
1004 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1005 case AMDGPUIntrinsic::SI_sampleb:
1006 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1007 case AMDGPUIntrinsic::SI_sampled:
1008 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1009 case AMDGPUIntrinsic::SI_samplel:
1010 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1011 case AMDGPUIntrinsic::SI_vs_load_input:
1012 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1017 case AMDGPUIntrinsic::AMDGPU_fract:
1018 case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1019 return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1020 DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1021 case AMDGPUIntrinsic::SI_fs_constant: {
1022 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1023 SDValue Glue = M0.getValue(1);
1024 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1025 DAG.getConstant(2, DL, MVT::i32), // P0
1026 Op.getOperand(1), Op.getOperand(2), Glue);
1028 case AMDGPUIntrinsic::SI_fs_interp: {
1029 SDValue IJ = Op.getOperand(4);
1030 SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1031 DAG.getConstant(0, DL, MVT::i32));
1032 SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1033 DAG.getConstant(1, DL, MVT::i32));
1034 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1035 SDValue Glue = M0.getValue(1);
1036 SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1037 DAG.getVTList(MVT::f32, MVT::Glue),
1038 I, Op.getOperand(1), Op.getOperand(2), Glue);
1039 Glue = SDValue(P1.getNode(), 1);
1040 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1041 Op.getOperand(1), Op.getOperand(2), Glue);
1044 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1048 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1049 SelectionDAG &DAG) const {
1050 MachineFunction &MF = DAG.getMachineFunction();
1052 SDValue Chain = Op.getOperand(0);
1053 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1055 switch (IntrinsicID) {
1056 case AMDGPUIntrinsic::SI_sendmsg: {
1057 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1058 SDValue Glue = Chain.getValue(1);
1059 return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1060 Op.getOperand(2), Glue);
1062 case AMDGPUIntrinsic::SI_tbuffer_store: {
1080 EVT VT = Op.getOperand(3).getValueType();
1082 MachineMemOperand *MMO = MF.getMachineMemOperand(
1083 MachinePointerInfo(),
1084 MachineMemOperand::MOStore,
1085 VT.getStoreSize(), 4);
1086 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1087 Op->getVTList(), Ops, VT, MMO);
1094 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1096 LoadSDNode *Load = cast<LoadSDNode>(Op);
1098 if (Op.getValueType().isVector()) {
1099 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1100 "Custom lowering for non-i32 vectors hasn't been implemented.");
1101 unsigned NumElements = Op.getValueType().getVectorNumElements();
1102 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1103 switch (Load->getAddressSpace()) {
1105 case AMDGPUAS::GLOBAL_ADDRESS:
1106 case AMDGPUAS::PRIVATE_ADDRESS:
1107 // v4 loads are supported for private and global memory.
1108 if (NumElements <= 4)
1111 case AMDGPUAS::LOCAL_ADDRESS:
1112 return ScalarizeVectorLoad(Op, DAG);
1116 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1119 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1121 SelectionDAG &DAG) const {
1122 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1128 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1129 if (Op.getValueType() != MVT::i64)
1133 SDValue Cond = Op.getOperand(0);
1135 SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1136 SDValue One = DAG.getConstant(1, DL, MVT::i32);
1138 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1139 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1141 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1142 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1144 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1146 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1147 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1149 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1151 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1152 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1155 // Catch division cases where we can use shortcuts with rcp and rsq
1157 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1159 SDValue LHS = Op.getOperand(0);
1160 SDValue RHS = Op.getOperand(1);
1161 EVT VT = Op.getValueType();
1162 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1164 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1165 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1166 CLHS->isExactlyValue(1.0)) {
1167 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1168 // the CI documentation has a worst case error of 1 ulp.
1169 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1170 // use it as long as we aren't trying to use denormals.
1172 // 1.0 / sqrt(x) -> rsq(x)
1174 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1175 // error seems really high at 2^29 ULP.
1176 if (RHS.getOpcode() == ISD::FSQRT)
1177 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1179 // 1.0 / x -> rcp(x)
1180 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1185 // Turn into multiply by the reciprocal.
1186 // x / y -> x * (1.0 / y)
1187 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1188 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1194 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1195 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1196 if (FastLowered.getNode())
1199 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1200 // selection error for now rather than do something incorrect.
1201 if (Subtarget->hasFP32Denormals())
1205 SDValue LHS = Op.getOperand(0);
1206 SDValue RHS = Op.getOperand(1);
1208 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1210 const APFloat K0Val(BitsToFloat(0x6f800000));
1211 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1213 const APFloat K1Val(BitsToFloat(0x2f800000));
1214 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1216 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1219 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1221 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1223 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1225 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1227 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1229 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1231 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1234 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1235 if (DAG.getTarget().Options.UnsafeFPMath)
1236 return LowerFastFDIV(Op, DAG);
1239 SDValue X = Op.getOperand(0);
1240 SDValue Y = Op.getOperand(1);
1242 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1244 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1246 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1248 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1250 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1252 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1254 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1256 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1258 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1260 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1261 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1263 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1264 NegDivScale0, Mul, DivScale1);
1268 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1269 // Workaround a hardware bug on SI where the condition output from div_scale
1272 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1274 // Figure out if the scale to use for div_fmas.
1275 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1276 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1277 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1278 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1280 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1281 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1284 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1286 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1288 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1289 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1290 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1292 Scale = DivScale1.getValue(1);
1295 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1296 Fma4, Fma3, Mul, Scale);
1298 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1301 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1302 EVT VT = Op.getValueType();
1305 return LowerFDIV32(Op, DAG);
1308 return LowerFDIV64(Op, DAG);
1310 llvm_unreachable("Unexpected type for fdiv");
1313 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1315 StoreSDNode *Store = cast<StoreSDNode>(Op);
1316 EVT VT = Store->getMemoryVT();
1318 // These stores are legal.
1319 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1320 if (VT.isVector() && VT.getVectorNumElements() > 4)
1321 return ScalarizeVectorStore(Op, DAG);
1325 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1329 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1330 return ScalarizeVectorStore(Op, DAG);
1333 return DAG.getTruncStore(Store->getChain(), DL,
1334 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1335 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1340 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1342 EVT VT = Op.getValueType();
1343 SDValue Arg = Op.getOperand(0);
1344 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1345 DAG.getNode(ISD::FMUL, DL, VT, Arg,
1346 DAG.getConstantFP(0.5/M_PI, DL,
1349 switch (Op.getOpcode()) {
1351 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1353 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1355 llvm_unreachable("Wrong trig opcode");
1359 //===----------------------------------------------------------------------===//
1360 // Custom DAG optimizations
1361 //===----------------------------------------------------------------------===//
1363 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1364 DAGCombinerInfo &DCI) const {
1365 EVT VT = N->getValueType(0);
1366 EVT ScalarVT = VT.getScalarType();
1367 if (ScalarVT != MVT::f32)
1370 SelectionDAG &DAG = DCI.DAG;
1373 SDValue Src = N->getOperand(0);
1374 EVT SrcVT = Src.getValueType();
1376 // TODO: We could try to match extracting the higher bytes, which would be
1377 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1378 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1379 // about in practice.
1380 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1381 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1382 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1383 DCI.AddToWorklist(Cvt.getNode());
1388 // We are primarily trying to catch operations on illegal vector types
1389 // before they are expanded.
1390 // For scalars, we can use the more flexible method of checking masked bits
1391 // after legalization.
1392 if (!DCI.isBeforeLegalize() ||
1393 !SrcVT.isVector() ||
1394 SrcVT.getVectorElementType() != MVT::i8) {
1398 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1400 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1402 unsigned NElts = SrcVT.getVectorNumElements();
1403 if (!SrcVT.isSimple() && NElts != 3)
1406 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1407 // prevent a mess from expanding to v4i32 and repacking.
1408 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1409 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1410 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1411 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1412 LoadSDNode *Load = cast<LoadSDNode>(Src);
1414 unsigned AS = Load->getAddressSpace();
1415 unsigned Align = Load->getAlignment();
1416 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1417 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1419 // Don't try to replace the load if we have to expand it due to alignment
1420 // problems. Otherwise we will end up scalarizing the load, and trying to
1421 // repack into the vector for no real reason.
1422 if (Align < ABIAlignment &&
1423 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1427 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1431 Load->getMemOperand());
1433 // Make sure successors of the original load stay after it by updating
1434 // them to use the new Chain.
1435 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1437 SmallVector<SDValue, 4> Elts;
1438 if (RegVT.isVector())
1439 DAG.ExtractVectorElements(NewLoad, Elts);
1441 Elts.push_back(NewLoad);
1443 SmallVector<SDValue, 4> Ops;
1445 unsigned EltIdx = 0;
1446 for (SDValue Elt : Elts) {
1447 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1448 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1449 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1450 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1451 DCI.AddToWorklist(Cvt.getNode());
1458 assert(Ops.size() == NElts);
1460 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1466 /// \brief Return true if the given offset Size in bytes can be folded into
1467 /// the immediate offsets of a memory instruction for the given address space.
1468 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1469 const AMDGPUSubtarget &STI) {
1471 case AMDGPUAS::GLOBAL_ADDRESS: {
1472 // MUBUF instructions a 12-bit offset in bytes.
1473 return isUInt<12>(OffsetSize);
1475 case AMDGPUAS::CONSTANT_ADDRESS: {
1476 // SMRD instructions have an 8-bit offset in dwords on SI and
1477 // a 20-bit offset in bytes on VI.
1478 if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1479 return isUInt<20>(OffsetSize);
1481 return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1483 case AMDGPUAS::LOCAL_ADDRESS:
1484 case AMDGPUAS::REGION_ADDRESS: {
1485 // The single offset versions have a 16-bit offset in bytes.
1486 return isUInt<16>(OffsetSize);
1488 case AMDGPUAS::PRIVATE_ADDRESS:
1489 // Indirect register addressing does not use any offsets.
1495 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1497 // This is a variant of
1498 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1500 // The normal DAG combiner will do this, but only if the add has one use since
1501 // that would increase the number of instructions.
1503 // This prevents us from seeing a constant offset that can be folded into a
1504 // memory instruction's addressing mode. If we know the resulting add offset of
1505 // a pointer can be folded into an addressing offset, we can replace the pointer
1506 // operand with the add of new constant offset. This eliminates one of the uses,
1507 // and may allow the remaining use to also be simplified.
1509 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1511 DAGCombinerInfo &DCI) const {
1512 SDValue N0 = N->getOperand(0);
1513 SDValue N1 = N->getOperand(1);
1515 if (N0.getOpcode() != ISD::ADD)
1518 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1522 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1526 // If the resulting offset is too large, we can't fold it into the addressing
1528 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1529 if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1532 SelectionDAG &DAG = DCI.DAG;
1534 EVT VT = N->getValueType(0);
1536 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1537 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1539 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1542 SDValue SITargetLowering::performAndCombine(SDNode *N,
1543 DAGCombinerInfo &DCI) const {
1544 if (DCI.isBeforeLegalize())
1547 SelectionDAG &DAG = DCI.DAG;
1549 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1550 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1551 SDValue LHS = N->getOperand(0);
1552 SDValue RHS = N->getOperand(1);
1554 if (LHS.getOpcode() == ISD::SETCC &&
1555 RHS.getOpcode() == ISD::SETCC) {
1556 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1557 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1559 SDValue X = LHS.getOperand(0);
1560 SDValue Y = RHS.getOperand(0);
1561 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1564 if (LCC == ISD::SETO) {
1565 if (X != LHS.getOperand(1))
1568 if (RCC == ISD::SETUNE) {
1569 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1570 if (!C1 || !C1->isInfinity() || C1->isNegative())
1573 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1574 SIInstrFlags::N_SUBNORMAL |
1575 SIInstrFlags::N_ZERO |
1576 SIInstrFlags::P_ZERO |
1577 SIInstrFlags::P_SUBNORMAL |
1578 SIInstrFlags::P_NORMAL;
1580 static_assert(((~(SIInstrFlags::S_NAN |
1581 SIInstrFlags::Q_NAN |
1582 SIInstrFlags::N_INFINITY |
1583 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1587 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1588 X, DAG.getConstant(Mask, DL, MVT::i32));
1596 SDValue SITargetLowering::performOrCombine(SDNode *N,
1597 DAGCombinerInfo &DCI) const {
1598 SelectionDAG &DAG = DCI.DAG;
1599 SDValue LHS = N->getOperand(0);
1600 SDValue RHS = N->getOperand(1);
1602 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1603 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1604 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1605 SDValue Src = LHS.getOperand(0);
1606 if (Src != RHS.getOperand(0))
1609 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1610 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1614 // Only 10 bits are used.
1615 static const uint32_t MaxMask = 0x3ff;
1617 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1619 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1620 Src, DAG.getConstant(NewMask, DL, MVT::i32));
1626 SDValue SITargetLowering::performClassCombine(SDNode *N,
1627 DAGCombinerInfo &DCI) const {
1628 SelectionDAG &DAG = DCI.DAG;
1629 SDValue Mask = N->getOperand(1);
1631 // fp_class x, 0 -> false
1632 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1633 if (CMask->isNullValue())
1634 return DAG.getConstant(0, SDLoc(N), MVT::i1);
1640 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1643 return AMDGPUISD::FMAX3;
1645 return AMDGPUISD::SMAX3;
1647 return AMDGPUISD::UMAX3;
1649 return AMDGPUISD::FMIN3;
1651 return AMDGPUISD::SMIN3;
1653 return AMDGPUISD::UMIN3;
1655 llvm_unreachable("Not a min/max opcode");
1659 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1660 DAGCombinerInfo &DCI) const {
1661 SelectionDAG &DAG = DCI.DAG;
1663 unsigned Opc = N->getOpcode();
1664 SDValue Op0 = N->getOperand(0);
1665 SDValue Op1 = N->getOperand(1);
1667 // Only do this if the inner op has one use since this will just increases
1668 // register pressure for no benefit.
1670 // max(max(a, b), c)
1671 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1673 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1681 // max(a, max(b, c))
1682 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1684 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1695 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1696 DAGCombinerInfo &DCI) const {
1697 SelectionDAG &DAG = DCI.DAG;
1700 SDValue LHS = N->getOperand(0);
1701 SDValue RHS = N->getOperand(1);
1702 EVT VT = LHS.getValueType();
1704 if (VT != MVT::f32 && VT != MVT::f64)
1707 // Match isinf pattern
1708 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1709 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1710 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1711 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1715 const APFloat &APF = CRHS->getValueAPF();
1716 if (APF.isInfinity() && !APF.isNegative()) {
1717 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1718 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1719 DAG.getConstant(Mask, SL, MVT::i32));
1726 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1727 DAGCombinerInfo &DCI) const {
1728 SelectionDAG &DAG = DCI.DAG;
1731 switch (N->getOpcode()) {
1733 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1735 return performSetCCCombine(N, DCI);
1736 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1742 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1743 N->getValueType(0) != MVT::f64 &&
1744 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1745 return performMin3Max3Combine(N, DCI);
1749 case AMDGPUISD::CVT_F32_UBYTE0:
1750 case AMDGPUISD::CVT_F32_UBYTE1:
1751 case AMDGPUISD::CVT_F32_UBYTE2:
1752 case AMDGPUISD::CVT_F32_UBYTE3: {
1753 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1755 SDValue Src = N->getOperand(0);
1756 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1758 APInt KnownZero, KnownOne;
1759 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1760 !DCI.isBeforeLegalizeOps());
1761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1762 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1763 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1764 DCI.CommitTargetLoweringOpt(TLO);
1770 case ISD::UINT_TO_FP: {
1771 return performUCharToFloatCombine(N, DCI);
1774 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1777 EVT VT = N->getValueType(0);
1781 // Only do this if we are not trying to support denormals. v_mad_f32 does
1782 // not support denormals ever.
1783 if (Subtarget->hasFP32Denormals())
1786 SDValue LHS = N->getOperand(0);
1787 SDValue RHS = N->getOperand(1);
1789 // These should really be instruction patterns, but writing patterns with
1790 // source modiifiers is a pain.
1792 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1793 if (LHS.getOpcode() == ISD::FADD) {
1794 SDValue A = LHS.getOperand(0);
1795 if (A == LHS.getOperand(1)) {
1796 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1797 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1801 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1802 if (RHS.getOpcode() == ISD::FADD) {
1803 SDValue A = RHS.getOperand(0);
1804 if (A == RHS.getOperand(1)) {
1805 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1806 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1813 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1816 EVT VT = N->getValueType(0);
1818 // Try to get the fneg to fold into the source modifier. This undoes generic
1819 // DAG combines and folds them into the mad.
1821 // Only do this if we are not trying to support denormals. v_mad_f32 does
1822 // not support denormals ever.
1823 if (VT == MVT::f32 &&
1824 !Subtarget->hasFP32Denormals()) {
1825 SDValue LHS = N->getOperand(0);
1826 SDValue RHS = N->getOperand(1);
1827 if (LHS.getOpcode() == ISD::FADD) {
1828 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1830 SDValue A = LHS.getOperand(0);
1831 if (A == LHS.getOperand(1)) {
1832 const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1833 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1835 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1839 if (RHS.getOpcode() == ISD::FADD) {
1840 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1842 SDValue A = RHS.getOperand(0);
1843 if (A == RHS.getOperand(1)) {
1844 const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1845 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1857 case ISD::ATOMIC_LOAD:
1858 case ISD::ATOMIC_STORE:
1859 case ISD::ATOMIC_CMP_SWAP:
1860 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1861 case ISD::ATOMIC_SWAP:
1862 case ISD::ATOMIC_LOAD_ADD:
1863 case ISD::ATOMIC_LOAD_SUB:
1864 case ISD::ATOMIC_LOAD_AND:
1865 case ISD::ATOMIC_LOAD_OR:
1866 case ISD::ATOMIC_LOAD_XOR:
1867 case ISD::ATOMIC_LOAD_NAND:
1868 case ISD::ATOMIC_LOAD_MIN:
1869 case ISD::ATOMIC_LOAD_MAX:
1870 case ISD::ATOMIC_LOAD_UMIN:
1871 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1872 if (DCI.isBeforeLegalize())
1875 MemSDNode *MemNode = cast<MemSDNode>(N);
1876 SDValue Ptr = MemNode->getBasePtr();
1878 // TODO: We could also do this for multiplies.
1879 unsigned AS = MemNode->getAddressSpace();
1880 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1881 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1883 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1885 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1886 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1892 return performAndCombine(N, DCI);
1894 return performOrCombine(N, DCI);
1895 case AMDGPUISD::FP_CLASS:
1896 return performClassCombine(N, DCI);
1898 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1901 /// \brief Analyze the possible immediate value Op
1903 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1904 /// and the immediate value if it's a literal immediate
1905 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1907 const SIInstrInfo *TII =
1908 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1910 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1911 if (TII->isInlineConstant(Node->getAPIntValue()))
1914 uint64_t Val = Node->getZExtValue();
1915 return isUInt<32>(Val) ? Val : -1;
1918 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1919 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1922 if (Node->getValueType(0) == MVT::f32)
1923 return FloatToBits(Node->getValueAPF().convertToFloat());
1931 /// \brief Helper function for adjustWritemask
1932 static unsigned SubIdx2Lane(unsigned Idx) {
1935 case AMDGPU::sub0: return 0;
1936 case AMDGPU::sub1: return 1;
1937 case AMDGPU::sub2: return 2;
1938 case AMDGPU::sub3: return 3;
1942 /// \brief Adjust the writemask of MIMG instructions
1943 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1944 SelectionDAG &DAG) const {
1945 SDNode *Users[4] = { };
1947 unsigned OldDmask = Node->getConstantOperandVal(0);
1948 unsigned NewDmask = 0;
1950 // Try to figure out the used register components
1951 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1954 // Abort if we can't understand the usage
1955 if (!I->isMachineOpcode() ||
1956 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1959 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1960 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1961 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1963 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1965 // Set which texture component corresponds to the lane.
1967 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1969 Comp = countTrailingZeros(Dmask);
1970 Dmask &= ~(1 << Comp);
1973 // Abort if we have more than one user per component
1978 NewDmask |= 1 << Comp;
1981 // Abort if there's no change
1982 if (NewDmask == OldDmask)
1985 // Adjust the writemask in the node
1986 std::vector<SDValue> Ops;
1987 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
1988 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
1989 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1991 // If we only got one lane, replace it with a copy
1992 // (if NewDmask has only one bit set...)
1993 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1994 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
1996 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1997 SDLoc(), Users[Lane]->getValueType(0),
1998 SDValue(Node, 0), RC);
1999 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2003 // Update the users of the node with the new indices
2004 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2006 SDNode *User = Users[i];
2010 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2011 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2015 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2016 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2017 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2022 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2023 /// with frame index operands.
2024 /// LLVM assumes that inputs are to these instructions are registers.
2025 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2026 SelectionDAG &DAG) const {
2028 SmallVector<SDValue, 8> Ops;
2029 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2030 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
2031 Ops.push_back(Node->getOperand(i));
2036 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2037 Node->getOperand(i).getValueType(),
2038 Node->getOperand(i)), 0));
2041 DAG.UpdateNodeOperands(Node, Ops);
2044 /// \brief Fold the instructions after selecting them.
2045 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2046 SelectionDAG &DAG) const {
2047 const SIInstrInfo *TII =
2048 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2050 if (TII->isMIMG(Node->getMachineOpcode()))
2051 adjustWritemask(Node, DAG);
2053 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2054 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2055 legalizeTargetIndependentNode(Node, DAG);
2061 /// \brief Assign the register class depending on the number of
2062 /// bits set in the writemask
2063 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2064 SDNode *Node) const {
2065 const SIInstrInfo *TII =
2066 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2068 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2069 TII->legalizeOperands(MI);
2071 if (TII->isMIMG(MI->getOpcode())) {
2072 unsigned VReg = MI->getOperand(0).getReg();
2073 unsigned Writemask = MI->getOperand(1).getImm();
2074 unsigned BitsSet = 0;
2075 for (unsigned i = 0; i < 4; ++i)
2076 BitsSet += Writemask & (1 << i) ? 1 : 0;
2078 const TargetRegisterClass *RC;
2081 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
2082 case 2: RC = &AMDGPU::VReg_64RegClass; break;
2083 case 3: RC = &AMDGPU::VReg_96RegClass; break;
2086 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2087 MI->setDesc(TII->get(NewOpcode));
2088 MRI.setRegClass(VReg, RC);
2092 // Replace unused atomics with the no return version.
2093 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2094 if (NoRetAtomicOp != -1) {
2095 if (!Node->hasAnyUseOfValue(0)) {
2096 MI->setDesc(TII->get(NoRetAtomicOp));
2097 MI->RemoveOperand(0);
2104 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2105 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2106 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2109 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2111 SDValue Ptr) const {
2112 const SIInstrInfo *TII =
2113 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2115 // XXX - Workaround for moveToVALU not handling different register class
2116 // inserts for REG_SEQUENCE.
2118 // Build the half of the subregister with the constants.
2119 const SDValue Ops0[] = {
2120 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2121 buildSMovImm32(DAG, DL, 0),
2122 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2123 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2124 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2127 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2128 MVT::v2i32, Ops0), 0);
2130 // Combine the constants and the pointer.
2131 const SDValue Ops1[] = {
2132 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2134 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2136 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2139 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2141 const SDValue Ops[] = {
2142 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2144 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2145 buildSMovImm32(DAG, DL, 0),
2146 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2147 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2148 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2151 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2156 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2157 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2158 /// of the resource descriptor) to create an offset, which is added to the
2159 /// resource ponter.
2160 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2163 uint32_t RsrcDword1,
2164 uint64_t RsrcDword2And3) const {
2165 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2166 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2168 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2169 DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2173 SDValue DataLo = buildSMovImm32(DAG, DL,
2174 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2175 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2177 const SDValue Ops[] = {
2178 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2180 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2182 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2184 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2186 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2189 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2192 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2194 SDValue Ptr) const {
2195 const SIInstrInfo *TII =
2196 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2197 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2200 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2203 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2204 const TargetRegisterClass *RC,
2205 unsigned Reg, EVT VT) const {
2206 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2208 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2209 cast<RegisterSDNode>(VReg)->getReg(), VT);
2212 //===----------------------------------------------------------------------===//
2213 // SI Inline Assembly Support
2214 //===----------------------------------------------------------------------===//
2216 std::pair<unsigned, const TargetRegisterClass *>
2217 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2218 StringRef Constraint,
2220 if (Constraint == "r") {
2221 switch(VT.SimpleTy) {
2222 default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2224 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2226 return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2230 if (Constraint.size() > 1) {
2231 const TargetRegisterClass *RC = nullptr;
2232 if (Constraint[1] == 'v') {
2233 RC = &AMDGPU::VGPR_32RegClass;
2234 } else if (Constraint[1] == 's') {
2235 RC = &AMDGPU::SGPR_32RegClass;
2240 bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2241 if (!Failed && Idx < RC->getNumRegs())
2242 return std::make_pair(RC->getRegister(Idx), RC);
2245 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);