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::f32, Legal);
80 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
81 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
82 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
84 // We need to custom lower vector stores from local memory
85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
90 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
92 setOperationAction(ISD::STORE, MVT::i1, Custom);
93 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
95 setOperationAction(ISD::SELECT, MVT::i64, Custom);
96 setOperationAction(ISD::SELECT, MVT::f64, Promote);
97 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
99 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
100 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
101 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
104 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
105 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
107 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
109 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
110 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
124 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
129 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
130 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
132 for (MVT VT : MVT::integer_valuetypes()) {
136 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
138 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
141 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
142 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
143 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
144 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
146 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
147 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
148 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
149 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
152 for (MVT VT : MVT::integer_vector_valuetypes()) {
153 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
154 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
157 for (MVT VT : MVT::fp_valuetypes())
158 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
160 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
161 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
162 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
163 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
165 setOperationAction(ISD::LOAD, MVT::i1, Custom);
167 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
169 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
171 // These should use UDIVREM, so set them to expand
172 setOperationAction(ISD::UDIV, MVT::i64, Expand);
173 setOperationAction(ISD::UREM, MVT::i64, Expand);
175 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
176 setOperationAction(ISD::SELECT, MVT::i1, Promote);
178 // We only support LOAD/STORE and vector manipulation ops for vectors
179 // with > 4 elements.
180 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32}) {
181 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
185 case ISD::BUILD_VECTOR:
187 case ISD::EXTRACT_VECTOR_ELT:
188 case ISD::INSERT_VECTOR_ELT:
189 case ISD::INSERT_SUBVECTOR:
190 case ISD::EXTRACT_SUBVECTOR:
192 case ISD::CONCAT_VECTORS:
193 setOperationAction(Op, VT, Custom);
196 setOperationAction(Op, VT, Expand);
202 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
203 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
204 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
205 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
206 setOperationAction(ISD::FRINT, MVT::f64, Legal);
209 setOperationAction(ISD::FDIV, MVT::f32, Custom);
210 setOperationAction(ISD::FDIV, MVT::f64, Custom);
212 setTargetDAGCombine(ISD::FADD);
213 setTargetDAGCombine(ISD::FSUB);
214 setTargetDAGCombine(ISD::FMINNUM);
215 setTargetDAGCombine(ISD::FMAXNUM);
216 setTargetDAGCombine(ISD::SELECT_CC);
217 setTargetDAGCombine(ISD::SETCC);
218 setTargetDAGCombine(ISD::AND);
219 setTargetDAGCombine(ISD::OR);
220 setTargetDAGCombine(ISD::UINT_TO_FP);
222 // All memory operations. Some folding on the pointer operand is done to help
223 // matching the constant offsets in the addressing modes.
224 setTargetDAGCombine(ISD::LOAD);
225 setTargetDAGCombine(ISD::STORE);
226 setTargetDAGCombine(ISD::ATOMIC_LOAD);
227 setTargetDAGCombine(ISD::ATOMIC_STORE);
228 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
229 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
230 setTargetDAGCombine(ISD::ATOMIC_SWAP);
231 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
232 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
242 setSchedulingPreference(Sched::RegPressure);
245 //===----------------------------------------------------------------------===//
246 // TargetLowering queries
247 //===----------------------------------------------------------------------===//
249 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
251 // SI has some legal vector types, but no legal vector operations. Say no
252 // shuffles are legal in order to prefer scalarizing some vector operations.
256 // FIXME: This really needs an address space argument. The immediate offset
257 // size is different for different sets of memory instruction sets.
259 // The single offset DS instructions have a 16-bit unsigned byte offset.
261 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
262 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
263 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
265 // SMRD instructions have an 8-bit, dword offset.
267 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
269 // No global is ever allowed as a base.
273 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
275 if (!isUInt<16>(AM.BaseOffs))
280 case 0: // "r+i" or just "i", depending on HasBaseReg.
283 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
285 // Otherwise we have r+r or r+i.
288 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
292 default: // Don't allow n * r
299 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
302 bool *IsFast) const {
306 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
307 // which isn't a simple VT.
308 if (!VT.isSimple() || VT == MVT::Other)
311 // TODO - CI+ supports unaligned memory accesses, but this requires driver
314 // XXX - The only mention I see of this in the ISA manual is for LDS direct
315 // reads the "byte address and must be dword aligned". Is it also true for the
316 // normal loads and stores?
317 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
318 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
319 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
320 // with adjacent offsets.
321 return Align % 4 == 0;
324 // Smaller than dword value must be aligned.
325 // FIXME: This should be allowed on CI+
326 if (VT.bitsLT(MVT::i32))
329 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
330 // byte-address are ignored, thus forcing Dword alignment.
331 // This applies to private, global, and constant memory.
335 return VT.bitsGT(MVT::i32) && Align % 4 == 0;
338 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
339 unsigned SrcAlign, bool IsMemset,
342 MachineFunction &MF) const {
343 // FIXME: Should account for address space here.
345 // The default fallback uses the private pointer size as a guess for a type to
346 // use. Make sure we switch these to 64-bit accesses.
348 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
351 if (Size >= 8 && DstAlign >= 4)
358 TargetLoweringBase::LegalizeTypeAction
359 SITargetLowering::getPreferredVectorAction(EVT VT) const {
360 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
361 return TypeSplitVector;
363 return TargetLoweringBase::getPreferredVectorAction(VT);
366 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
368 const SIInstrInfo *TII =
369 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
370 return TII->isInlineConstant(Imm);
373 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
374 SDLoc SL, SDValue Chain,
375 unsigned Offset, bool Signed) const {
376 const DataLayout *DL = getDataLayout();
377 MachineFunction &MF = DAG.getMachineFunction();
378 const SIRegisterInfo *TRI =
379 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
380 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
382 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
384 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
385 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
386 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
387 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
388 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
389 DAG.getConstant(Offset, MVT::i64));
390 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
391 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
393 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
394 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
396 true, // isNonTemporal
398 DL->getABITypeAlignment(Ty)); // Alignment
401 SDValue SITargetLowering::LowerFormalArguments(
402 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
403 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
404 SmallVectorImpl<SDValue> &InVals) const {
405 const SIRegisterInfo *TRI =
406 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
408 MachineFunction &MF = DAG.getMachineFunction();
409 FunctionType *FType = MF.getFunction()->getFunctionType();
410 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
412 assert(CallConv == CallingConv::C);
414 SmallVector<ISD::InputArg, 16> Splits;
415 BitVector Skipped(Ins.size());
417 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
418 const ISD::InputArg &Arg = Ins[i];
420 // First check if it's a PS input addr
421 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
422 !Arg.Flags.isByVal()) {
424 assert((PSInputNum <= 15) && "Too many PS inputs!");
427 // We can savely skip PS inputs
433 Info->PSInputAddr |= 1 << PSInputNum++;
436 // Second split vertices into their elements
437 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
438 ISD::InputArg NewArg = Arg;
439 NewArg.Flags.setSplit();
440 NewArg.VT = Arg.VT.getVectorElementType();
442 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
443 // three or five element vertex only needs three or five registers,
444 // NOT four or eigth.
445 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
446 unsigned NumElements = ParamType->getVectorNumElements();
448 for (unsigned j = 0; j != NumElements; ++j) {
449 Splits.push_back(NewArg);
450 NewArg.PartOffset += NewArg.VT.getStoreSize();
453 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
454 Splits.push_back(Arg);
458 SmallVector<CCValAssign, 16> ArgLocs;
459 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
462 // At least one interpolation mode must be enabled or else the GPU will hang.
463 if (Info->getShaderType() == ShaderType::PIXEL &&
464 (Info->PSInputAddr & 0x7F) == 0) {
465 Info->PSInputAddr |= 1;
466 CCInfo.AllocateReg(AMDGPU::VGPR0);
467 CCInfo.AllocateReg(AMDGPU::VGPR1);
470 // The pointer to the list of arguments is stored in SGPR0, SGPR1
471 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
472 if (Info->getShaderType() == ShaderType::COMPUTE) {
473 if (Subtarget->isAmdHsaOS())
474 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
476 Info->NumUserSGPRs = 4;
478 unsigned InputPtrReg =
479 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
480 unsigned InputPtrRegLo =
481 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
482 unsigned InputPtrRegHi =
483 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
485 unsigned ScratchPtrReg =
486 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
487 unsigned ScratchPtrRegLo =
488 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
489 unsigned ScratchPtrRegHi =
490 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
492 CCInfo.AllocateReg(InputPtrRegLo);
493 CCInfo.AllocateReg(InputPtrRegHi);
494 CCInfo.AllocateReg(ScratchPtrRegLo);
495 CCInfo.AllocateReg(ScratchPtrRegHi);
496 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
497 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
500 if (Info->getShaderType() == ShaderType::COMPUTE) {
501 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
505 AnalyzeFormalArguments(CCInfo, Splits);
507 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
509 const ISD::InputArg &Arg = Ins[i];
511 InVals.push_back(DAG.getUNDEF(Arg.VT));
515 CCValAssign &VA = ArgLocs[ArgIdx++];
516 MVT VT = VA.getLocVT();
520 EVT MemVT = Splits[i].VT;
521 const unsigned Offset = 36 + VA.getLocMemOffset();
522 // The first 36 bytes of the input buffer contains information about
523 // thread group and global sizes.
524 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
525 Offset, Ins[i].Flags.isSExt());
527 const PointerType *ParamTy =
528 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
529 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
530 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
531 // On SI local pointers are just offsets into LDS, so they are always
532 // less than 16-bits. On CI and newer they could potentially be
533 // real pointers, so we can't guarantee their size.
534 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
535 DAG.getValueType(MVT::i16));
538 InVals.push_back(Arg);
539 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
542 assert(VA.isRegLoc() && "Parameter must be in a register!");
544 unsigned Reg = VA.getLocReg();
546 if (VT == MVT::i64) {
547 // For now assume it is a pointer
548 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
549 &AMDGPU::SReg_64RegClass);
550 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
551 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
555 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
557 Reg = MF.addLiveIn(Reg, RC);
558 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
560 if (Arg.VT.isVector()) {
562 // Build a vector from the registers
563 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
564 unsigned NumElements = ParamType->getVectorNumElements();
566 SmallVector<SDValue, 4> Regs;
568 for (unsigned j = 1; j != NumElements; ++j) {
569 Reg = ArgLocs[ArgIdx++].getLocReg();
570 Reg = MF.addLiveIn(Reg, RC);
571 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
574 // Fill up the missing vector elements
575 NumElements = Arg.VT.getVectorNumElements() - NumElements;
576 Regs.append(NumElements, DAG.getUNDEF(VT));
578 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
582 InVals.push_back(Val);
585 if (Info->getShaderType() != ShaderType::COMPUTE) {
586 unsigned ScratchIdx = CCInfo.getFirstUnallocated(ArrayRef<MCPhysReg>(
587 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
588 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
593 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
594 MachineInstr * MI, MachineBasicBlock * BB) const {
596 MachineBasicBlock::iterator I = *MI;
597 const SIInstrInfo *TII =
598 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
600 switch (MI->getOpcode()) {
602 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
605 case AMDGPU::SI_RegisterStorePseudo: {
606 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
607 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
608 MachineInstrBuilder MIB =
609 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
611 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
612 MIB.addOperand(MI->getOperand(i));
614 MI->eraseFromParent();
621 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
622 // This currently forces unfolding various combinations of fsub into fma with
623 // free fneg'd operands. As long as we have fast FMA (controlled by
624 // isFMAFasterThanFMulAndFAdd), we should perform these.
626 // When fma is quarter rate, for f64 where add / sub are at best half rate,
627 // most of these combines appear to be cycle neutral but save on instruction
628 // count / code size.
632 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
633 if (!VT.isVector()) {
636 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
639 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
643 // Answering this is somewhat tricky and depends on the specific device which
644 // have different rates for fma or all f64 operations.
646 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
647 // regardless of which device (although the number of cycles differs between
648 // devices), so it is always profitable for f64.
650 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
651 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
652 // which we can always do even without fused FP ops since it returns the same
653 // result as the separate operations and since it is always full
654 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
655 // however does not support denormals, so we do report fma as faster if we have
656 // a fast fma device and require denormals.
658 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
659 VT = VT.getScalarType();
664 switch (VT.getSimpleVT().SimpleTy) {
666 // This is as fast on some subtargets. However, we always have full rate f32
667 // mad available which returns the same result as the separate operations
668 // which we should prefer over fma. We can't use this if we want to support
669 // denormals, so only report this in these cases.
670 return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
680 //===----------------------------------------------------------------------===//
681 // Custom DAG Lowering Operations
682 //===----------------------------------------------------------------------===//
684 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
685 switch (Op.getOpcode()) {
686 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
687 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
688 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
690 SDValue Result = LowerLOAD(Op, DAG);
691 assert((!Result.getNode() ||
692 Result.getNode()->getNumValues() == 2) &&
693 "Load should return a value and a chain");
699 return LowerTrig(Op, DAG);
700 case ISD::SELECT: return LowerSELECT(Op, DAG);
701 case ISD::FDIV: return LowerFDIV(Op, DAG);
702 case ISD::STORE: return LowerSTORE(Op, DAG);
703 case ISD::GlobalAddress: {
704 MachineFunction &MF = DAG.getMachineFunction();
705 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
706 return LowerGlobalAddress(MFI, Op, DAG);
708 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
709 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
714 /// \brief Helper function for LowerBRCOND
715 static SDNode *findUser(SDValue Value, unsigned Opcode) {
717 SDNode *Parent = Value.getNode();
718 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
721 if (I.getUse().get() != Value)
724 if (I->getOpcode() == Opcode)
730 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
732 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
733 unsigned FrameIndex = FINode->getIndex();
735 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
738 /// This transforms the control flow intrinsics to get the branch destination as
739 /// last parameter, also switches branch target with BR if the need arise
740 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
741 SelectionDAG &DAG) const {
745 SDNode *Intr = BRCOND.getOperand(1).getNode();
746 SDValue Target = BRCOND.getOperand(2);
747 SDNode *BR = nullptr;
749 if (Intr->getOpcode() == ISD::SETCC) {
750 // As long as we negate the condition everything is fine
751 SDNode *SetCC = Intr;
752 assert(SetCC->getConstantOperandVal(1) == 1);
753 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
755 Intr = SetCC->getOperand(0).getNode();
758 // Get the target from BR if we don't negate the condition
759 BR = findUser(BRCOND, ISD::BR);
760 Target = BR->getOperand(1);
763 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
765 // Build the result and
766 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
768 // operands of the new intrinsic call
769 SmallVector<SDValue, 4> Ops;
770 Ops.push_back(BRCOND.getOperand(0));
771 Ops.append(Intr->op_begin() + 1, Intr->op_end());
772 Ops.push_back(Target);
774 // build the new intrinsic call
775 SDNode *Result = DAG.getNode(
776 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
777 DAG.getVTList(Res), Ops).getNode();
780 // Give the branch instruction our target
785 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
786 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
787 BR = NewBR.getNode();
790 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
792 // Copy the intrinsic results to registers
793 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
794 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
798 Chain = DAG.getCopyToReg(
800 CopyToReg->getOperand(1),
801 SDValue(Result, i - 1),
804 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
807 // Remove the old intrinsic from the chain
808 DAG.ReplaceAllUsesOfValueWith(
809 SDValue(Intr, Intr->getNumValues() - 1),
810 Intr->getOperand(0));
815 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
817 SelectionDAG &DAG) const {
818 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
820 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
821 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
824 const GlobalValue *GV = GSD->getGlobal();
825 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
827 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
828 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
830 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
831 DAG.getConstant(0, MVT::i32));
832 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
833 DAG.getConstant(1, MVT::i32));
835 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
837 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
838 PtrHi, DAG.getConstant(0, MVT::i32),
839 SDValue(Lo.getNode(), 1));
840 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
843 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
844 SelectionDAG &DAG) const {
845 MachineFunction &MF = DAG.getMachineFunction();
846 const SIRegisterInfo *TRI =
847 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
849 EVT VT = Op.getValueType();
851 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
853 switch (IntrinsicID) {
854 case Intrinsic::r600_read_ngroups_x:
855 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
856 SI::KernelInputOffsets::NGROUPS_X, false);
857 case Intrinsic::r600_read_ngroups_y:
858 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
859 SI::KernelInputOffsets::NGROUPS_Y, false);
860 case Intrinsic::r600_read_ngroups_z:
861 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
862 SI::KernelInputOffsets::NGROUPS_Z, false);
863 case Intrinsic::r600_read_global_size_x:
864 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
865 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
866 case Intrinsic::r600_read_global_size_y:
867 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
868 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
869 case Intrinsic::r600_read_global_size_z:
870 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
871 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
872 case Intrinsic::r600_read_local_size_x:
873 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
874 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
875 case Intrinsic::r600_read_local_size_y:
876 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
877 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
878 case Intrinsic::r600_read_local_size_z:
879 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
880 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
882 case Intrinsic::AMDGPU_read_workdim:
883 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
884 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
887 case Intrinsic::r600_read_tgid_x:
888 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
889 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
890 case Intrinsic::r600_read_tgid_y:
891 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
892 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
893 case Intrinsic::r600_read_tgid_z:
894 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
895 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
896 case Intrinsic::r600_read_tidig_x:
897 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
898 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
899 case Intrinsic::r600_read_tidig_y:
900 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
901 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
902 case Intrinsic::r600_read_tidig_z:
903 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
904 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
905 case AMDGPUIntrinsic::SI_load_const: {
911 MachineMemOperand *MMO = MF.getMachineMemOperand(
912 MachinePointerInfo(),
913 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
914 VT.getStoreSize(), 4);
915 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
916 Op->getVTList(), Ops, VT, MMO);
918 case AMDGPUIntrinsic::SI_sample:
919 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
920 case AMDGPUIntrinsic::SI_sampleb:
921 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
922 case AMDGPUIntrinsic::SI_sampled:
923 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
924 case AMDGPUIntrinsic::SI_samplel:
925 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
926 case AMDGPUIntrinsic::SI_vs_load_input:
927 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
932 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
936 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
937 SelectionDAG &DAG) const {
938 MachineFunction &MF = DAG.getMachineFunction();
939 SDValue Chain = Op.getOperand(0);
940 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
942 switch (IntrinsicID) {
943 case AMDGPUIntrinsic::SI_tbuffer_store: {
962 EVT VT = Op.getOperand(3).getValueType();
964 MachineMemOperand *MMO = MF.getMachineMemOperand(
965 MachinePointerInfo(),
966 MachineMemOperand::MOStore,
967 VT.getStoreSize(), 4);
968 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
969 Op->getVTList(), Ops, VT, MMO);
976 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
978 LoadSDNode *Load = cast<LoadSDNode>(Op);
980 if (Op.getValueType().isVector()) {
981 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
982 "Custom lowering for non-i32 vectors hasn't been implemented.");
983 unsigned NumElements = Op.getValueType().getVectorNumElements();
984 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
985 switch (Load->getAddressSpace()) {
987 case AMDGPUAS::GLOBAL_ADDRESS:
988 case AMDGPUAS::PRIVATE_ADDRESS:
989 // v4 loads are supported for private and global memory.
990 if (NumElements <= 4)
993 case AMDGPUAS::LOCAL_ADDRESS:
994 return ScalarizeVectorLoad(Op, DAG);
998 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1001 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1003 SelectionDAG &DAG) const {
1004 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1010 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1011 if (Op.getValueType() != MVT::i64)
1015 SDValue Cond = Op.getOperand(0);
1017 SDValue Zero = DAG.getConstant(0, MVT::i32);
1018 SDValue One = DAG.getConstant(1, MVT::i32);
1020 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1021 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1023 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1024 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1026 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1028 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1029 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1031 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1033 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1034 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1037 // Catch division cases where we can use shortcuts with rcp and rsq
1039 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1041 SDValue LHS = Op.getOperand(0);
1042 SDValue RHS = Op.getOperand(1);
1043 EVT VT = Op.getValueType();
1044 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1046 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1047 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1048 CLHS->isExactlyValue(1.0)) {
1049 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1050 // the CI documentation has a worst case error of 1 ulp.
1051 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1052 // use it as long as we aren't trying to use denormals.
1054 // 1.0 / sqrt(x) -> rsq(x)
1056 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1057 // error seems really high at 2^29 ULP.
1058 if (RHS.getOpcode() == ISD::FSQRT)
1059 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1061 // 1.0 / x -> rcp(x)
1062 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1067 // Turn into multiply by the reciprocal.
1068 // x / y -> x * (1.0 / y)
1069 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1070 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1076 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1077 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1078 if (FastLowered.getNode())
1081 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1082 // selection error for now rather than do something incorrect.
1083 if (Subtarget->hasFP32Denormals())
1087 SDValue LHS = Op.getOperand(0);
1088 SDValue RHS = Op.getOperand(1);
1090 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1092 const APFloat K0Val(BitsToFloat(0x6f800000));
1093 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1095 const APFloat K1Val(BitsToFloat(0x2f800000));
1096 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1098 const SDValue One = DAG.getConstantFP(1.0, MVT::f32);
1100 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1102 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1104 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1106 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1108 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1110 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1112 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1115 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1116 if (DAG.getTarget().Options.UnsafeFPMath)
1117 return LowerFastFDIV(Op, DAG);
1120 SDValue X = Op.getOperand(0);
1121 SDValue Y = Op.getOperand(1);
1123 const SDValue One = DAG.getConstantFP(1.0, MVT::f64);
1125 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1127 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1129 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1131 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1133 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1135 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1137 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1139 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1141 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1142 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1144 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1145 NegDivScale0, Mul, DivScale1);
1149 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1150 // Workaround a hardware bug on SI where the condition output from div_scale
1153 const SDValue Hi = DAG.getConstant(1, MVT::i32);
1155 // Figure out if the scale to use for div_fmas.
1156 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1157 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1158 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1159 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1161 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1162 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1165 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1167 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1169 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1170 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1171 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1173 Scale = DivScale1.getValue(1);
1176 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1177 Fma4, Fma3, Mul, Scale);
1179 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1182 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1183 EVT VT = Op.getValueType();
1186 return LowerFDIV32(Op, DAG);
1189 return LowerFDIV64(Op, DAG);
1191 llvm_unreachable("Unexpected type for fdiv");
1194 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1196 StoreSDNode *Store = cast<StoreSDNode>(Op);
1197 EVT VT = Store->getMemoryVT();
1199 // These stores are legal.
1200 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1201 if (VT.isVector() && VT.getVectorNumElements() > 4)
1202 return ScalarizeVectorStore(Op, DAG);
1206 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1210 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1211 return ScalarizeVectorStore(Op, DAG);
1214 return DAG.getTruncStore(Store->getChain(), DL,
1215 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1216 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1221 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1222 EVT VT = Op.getValueType();
1223 SDValue Arg = Op.getOperand(0);
1224 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1225 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1226 DAG.getConstantFP(0.5 / M_PI, VT)));
1228 switch (Op.getOpcode()) {
1230 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1232 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1234 llvm_unreachable("Wrong trig opcode");
1238 //===----------------------------------------------------------------------===//
1239 // Custom DAG optimizations
1240 //===----------------------------------------------------------------------===//
1242 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1243 DAGCombinerInfo &DCI) const {
1244 EVT VT = N->getValueType(0);
1245 EVT ScalarVT = VT.getScalarType();
1246 if (ScalarVT != MVT::f32)
1249 SelectionDAG &DAG = DCI.DAG;
1252 SDValue Src = N->getOperand(0);
1253 EVT SrcVT = Src.getValueType();
1255 // TODO: We could try to match extracting the higher bytes, which would be
1256 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1257 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1258 // about in practice.
1259 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1260 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1261 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1262 DCI.AddToWorklist(Cvt.getNode());
1267 // We are primarily trying to catch operations on illegal vector types
1268 // before they are expanded.
1269 // For scalars, we can use the more flexible method of checking masked bits
1270 // after legalization.
1271 if (!DCI.isBeforeLegalize() ||
1272 !SrcVT.isVector() ||
1273 SrcVT.getVectorElementType() != MVT::i8) {
1277 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1279 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1281 unsigned NElts = SrcVT.getVectorNumElements();
1282 if (!SrcVT.isSimple() && NElts != 3)
1285 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1286 // prevent a mess from expanding to v4i32 and repacking.
1287 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1288 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1289 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1290 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1291 LoadSDNode *Load = cast<LoadSDNode>(Src);
1293 unsigned AS = Load->getAddressSpace();
1294 unsigned Align = Load->getAlignment();
1295 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1296 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1298 // Don't try to replace the load if we have to expand it due to alignment
1299 // problems. Otherwise we will end up scalarizing the load, and trying to
1300 // repack into the vector for no real reason.
1301 if (Align < ABIAlignment &&
1302 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1306 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1310 Load->getMemOperand());
1312 // Make sure successors of the original load stay after it by updating
1313 // them to use the new Chain.
1314 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1316 SmallVector<SDValue, 4> Elts;
1317 if (RegVT.isVector())
1318 DAG.ExtractVectorElements(NewLoad, Elts);
1320 Elts.push_back(NewLoad);
1322 SmallVector<SDValue, 4> Ops;
1324 unsigned EltIdx = 0;
1325 for (SDValue Elt : Elts) {
1326 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1327 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1328 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1329 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1330 DCI.AddToWorklist(Cvt.getNode());
1337 assert(Ops.size() == NElts);
1339 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1345 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1347 // This is a variant of
1348 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1350 // The normal DAG combiner will do this, but only if the add has one use since
1351 // that would increase the number of instructions.
1353 // This prevents us from seeing a constant offset that can be folded into a
1354 // memory instruction's addressing mode. If we know the resulting add offset of
1355 // a pointer can be folded into an addressing offset, we can replace the pointer
1356 // operand with the add of new constant offset. This eliminates one of the uses,
1357 // and may allow the remaining use to also be simplified.
1359 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1361 DAGCombinerInfo &DCI) const {
1362 SDValue N0 = N->getOperand(0);
1363 SDValue N1 = N->getOperand(1);
1365 if (N0.getOpcode() != ISD::ADD)
1368 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1372 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1376 const SIInstrInfo *TII =
1377 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1379 // If the resulting offset is too large, we can't fold it into the addressing
1381 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1382 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1385 SelectionDAG &DAG = DCI.DAG;
1387 EVT VT = N->getValueType(0);
1389 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1390 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1392 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1395 SDValue SITargetLowering::performAndCombine(SDNode *N,
1396 DAGCombinerInfo &DCI) const {
1397 if (DCI.isBeforeLegalize())
1400 SelectionDAG &DAG = DCI.DAG;
1402 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1403 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1404 SDValue LHS = N->getOperand(0);
1405 SDValue RHS = N->getOperand(1);
1407 if (LHS.getOpcode() == ISD::SETCC &&
1408 RHS.getOpcode() == ISD::SETCC) {
1409 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1410 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1412 SDValue X = LHS.getOperand(0);
1413 SDValue Y = RHS.getOperand(0);
1414 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1417 if (LCC == ISD::SETO) {
1418 if (X != LHS.getOperand(1))
1421 if (RCC == ISD::SETUNE) {
1422 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1423 if (!C1 || !C1->isInfinity() || C1->isNegative())
1426 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1427 SIInstrFlags::N_SUBNORMAL |
1428 SIInstrFlags::N_ZERO |
1429 SIInstrFlags::P_ZERO |
1430 SIInstrFlags::P_SUBNORMAL |
1431 SIInstrFlags::P_NORMAL;
1433 static_assert(((~(SIInstrFlags::S_NAN |
1434 SIInstrFlags::Q_NAN |
1435 SIInstrFlags::N_INFINITY |
1436 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1439 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1440 X, DAG.getConstant(Mask, MVT::i32));
1448 SDValue SITargetLowering::performOrCombine(SDNode *N,
1449 DAGCombinerInfo &DCI) const {
1450 SelectionDAG &DAG = DCI.DAG;
1451 SDValue LHS = N->getOperand(0);
1452 SDValue RHS = N->getOperand(1);
1454 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1455 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1456 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1457 SDValue Src = LHS.getOperand(0);
1458 if (Src != RHS.getOperand(0))
1461 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1462 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1466 // Only 10 bits are used.
1467 static const uint32_t MaxMask = 0x3ff;
1469 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1470 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1471 Src, DAG.getConstant(NewMask, MVT::i32));
1477 SDValue SITargetLowering::performClassCombine(SDNode *N,
1478 DAGCombinerInfo &DCI) const {
1479 SelectionDAG &DAG = DCI.DAG;
1480 SDValue Mask = N->getOperand(1);
1482 // fp_class x, 0 -> false
1483 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1484 if (CMask->isNullValue())
1485 return DAG.getConstant(0, MVT::i1);
1491 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1494 return AMDGPUISD::FMAX3;
1495 case AMDGPUISD::SMAX:
1496 return AMDGPUISD::SMAX3;
1497 case AMDGPUISD::UMAX:
1498 return AMDGPUISD::UMAX3;
1500 return AMDGPUISD::FMIN3;
1501 case AMDGPUISD::SMIN:
1502 return AMDGPUISD::SMIN3;
1503 case AMDGPUISD::UMIN:
1504 return AMDGPUISD::UMIN3;
1506 llvm_unreachable("Not a min/max opcode");
1510 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1511 DAGCombinerInfo &DCI) const {
1512 SelectionDAG &DAG = DCI.DAG;
1514 unsigned Opc = N->getOpcode();
1515 SDValue Op0 = N->getOperand(0);
1516 SDValue Op1 = N->getOperand(1);
1518 // Only do this if the inner op has one use since this will just increases
1519 // register pressure for no benefit.
1521 // max(max(a, b), c)
1522 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1524 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1532 // max(a, max(b, c))
1533 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1535 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1546 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1547 DAGCombinerInfo &DCI) const {
1548 SelectionDAG &DAG = DCI.DAG;
1551 SDValue LHS = N->getOperand(0);
1552 SDValue RHS = N->getOperand(1);
1553 EVT VT = LHS.getValueType();
1555 if (VT != MVT::f32 && VT != MVT::f64)
1558 // Match isinf pattern
1559 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1560 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1561 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1562 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1566 const APFloat &APF = CRHS->getValueAPF();
1567 if (APF.isInfinity() && !APF.isNegative()) {
1568 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1569 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1,
1570 LHS.getOperand(0), DAG.getConstant(Mask, MVT::i32));
1577 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1578 DAGCombinerInfo &DCI) const {
1579 SelectionDAG &DAG = DCI.DAG;
1582 switch (N->getOpcode()) {
1584 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1586 return performSetCCCombine(N, DCI);
1587 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1589 case AMDGPUISD::SMAX:
1590 case AMDGPUISD::SMIN:
1591 case AMDGPUISD::UMAX:
1592 case AMDGPUISD::UMIN: {
1593 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1594 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1595 return performMin3Max3Combine(N, DCI);
1599 case AMDGPUISD::CVT_F32_UBYTE0:
1600 case AMDGPUISD::CVT_F32_UBYTE1:
1601 case AMDGPUISD::CVT_F32_UBYTE2:
1602 case AMDGPUISD::CVT_F32_UBYTE3: {
1603 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1605 SDValue Src = N->getOperand(0);
1606 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1608 APInt KnownZero, KnownOne;
1609 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1610 !DCI.isBeforeLegalizeOps());
1611 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1612 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1613 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1614 DCI.CommitTargetLoweringOpt(TLO);
1620 case ISD::UINT_TO_FP: {
1621 return performUCharToFloatCombine(N, DCI);
1624 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1627 EVT VT = N->getValueType(0);
1631 // Only do this if we are not trying to support denormals. v_mad_f32 does
1632 // not support denormals ever.
1633 if (Subtarget->hasFP32Denormals())
1636 SDValue LHS = N->getOperand(0);
1637 SDValue RHS = N->getOperand(1);
1639 // These should really be instruction patterns, but writing patterns with
1640 // source modiifiers is a pain.
1642 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1643 if (LHS.getOpcode() == ISD::FADD) {
1644 SDValue A = LHS.getOperand(0);
1645 if (A == LHS.getOperand(1)) {
1646 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1647 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1651 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1652 if (RHS.getOpcode() == ISD::FADD) {
1653 SDValue A = RHS.getOperand(0);
1654 if (A == RHS.getOperand(1)) {
1655 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1656 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1663 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1666 EVT VT = N->getValueType(0);
1668 // Try to get the fneg to fold into the source modifier. This undoes generic
1669 // DAG combines and folds them into the mad.
1671 // Only do this if we are not trying to support denormals. v_mad_f32 does
1672 // not support denormals ever.
1673 if (VT == MVT::f32 &&
1674 !Subtarget->hasFP32Denormals()) {
1675 SDValue LHS = N->getOperand(0);
1676 SDValue RHS = N->getOperand(1);
1677 if (LHS.getOpcode() == ISD::FADD) {
1678 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1680 SDValue A = LHS.getOperand(0);
1681 if (A == LHS.getOperand(1)) {
1682 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1683 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1685 return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1689 if (RHS.getOpcode() == ISD::FADD) {
1690 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1692 SDValue A = RHS.getOperand(0);
1693 if (A == RHS.getOperand(1)) {
1694 const SDValue NegTwo = DAG.getConstantFP(-2.0, MVT::f32);
1695 return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1707 case ISD::ATOMIC_LOAD:
1708 case ISD::ATOMIC_STORE:
1709 case ISD::ATOMIC_CMP_SWAP:
1710 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1711 case ISD::ATOMIC_SWAP:
1712 case ISD::ATOMIC_LOAD_ADD:
1713 case ISD::ATOMIC_LOAD_SUB:
1714 case ISD::ATOMIC_LOAD_AND:
1715 case ISD::ATOMIC_LOAD_OR:
1716 case ISD::ATOMIC_LOAD_XOR:
1717 case ISD::ATOMIC_LOAD_NAND:
1718 case ISD::ATOMIC_LOAD_MIN:
1719 case ISD::ATOMIC_LOAD_MAX:
1720 case ISD::ATOMIC_LOAD_UMIN:
1721 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1722 if (DCI.isBeforeLegalize())
1725 MemSDNode *MemNode = cast<MemSDNode>(N);
1726 SDValue Ptr = MemNode->getBasePtr();
1728 // TODO: We could also do this for multiplies.
1729 unsigned AS = MemNode->getAddressSpace();
1730 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1731 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1733 SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1735 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1736 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1742 return performAndCombine(N, DCI);
1744 return performOrCombine(N, DCI);
1745 case AMDGPUISD::FP_CLASS:
1746 return performClassCombine(N, DCI);
1748 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1751 /// \brief Analyze the possible immediate value Op
1753 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1754 /// and the immediate value if it's a literal immediate
1755 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1757 const SIInstrInfo *TII =
1758 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1760 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1761 if (TII->isInlineConstant(Node->getAPIntValue()))
1764 uint64_t Val = Node->getZExtValue();
1765 return isUInt<32>(Val) ? Val : -1;
1768 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1769 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1772 if (Node->getValueType(0) == MVT::f32)
1773 return FloatToBits(Node->getValueAPF().convertToFloat());
1781 /// \brief Helper function for adjustWritemask
1782 static unsigned SubIdx2Lane(unsigned Idx) {
1785 case AMDGPU::sub0: return 0;
1786 case AMDGPU::sub1: return 1;
1787 case AMDGPU::sub2: return 2;
1788 case AMDGPU::sub3: return 3;
1792 /// \brief Adjust the writemask of MIMG instructions
1793 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1794 SelectionDAG &DAG) const {
1795 SDNode *Users[4] = { };
1797 unsigned OldDmask = Node->getConstantOperandVal(0);
1798 unsigned NewDmask = 0;
1800 // Try to figure out the used register components
1801 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1804 // Abort if we can't understand the usage
1805 if (!I->isMachineOpcode() ||
1806 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1809 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1810 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1811 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1813 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1815 // Set which texture component corresponds to the lane.
1817 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1819 Comp = countTrailingZeros(Dmask);
1820 Dmask &= ~(1 << Comp);
1823 // Abort if we have more than one user per component
1828 NewDmask |= 1 << Comp;
1831 // Abort if there's no change
1832 if (NewDmask == OldDmask)
1835 // Adjust the writemask in the node
1836 std::vector<SDValue> Ops;
1837 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1838 Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
1839 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1841 // If we only got one lane, replace it with a copy
1842 // (if NewDmask has only one bit set...)
1843 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1844 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, MVT::i32);
1845 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1846 SDLoc(), Users[Lane]->getValueType(0),
1847 SDValue(Node, 0), RC);
1848 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1852 // Update the users of the node with the new indices
1853 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1855 SDNode *User = Users[i];
1859 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1860 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1864 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1865 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1866 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1871 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1872 /// with frame index operands.
1873 /// LLVM assumes that inputs are to these instructions are registers.
1874 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1875 SelectionDAG &DAG) const {
1877 SmallVector<SDValue, 8> Ops;
1878 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1879 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1880 Ops.push_back(Node->getOperand(i));
1885 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1886 Node->getOperand(i).getValueType(),
1887 Node->getOperand(i)), 0));
1890 DAG.UpdateNodeOperands(Node, Ops);
1893 /// \brief Fold the instructions after selecting them.
1894 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1895 SelectionDAG &DAG) const {
1896 const SIInstrInfo *TII =
1897 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1899 if (TII->isMIMG(Node->getMachineOpcode()))
1900 adjustWritemask(Node, DAG);
1902 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1903 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1904 legalizeTargetIndependentNode(Node, DAG);
1910 /// \brief Assign the register class depending on the number of
1911 /// bits set in the writemask
1912 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1913 SDNode *Node) const {
1914 const SIInstrInfo *TII =
1915 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1917 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1918 TII->legalizeOperands(MI);
1920 if (TII->isMIMG(MI->getOpcode())) {
1921 unsigned VReg = MI->getOperand(0).getReg();
1922 unsigned Writemask = MI->getOperand(1).getImm();
1923 unsigned BitsSet = 0;
1924 for (unsigned i = 0; i < 4; ++i)
1925 BitsSet += Writemask & (1 << i) ? 1 : 0;
1927 const TargetRegisterClass *RC;
1930 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
1931 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1932 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1935 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1936 MI->setDesc(TII->get(NewOpcode));
1937 MRI.setRegClass(VReg, RC);
1941 // Replace unused atomics with the no return version.
1942 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1943 if (NoRetAtomicOp != -1) {
1944 if (!Node->hasAnyUseOfValue(0)) {
1945 MI->setDesc(TII->get(NoRetAtomicOp));
1946 MI->RemoveOperand(0);
1953 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1954 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1955 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1958 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
1960 SDValue Ptr) const {
1961 const SIInstrInfo *TII =
1962 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1964 // XXX - Workaround for moveToVALU not handling different register class
1965 // inserts for REG_SEQUENCE.
1967 // Build the half of the subregister with the constants.
1968 const SDValue Ops0[] = {
1969 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
1970 buildSMovImm32(DAG, DL, 0),
1971 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
1972 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
1973 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
1976 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1977 MVT::v2i32, Ops0), 0);
1979 // Combine the constants and the pointer.
1980 const SDValue Ops1[] = {
1981 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1983 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
1985 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
1988 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
1990 const SDValue Ops[] = {
1991 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
1993 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
1994 buildSMovImm32(DAG, DL, 0),
1995 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
1996 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
1997 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2000 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2005 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2006 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2007 /// of the resource descriptor) to create an offset, which is added to the
2008 /// resource ponter.
2009 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2012 uint32_t RsrcDword1,
2013 uint64_t RsrcDword2And3) const {
2014 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2015 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2017 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2018 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2021 SDValue DataLo = buildSMovImm32(DAG, DL,
2022 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2023 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2025 const SDValue Ops[] = {
2026 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2028 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2030 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2032 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2034 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2037 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2040 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2042 SDValue Ptr) const {
2043 const SIInstrInfo *TII =
2044 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2045 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2048 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2051 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2052 const TargetRegisterClass *RC,
2053 unsigned Reg, EVT VT) const {
2054 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2056 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2057 cast<RegisterSDNode>(VReg)->getReg(), VT);