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 AMDGPUTargetLowering(TM) {
40 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
41 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
43 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
44 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
46 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
47 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
49 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
50 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
51 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
53 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
54 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
56 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
69 setOperationAction(ISD::ADD, MVT::i32, Legal);
70 setOperationAction(ISD::ADDC, MVT::i32, Legal);
71 setOperationAction(ISD::ADDE, MVT::i32, Legal);
72 setOperationAction(ISD::SUBC, MVT::i32, Legal);
73 setOperationAction(ISD::SUBE, MVT::i32, Legal);
75 setOperationAction(ISD::FSIN, MVT::f32, Custom);
76 setOperationAction(ISD::FCOS, MVT::f32, Custom);
78 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
79 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
80 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
81 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
83 // We need to custom lower vector stores from local memory
84 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
88 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
91 setOperationAction(ISD::STORE, MVT::i1, Custom);
92 setOperationAction(ISD::STORE, MVT::i32, Custom);
93 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
94 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
96 setOperationAction(ISD::SELECT, MVT::f32, Promote);
97 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
98 setOperationAction(ISD::SELECT, MVT::i64, Custom);
99 setOperationAction(ISD::SELECT, MVT::f64, Promote);
100 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
102 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
104 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
105 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
107 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
108 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
110 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
129 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
130 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
132 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
133 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
136 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
137 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
138 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
139 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
140 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
142 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
143 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
144 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
145 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
147 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
148 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
149 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
150 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
151 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
153 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
154 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
155 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
156 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
157 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
158 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
160 setOperationAction(ISD::LOAD, MVT::i1, Custom);
162 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
163 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
164 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
166 // These should use UDIVREM, so set them to expand
167 setOperationAction(ISD::UDIV, MVT::i64, Expand);
168 setOperationAction(ISD::UREM, MVT::i64, Expand);
170 // We only support LOAD/STORE and vector manipulation ops for vectors
171 // with > 4 elements.
173 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
176 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
177 setOperationAction(ISD::SELECT, MVT::i1, Promote);
179 for (MVT VT : VecTypes) {
180 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
184 case ISD::BUILD_VECTOR:
186 case ISD::EXTRACT_VECTOR_ELT:
187 case ISD::INSERT_VECTOR_ELT:
188 case ISD::INSERT_SUBVECTOR:
189 case ISD::EXTRACT_SUBVECTOR:
191 case ISD::CONCAT_VECTORS:
192 setOperationAction(Op, VT, Custom);
195 setOperationAction(Op, VT, Expand);
201 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
202 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
203 setOperationAction(ISD::FTRUNC, VT, Expand);
204 setOperationAction(ISD::FCEIL, VT, Expand);
205 setOperationAction(ISD::FFLOOR, VT, Expand);
208 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
209 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
210 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
211 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
212 setOperationAction(ISD::FRINT, MVT::f64, Legal);
215 setOperationAction(ISD::FDIV, MVT::f32, Custom);
217 setTargetDAGCombine(ISD::FADD);
218 setTargetDAGCombine(ISD::FSUB);
219 setTargetDAGCombine(ISD::FMINNUM);
220 setTargetDAGCombine(ISD::FMAXNUM);
221 setTargetDAGCombine(ISD::SELECT_CC);
222 setTargetDAGCombine(ISD::SETCC);
224 setTargetDAGCombine(ISD::UINT_TO_FP);
226 // All memory operations. Some folding on the pointer operand is done to help
227 // matching the constant offsets in the addressing modes.
228 setTargetDAGCombine(ISD::LOAD);
229 setTargetDAGCombine(ISD::STORE);
230 setTargetDAGCombine(ISD::ATOMIC_LOAD);
231 setTargetDAGCombine(ISD::ATOMIC_STORE);
232 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
233 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
234 setTargetDAGCombine(ISD::ATOMIC_SWAP);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
246 setSchedulingPreference(Sched::RegPressure);
249 //===----------------------------------------------------------------------===//
250 // TargetLowering queries
251 //===----------------------------------------------------------------------===//
253 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
255 // SI has some legal vector types, but no legal vector operations. Say no
256 // shuffles are legal in order to prefer scalarizing some vector operations.
260 // FIXME: This really needs an address space argument. The immediate offset
261 // size is different for different sets of memory instruction sets.
263 // The single offset DS instructions have a 16-bit unsigned byte offset.
265 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
266 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
267 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
269 // SMRD instructions have an 8-bit, dword offset.
271 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
273 // No global is ever allowed as a base.
277 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
279 if (!isUInt<16>(AM.BaseOffs))
284 case 0: // "r+i" or just "i", depending on HasBaseReg.
287 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
289 // Otherwise we have r+r or r+i.
292 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
296 default: // Don't allow n * r
303 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
306 bool *IsFast) const {
310 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
311 // which isn't a simple VT.
312 if (!VT.isSimple() || VT == MVT::Other)
315 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
316 // see what for specifically. The wording everywhere else seems to be the
319 // XXX - The only mention I see of this in the ISA manual is for LDS direct
320 // reads the "byte address and must be dword aligned". Is it also true for the
321 // normal loads and stores?
322 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
323 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
324 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
325 // with adjacent offsets.
326 return Align % 4 == 0;
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.
334 return VT.bitsGT(MVT::i32);
337 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
338 unsigned SrcAlign, bool IsMemset,
341 MachineFunction &MF) const {
342 // FIXME: Should account for address space here.
344 // The default fallback uses the private pointer size as a guess for a type to
345 // use. Make sure we switch these to 64-bit accesses.
347 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
350 if (Size >= 8 && DstAlign >= 4)
357 TargetLoweringBase::LegalizeTypeAction
358 SITargetLowering::getPreferredVectorAction(EVT VT) const {
359 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
360 return TypeSplitVector;
362 return TargetLoweringBase::getPreferredVectorAction(VT);
365 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
367 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
368 getTargetMachine().getSubtargetImpl()->getInstrInfo());
369 return TII->isInlineConstant(Imm);
372 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
373 SDLoc SL, SDValue Chain,
374 unsigned Offset, bool Signed) const {
375 const DataLayout *DL = getDataLayout();
376 MachineFunction &MF = DAG.getMachineFunction();
377 const SIRegisterInfo *TRI =
378 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
379 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
381 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
383 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
384 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
385 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
386 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
387 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
388 DAG.getConstant(Offset, MVT::i64));
389 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
390 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
392 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
393 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
395 true, // isNonTemporal
397 DL->getABITypeAlignment(Ty)); // Alignment
400 SDValue SITargetLowering::LowerFormalArguments(
402 CallingConv::ID CallConv,
404 const SmallVectorImpl<ISD::InputArg> &Ins,
405 SDLoc DL, SelectionDAG &DAG,
406 SmallVectorImpl<SDValue> &InVals) const {
408 const TargetMachine &TM = getTargetMachine();
409 const SIRegisterInfo *TRI =
410 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
412 MachineFunction &MF = DAG.getMachineFunction();
413 FunctionType *FType = MF.getFunction()->getFunctionType();
414 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
416 assert(CallConv == CallingConv::C);
418 SmallVector<ISD::InputArg, 16> Splits;
419 BitVector Skipped(Ins.size());
421 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
422 const ISD::InputArg &Arg = Ins[i];
424 // First check if it's a PS input addr
425 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
426 !Arg.Flags.isByVal()) {
428 assert((PSInputNum <= 15) && "Too many PS inputs!");
431 // We can savely skip PS inputs
437 Info->PSInputAddr |= 1 << PSInputNum++;
440 // Second split vertices into their elements
441 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
442 ISD::InputArg NewArg = Arg;
443 NewArg.Flags.setSplit();
444 NewArg.VT = Arg.VT.getVectorElementType();
446 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
447 // three or five element vertex only needs three or five registers,
448 // NOT four or eigth.
449 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
450 unsigned NumElements = ParamType->getVectorNumElements();
452 for (unsigned j = 0; j != NumElements; ++j) {
453 Splits.push_back(NewArg);
454 NewArg.PartOffset += NewArg.VT.getStoreSize();
457 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
458 Splits.push_back(Arg);
462 SmallVector<CCValAssign, 16> ArgLocs;
463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
466 // At least one interpolation mode must be enabled or else the GPU will hang.
467 if (Info->getShaderType() == ShaderType::PIXEL &&
468 (Info->PSInputAddr & 0x7F) == 0) {
469 Info->PSInputAddr |= 1;
470 CCInfo.AllocateReg(AMDGPU::VGPR0);
471 CCInfo.AllocateReg(AMDGPU::VGPR1);
474 // The pointer to the list of arguments is stored in SGPR0, SGPR1
475 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
476 if (Info->getShaderType() == ShaderType::COMPUTE) {
477 if (Subtarget->isAmdHsaOS())
478 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
480 Info->NumUserSGPRs = 4;
482 unsigned InputPtrReg =
483 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
484 unsigned InputPtrRegLo =
485 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
486 unsigned InputPtrRegHi =
487 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
489 unsigned ScratchPtrReg =
490 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
491 unsigned ScratchPtrRegLo =
492 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
493 unsigned ScratchPtrRegHi =
494 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
496 CCInfo.AllocateReg(InputPtrRegLo);
497 CCInfo.AllocateReg(InputPtrRegHi);
498 CCInfo.AllocateReg(ScratchPtrRegLo);
499 CCInfo.AllocateReg(ScratchPtrRegHi);
500 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
501 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
504 if (Info->getShaderType() == ShaderType::COMPUTE) {
505 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
509 AnalyzeFormalArguments(CCInfo, Splits);
511 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
513 const ISD::InputArg &Arg = Ins[i];
515 InVals.push_back(DAG.getUNDEF(Arg.VT));
519 CCValAssign &VA = ArgLocs[ArgIdx++];
520 MVT VT = VA.getLocVT();
524 EVT MemVT = Splits[i].VT;
525 const unsigned Offset = 36 + VA.getLocMemOffset();
526 // The first 36 bytes of the input buffer contains information about
527 // thread group and global sizes.
528 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
529 Offset, Ins[i].Flags.isSExt());
531 const PointerType *ParamTy =
532 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
533 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
534 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
535 // On SI local pointers are just offsets into LDS, so they are always
536 // less than 16-bits. On CI and newer they could potentially be
537 // real pointers, so we can't guarantee their size.
538 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
539 DAG.getValueType(MVT::i16));
542 InVals.push_back(Arg);
543 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
546 assert(VA.isRegLoc() && "Parameter must be in a register!");
548 unsigned Reg = VA.getLocReg();
550 if (VT == MVT::i64) {
551 // For now assume it is a pointer
552 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
553 &AMDGPU::SReg_64RegClass);
554 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
555 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
559 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
561 Reg = MF.addLiveIn(Reg, RC);
562 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
564 if (Arg.VT.isVector()) {
566 // Build a vector from the registers
567 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
568 unsigned NumElements = ParamType->getVectorNumElements();
570 SmallVector<SDValue, 4> Regs;
572 for (unsigned j = 1; j != NumElements; ++j) {
573 Reg = ArgLocs[ArgIdx++].getLocReg();
574 Reg = MF.addLiveIn(Reg, RC);
575 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
578 // Fill up the missing vector elements
579 NumElements = Arg.VT.getVectorNumElements() - NumElements;
580 for (unsigned j = 0; j != NumElements; ++j)
581 Regs.push_back(DAG.getUNDEF(VT));
583 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
587 InVals.push_back(Val);
592 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
593 MachineInstr * MI, MachineBasicBlock * BB) const {
595 MachineBasicBlock::iterator I = *MI;
596 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
597 getTargetMachine().getSubtargetImpl()->getInstrInfo());
599 switch (MI->getOpcode()) {
601 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
602 case AMDGPU::BRANCH: return BB;
603 case AMDGPU::V_SUB_F64: {
604 unsigned DestReg = MI->getOperand(0).getReg();
605 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
606 .addImm(0) // SRC0 modifiers
607 .addReg(MI->getOperand(1).getReg())
608 .addImm(1) // SRC1 modifiers
609 .addReg(MI->getOperand(2).getReg())
612 MI->eraseFromParent();
615 case AMDGPU::SI_RegisterStorePseudo: {
616 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
617 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
618 MachineInstrBuilder MIB =
619 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
621 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
622 MIB.addOperand(MI->getOperand(i));
624 MI->eraseFromParent();
631 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
632 if (!VT.isVector()) {
635 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
638 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
642 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
643 VT = VT.getScalarType();
648 switch (VT.getSimpleVT().SimpleTy) {
650 return false; /* There is V_MAD_F32 for f32 */
660 //===----------------------------------------------------------------------===//
661 // Custom DAG Lowering Operations
662 //===----------------------------------------------------------------------===//
664 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
665 switch (Op.getOpcode()) {
666 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
667 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
668 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
670 SDValue Result = LowerLOAD(Op, DAG);
671 assert((!Result.getNode() ||
672 Result.getNode()->getNumValues() == 2) &&
673 "Load should return a value and a chain");
679 return LowerTrig(Op, DAG);
680 case ISD::SELECT: return LowerSELECT(Op, DAG);
681 case ISD::FDIV: return LowerFDIV(Op, DAG);
682 case ISD::STORE: return LowerSTORE(Op, DAG);
683 case ISD::GlobalAddress: {
684 MachineFunction &MF = DAG.getMachineFunction();
685 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
686 return LowerGlobalAddress(MFI, Op, DAG);
688 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
689 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
694 /// \brief Helper function for LowerBRCOND
695 static SDNode *findUser(SDValue Value, unsigned Opcode) {
697 SDNode *Parent = Value.getNode();
698 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
701 if (I.getUse().get() != Value)
704 if (I->getOpcode() == Opcode)
710 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
712 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
713 unsigned FrameIndex = FINode->getIndex();
715 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
718 /// This transforms the control flow intrinsics to get the branch destination as
719 /// last parameter, also switches branch target with BR if the need arise
720 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
721 SelectionDAG &DAG) const {
725 SDNode *Intr = BRCOND.getOperand(1).getNode();
726 SDValue Target = BRCOND.getOperand(2);
727 SDNode *BR = nullptr;
729 if (Intr->getOpcode() == ISD::SETCC) {
730 // As long as we negate the condition everything is fine
731 SDNode *SetCC = Intr;
732 assert(SetCC->getConstantOperandVal(1) == 1);
733 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
735 Intr = SetCC->getOperand(0).getNode();
738 // Get the target from BR if we don't negate the condition
739 BR = findUser(BRCOND, ISD::BR);
740 Target = BR->getOperand(1);
743 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
745 // Build the result and
746 SmallVector<EVT, 4> Res;
747 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
748 Res.push_back(Intr->getValueType(i));
750 // operands of the new intrinsic call
751 SmallVector<SDValue, 4> Ops;
752 Ops.push_back(BRCOND.getOperand(0));
753 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
754 Ops.push_back(Intr->getOperand(i));
755 Ops.push_back(Target);
757 // build the new intrinsic call
758 SDNode *Result = DAG.getNode(
759 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
760 DAG.getVTList(Res), Ops).getNode();
763 // Give the branch instruction our target
768 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
769 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
770 BR = NewBR.getNode();
773 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
775 // Copy the intrinsic results to registers
776 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
777 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
781 Chain = DAG.getCopyToReg(
783 CopyToReg->getOperand(1),
784 SDValue(Result, i - 1),
787 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
790 // Remove the old intrinsic from the chain
791 DAG.ReplaceAllUsesOfValueWith(
792 SDValue(Intr, Intr->getNumValues() - 1),
793 Intr->getOperand(0));
798 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
800 SelectionDAG &DAG) const {
801 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
803 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
804 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
807 const GlobalValue *GV = GSD->getGlobal();
808 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
810 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
811 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
813 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
814 DAG.getConstant(0, MVT::i32));
815 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
816 DAG.getConstant(1, MVT::i32));
818 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
820 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
821 PtrHi, DAG.getConstant(0, MVT::i32),
822 SDValue(Lo.getNode(), 1));
823 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
826 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
827 SelectionDAG &DAG) const {
828 MachineFunction &MF = DAG.getMachineFunction();
829 const SIRegisterInfo *TRI =
830 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
832 EVT VT = Op.getValueType();
834 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
836 switch (IntrinsicID) {
837 case Intrinsic::r600_read_ngroups_x:
838 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
839 SI::KernelInputOffsets::NGROUPS_X, false);
840 case Intrinsic::r600_read_ngroups_y:
841 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
842 SI::KernelInputOffsets::NGROUPS_Y, false);
843 case Intrinsic::r600_read_ngroups_z:
844 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
845 SI::KernelInputOffsets::NGROUPS_Z, false);
846 case Intrinsic::r600_read_global_size_x:
847 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
848 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
849 case Intrinsic::r600_read_global_size_y:
850 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
851 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
852 case Intrinsic::r600_read_global_size_z:
853 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
854 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
855 case Intrinsic::r600_read_local_size_x:
856 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
857 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
858 case Intrinsic::r600_read_local_size_y:
859 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
860 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
861 case Intrinsic::r600_read_local_size_z:
862 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
863 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
865 case Intrinsic::AMDGPU_read_workdim:
866 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
867 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
870 case Intrinsic::r600_read_tgid_x:
871 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
872 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
873 case Intrinsic::r600_read_tgid_y:
874 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
875 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
876 case Intrinsic::r600_read_tgid_z:
877 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
878 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
879 case Intrinsic::r600_read_tidig_x:
880 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
881 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
882 case Intrinsic::r600_read_tidig_y:
883 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
884 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
885 case Intrinsic::r600_read_tidig_z:
886 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
887 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
888 case AMDGPUIntrinsic::SI_load_const: {
894 MachineMemOperand *MMO = MF.getMachineMemOperand(
895 MachinePointerInfo(),
896 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
897 VT.getStoreSize(), 4);
898 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
899 Op->getVTList(), Ops, VT, MMO);
901 case AMDGPUIntrinsic::SI_sample:
902 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
903 case AMDGPUIntrinsic::SI_sampleb:
904 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
905 case AMDGPUIntrinsic::SI_sampled:
906 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
907 case AMDGPUIntrinsic::SI_samplel:
908 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
909 case AMDGPUIntrinsic::SI_vs_load_input:
910 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
915 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
919 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
920 SelectionDAG &DAG) const {
921 MachineFunction &MF = DAG.getMachineFunction();
922 SDValue Chain = Op.getOperand(0);
923 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
925 switch (IntrinsicID) {
926 case AMDGPUIntrinsic::SI_tbuffer_store: {
945 EVT VT = Op.getOperand(3).getValueType();
947 MachineMemOperand *MMO = MF.getMachineMemOperand(
948 MachinePointerInfo(),
949 MachineMemOperand::MOStore,
950 VT.getStoreSize(), 4);
951 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
952 Op->getVTList(), Ops, VT, MMO);
959 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
961 LoadSDNode *Load = cast<LoadSDNode>(Op);
963 if (Op.getValueType().isVector()) {
964 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
965 "Custom lowering for non-i32 vectors hasn't been implemented.");
966 unsigned NumElements = Op.getValueType().getVectorNumElements();
967 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
968 switch (Load->getAddressSpace()) {
970 case AMDGPUAS::GLOBAL_ADDRESS:
971 case AMDGPUAS::PRIVATE_ADDRESS:
972 // v4 loads are supported for private and global memory.
973 if (NumElements <= 4)
976 case AMDGPUAS::LOCAL_ADDRESS:
977 return ScalarizeVectorLoad(Op, DAG);
981 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
984 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
986 SelectionDAG &DAG) const {
987 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
993 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
994 if (Op.getValueType() != MVT::i64)
998 SDValue Cond = Op.getOperand(0);
1000 SDValue Zero = DAG.getConstant(0, MVT::i32);
1001 SDValue One = DAG.getConstant(1, MVT::i32);
1003 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1004 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1006 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1007 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1009 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1011 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1012 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1014 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1016 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1017 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1020 // Catch division cases where we can use shortcuts with rcp and rsq
1022 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1024 SDValue LHS = Op.getOperand(0);
1025 SDValue RHS = Op.getOperand(1);
1026 EVT VT = Op.getValueType();
1027 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1029 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1030 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1031 CLHS->isExactlyValue(1.0)) {
1032 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1033 // the CI documentation has a worst case error of 1 ulp.
1034 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1035 // use it as long as we aren't trying to use denormals.
1037 // 1.0 / sqrt(x) -> rsq(x)
1039 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1040 // error seems really high at 2^29 ULP.
1041 if (RHS.getOpcode() == ISD::FSQRT)
1042 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1044 // 1.0 / x -> rcp(x)
1045 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1050 // Turn into multiply by the reciprocal.
1051 // x / y -> x * (1.0 / y)
1052 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1053 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1059 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1060 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1061 if (FastLowered.getNode())
1064 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1065 // selection error for now rather than do something incorrect.
1066 if (Subtarget->hasFP32Denormals())
1070 SDValue LHS = Op.getOperand(0);
1071 SDValue RHS = Op.getOperand(1);
1073 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1075 const APFloat K0Val(BitsToFloat(0x6f800000));
1076 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1078 const APFloat K1Val(BitsToFloat(0x2f800000));
1079 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1081 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1083 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1085 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1087 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1089 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1091 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1093 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1095 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1098 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1102 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1103 EVT VT = Op.getValueType();
1106 return LowerFDIV32(Op, DAG);
1109 return LowerFDIV64(Op, DAG);
1111 llvm_unreachable("Unexpected type for fdiv");
1114 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1116 StoreSDNode *Store = cast<StoreSDNode>(Op);
1117 EVT VT = Store->getMemoryVT();
1119 // These stores are legal.
1120 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1121 VT.isVector() && VT.getVectorNumElements() == 2 &&
1122 VT.getVectorElementType() == MVT::i32)
1125 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1126 if (VT.isVector() && VT.getVectorNumElements() > 4)
1127 return ScalarizeVectorStore(Op, DAG);
1131 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1135 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1136 return ScalarizeVectorStore(Op, DAG);
1139 return DAG.getTruncStore(Store->getChain(), DL,
1140 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1141 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1146 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1147 EVT VT = Op.getValueType();
1148 SDValue Arg = Op.getOperand(0);
1149 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1150 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1151 DAG.getConstantFP(0.5 / M_PI, VT)));
1153 switch (Op.getOpcode()) {
1155 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1157 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1159 llvm_unreachable("Wrong trig opcode");
1163 //===----------------------------------------------------------------------===//
1164 // Custom DAG optimizations
1165 //===----------------------------------------------------------------------===//
1167 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1168 DAGCombinerInfo &DCI) {
1169 EVT VT = N->getValueType(0);
1170 EVT ScalarVT = VT.getScalarType();
1171 if (ScalarVT != MVT::f32)
1174 SelectionDAG &DAG = DCI.DAG;
1177 SDValue Src = N->getOperand(0);
1178 EVT SrcVT = Src.getValueType();
1180 // TODO: We could try to match extracting the higher bytes, which would be
1181 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1182 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1183 // about in practice.
1184 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1185 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1186 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1187 DCI.AddToWorklist(Cvt.getNode());
1192 // We are primarily trying to catch operations on illegal vector types
1193 // before they are expanded.
1194 // For scalars, we can use the more flexible method of checking masked bits
1195 // after legalization.
1196 if (!DCI.isBeforeLegalize() ||
1197 !SrcVT.isVector() ||
1198 SrcVT.getVectorElementType() != MVT::i8) {
1202 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1204 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1206 unsigned NElts = SrcVT.getVectorNumElements();
1207 if (!SrcVT.isSimple() && NElts != 3)
1210 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1211 // prevent a mess from expanding to v4i32 and repacking.
1212 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1213 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1214 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1215 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1217 LoadSDNode *Load = cast<LoadSDNode>(Src);
1218 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1222 Load->getMemOperand());
1224 // Make sure successors of the original load stay after it by updating
1225 // them to use the new Chain.
1226 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1228 SmallVector<SDValue, 4> Elts;
1229 if (RegVT.isVector())
1230 DAG.ExtractVectorElements(NewLoad, Elts);
1232 Elts.push_back(NewLoad);
1234 SmallVector<SDValue, 4> Ops;
1236 unsigned EltIdx = 0;
1237 for (SDValue Elt : Elts) {
1238 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1239 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1240 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1241 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1242 DCI.AddToWorklist(Cvt.getNode());
1249 assert(Ops.size() == NElts);
1251 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1257 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1259 // This is a variant of
1260 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1262 // The normal DAG combiner will do this, but only if the add has one use since
1263 // that would increase the number of instructions.
1265 // This prevents us from seeing a constant offset that can be folded into a
1266 // memory instruction's addressing mode. If we know the resulting add offset of
1267 // a pointer can be folded into an addressing offset, we can replace the pointer
1268 // operand with the add of new constant offset. This eliminates one of the uses,
1269 // and may allow the remaining use to also be simplified.
1271 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1273 DAGCombinerInfo &DCI) const {
1274 SDValue N0 = N->getOperand(0);
1275 SDValue N1 = N->getOperand(1);
1277 if (N0.getOpcode() != ISD::ADD)
1280 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1284 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1288 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1289 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1291 // If the resulting offset is too large, we can't fold it into the addressing
1293 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1294 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1297 SelectionDAG &DAG = DCI.DAG;
1299 EVT VT = N->getValueType(0);
1301 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1302 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1304 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1307 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1310 return AMDGPUISD::FMAX3;
1311 case AMDGPUISD::SMAX:
1312 return AMDGPUISD::SMAX3;
1313 case AMDGPUISD::UMAX:
1314 return AMDGPUISD::UMAX3;
1316 return AMDGPUISD::FMIN3;
1317 case AMDGPUISD::SMIN:
1318 return AMDGPUISD::SMIN3;
1319 case AMDGPUISD::UMIN:
1320 return AMDGPUISD::UMIN3;
1322 llvm_unreachable("Not a min/max opcode");
1326 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1327 DAGCombinerInfo &DCI) const {
1328 SelectionDAG &DAG = DCI.DAG;
1330 unsigned Opc = N->getOpcode();
1331 SDValue Op0 = N->getOperand(0);
1332 SDValue Op1 = N->getOperand(1);
1334 // Only do this if the inner op has one use since this will just increases
1335 // register pressure for no benefit.
1337 // max(max(a, b), c)
1338 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1340 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1348 // max(a, max(b, c))
1349 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1351 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1362 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1363 DAGCombinerInfo &DCI) const {
1364 SelectionDAG &DAG = DCI.DAG;
1366 EVT VT = N->getValueType(0);
1368 switch (N->getOpcode()) {
1369 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1371 SDValue Arg0 = N->getOperand(0);
1372 SDValue Arg1 = N->getOperand(1);
1373 SDValue CC = N->getOperand(2);
1374 ConstantSDNode * C = nullptr;
1375 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1377 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1379 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1380 && Arg0.getOperand(0).getValueType() == MVT::i1
1381 && (C = dyn_cast<ConstantSDNode>(Arg1))
1383 && CCOp == ISD::SETNE) {
1384 return SimplifySetCC(VT, Arg0.getOperand(0),
1385 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1389 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1391 case AMDGPUISD::SMAX:
1392 case AMDGPUISD::SMIN:
1393 case AMDGPUISD::UMAX:
1394 case AMDGPUISD::UMIN: {
1395 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1396 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1397 return performMin3Max3Combine(N, DCI);
1401 case AMDGPUISD::CVT_F32_UBYTE0:
1402 case AMDGPUISD::CVT_F32_UBYTE1:
1403 case AMDGPUISD::CVT_F32_UBYTE2:
1404 case AMDGPUISD::CVT_F32_UBYTE3: {
1405 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1407 SDValue Src = N->getOperand(0);
1408 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1410 APInt KnownZero, KnownOne;
1411 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1412 !DCI.isBeforeLegalizeOps());
1413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1414 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1415 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1416 DCI.CommitTargetLoweringOpt(TLO);
1422 case ISD::UINT_TO_FP: {
1423 return performUCharToFloatCombine(N, DCI);
1426 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1429 EVT VT = N->getValueType(0);
1433 SDValue LHS = N->getOperand(0);
1434 SDValue RHS = N->getOperand(1);
1436 // These should really be instruction patterns, but writing patterns with
1437 // source modiifiers is a pain.
1439 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1440 if (LHS.getOpcode() == ISD::FADD) {
1441 SDValue A = LHS.getOperand(0);
1442 if (A == LHS.getOperand(1)) {
1443 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1444 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1448 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1449 if (RHS.getOpcode() == ISD::FADD) {
1450 SDValue A = RHS.getOperand(0);
1451 if (A == RHS.getOperand(1)) {
1452 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1453 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1460 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1463 EVT VT = N->getValueType(0);
1465 // Try to get the fneg to fold into the source modifier. This undoes generic
1466 // DAG combines and folds them into the mad.
1467 if (VT == MVT::f32) {
1468 SDValue LHS = N->getOperand(0);
1469 SDValue RHS = N->getOperand(1);
1471 if (LHS.getOpcode() == ISD::FMUL) {
1472 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1474 SDValue A = LHS.getOperand(0);
1475 SDValue B = LHS.getOperand(1);
1476 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1478 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1481 if (RHS.getOpcode() == ISD::FMUL) {
1482 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1484 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1485 SDValue B = RHS.getOperand(1);
1488 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1491 if (LHS.getOpcode() == ISD::FADD) {
1492 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1494 SDValue A = LHS.getOperand(0);
1495 if (A == LHS.getOperand(1)) {
1496 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1497 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1499 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1503 if (RHS.getOpcode() == ISD::FADD) {
1504 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1506 SDValue A = RHS.getOperand(0);
1507 if (A == RHS.getOperand(1)) {
1508 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1509 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1519 case ISD::ATOMIC_LOAD:
1520 case ISD::ATOMIC_STORE:
1521 case ISD::ATOMIC_CMP_SWAP:
1522 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1523 case ISD::ATOMIC_SWAP:
1524 case ISD::ATOMIC_LOAD_ADD:
1525 case ISD::ATOMIC_LOAD_SUB:
1526 case ISD::ATOMIC_LOAD_AND:
1527 case ISD::ATOMIC_LOAD_OR:
1528 case ISD::ATOMIC_LOAD_XOR:
1529 case ISD::ATOMIC_LOAD_NAND:
1530 case ISD::ATOMIC_LOAD_MIN:
1531 case ISD::ATOMIC_LOAD_MAX:
1532 case ISD::ATOMIC_LOAD_UMIN:
1533 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1534 if (DCI.isBeforeLegalize())
1537 MemSDNode *MemNode = cast<MemSDNode>(N);
1538 SDValue Ptr = MemNode->getBasePtr();
1540 // TODO: We could also do this for multiplies.
1541 unsigned AS = MemNode->getAddressSpace();
1542 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1543 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1545 SmallVector<SDValue, 8> NewOps;
1546 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1547 NewOps.push_back(MemNode->getOperand(I));
1549 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1550 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1556 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1559 /// \brief Test if RegClass is one of the VSrc classes
1560 static bool isVSrc(unsigned RegClass) {
1562 default: return false;
1563 case AMDGPU::VSrc_32RegClassID:
1564 case AMDGPU::VCSrc_32RegClassID:
1565 case AMDGPU::VSrc_64RegClassID:
1566 case AMDGPU::VCSrc_64RegClassID:
1571 /// \brief Test if RegClass is one of the SSrc classes
1572 static bool isSSrc(unsigned RegClass) {
1573 return AMDGPU::SSrc_32RegClassID == RegClass ||
1574 AMDGPU::SSrc_64RegClassID == RegClass;
1577 /// \brief Analyze the possible immediate value Op
1579 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1580 /// and the immediate value if it's a literal immediate
1581 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1588 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1589 if (Node->getZExtValue() >> 32) {
1592 Imm.I = Node->getSExtValue();
1593 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1594 if (N->getValueType(0) != MVT::f32)
1596 Imm.F = Node->getValueAPF().convertToFloat();
1598 return -1; // It isn't an immediate
1600 if ((Imm.I >= -16 && Imm.I <= 64) ||
1601 Imm.F == 0.5f || Imm.F == -0.5f ||
1602 Imm.F == 1.0f || Imm.F == -1.0f ||
1603 Imm.F == 2.0f || Imm.F == -2.0f ||
1604 Imm.F == 4.0f || Imm.F == -4.0f)
1605 return 0; // It's an inline immediate
1607 return Imm.I; // It's a literal immediate
1610 /// \brief Try to fold an immediate directly into an instruction
1611 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1612 bool &ScalarSlotUsed) const {
1614 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1615 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1616 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1617 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1620 const SDValue &Op = Mov->getOperand(0);
1621 int32_t Value = analyzeImmediate(Op.getNode());
1623 // Not an immediate at all
1626 } else if (Value == 0) {
1627 // Inline immediates can always be fold
1631 } else if (Value == Immediate) {
1632 // Already fold literal immediate
1636 } else if (!ScalarSlotUsed && !Immediate) {
1637 // Fold this literal immediate
1638 ScalarSlotUsed = true;
1648 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1649 SelectionDAG &DAG, const SDValue &Op) const {
1650 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1651 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1652 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1654 if (!Op->isMachineOpcode()) {
1655 switch(Op->getOpcode()) {
1656 case ISD::CopyFromReg: {
1657 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1658 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1659 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1660 return MRI.getRegClass(Reg);
1662 return TRI.getPhysRegClass(Reg);
1664 default: return nullptr;
1667 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1668 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1669 if (OpClassID != -1) {
1670 return TRI.getRegClass(OpClassID);
1672 switch(Op.getMachineOpcode()) {
1673 case AMDGPU::COPY_TO_REGCLASS:
1674 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1675 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1677 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1678 // class, then the register class for the value could be either a
1679 // VReg or and SReg. In order to get a more accurate
1680 if (isVSrc(OpClassID))
1681 return getRegClassForNode(DAG, Op.getOperand(0));
1683 return TRI.getRegClass(OpClassID);
1684 case AMDGPU::EXTRACT_SUBREG: {
1685 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1686 const TargetRegisterClass *SuperClass =
1687 getRegClassForNode(DAG, Op.getOperand(0));
1688 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1690 case AMDGPU::REG_SEQUENCE:
1691 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1692 return TRI.getRegClass(
1693 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1695 return getRegClassFor(Op.getSimpleValueType());
1699 /// \brief Does "Op" fit into register class "RegClass" ?
1700 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1701 unsigned RegClass) const {
1702 const TargetRegisterInfo *TRI =
1703 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1704 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1708 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1711 /// \returns true if \p Node's operands are different from the SDValue list
1713 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1714 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1715 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1722 /// TODO: This needs to be removed. It's current primary purpose is to fold
1723 /// immediates into operands when legal. The legalization parts are redundant
1724 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1725 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1726 SelectionDAG &DAG) const {
1727 // Original encoding (either e32 or e64)
1728 int Opcode = Node->getMachineOpcode();
1729 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1730 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1731 const MCInstrDesc *Desc = &TII->get(Opcode);
1733 unsigned NumDefs = Desc->getNumDefs();
1734 unsigned NumOps = Desc->getNumOperands();
1736 // Commuted opcode if available
1737 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1738 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1740 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1741 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1743 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1744 bool HaveVSrc = false, HaveSSrc = false;
1746 // First figure out what we already have in this instruction.
1747 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1748 i != e && Op < NumOps; ++i, ++Op) {
1750 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1751 if (isVSrc(RegClass))
1753 else if (isSSrc(RegClass))
1758 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1759 if (Imm != -1 && Imm != 0) {
1760 // Literal immediate
1765 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1766 if (!HaveVSrc && !HaveSSrc)
1769 // No scalar allowed when we have both VSrc and SSrc
1770 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1772 // If this instruction has an implicit use of VCC, then it can't use the
1774 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1775 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1776 ScalarSlotUsed = true;
1781 // Second go over the operands and try to fold them
1782 std::vector<SDValue> Ops;
1783 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1784 i != e && Op < NumOps; ++i, ++Op) {
1786 const SDValue &Operand = Node->getOperand(i);
1787 Ops.push_back(Operand);
1789 // Already folded immediate?
1790 if (isa<ConstantSDNode>(Operand.getNode()) ||
1791 isa<ConstantFPSDNode>(Operand.getNode()))
1794 // Is this a VSrc or SSrc operand?
1795 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1796 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1797 // Try to fold the immediates. If this ends up with multiple constant bus
1798 // uses, it will be legalized later.
1799 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1803 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1805 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1806 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1808 // Test if it makes sense to swap operands
1809 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1810 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1811 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1813 // Swap commutable operands
1814 std::swap(Ops[0], Ops[1]);
1823 // Add optional chain and glue
1824 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1825 Ops.push_back(Node->getOperand(i));
1827 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1828 // this case a brand new node is always be created, even if the operands
1829 // are the same as before. So, manually check if anything has been changed.
1830 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1834 // Create a complete new instruction
1835 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1838 /// \brief Helper function for adjustWritemask
1839 static unsigned SubIdx2Lane(unsigned Idx) {
1842 case AMDGPU::sub0: return 0;
1843 case AMDGPU::sub1: return 1;
1844 case AMDGPU::sub2: return 2;
1845 case AMDGPU::sub3: return 3;
1849 /// \brief Adjust the writemask of MIMG instructions
1850 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1851 SelectionDAG &DAG) const {
1852 SDNode *Users[4] = { };
1854 unsigned OldDmask = Node->getConstantOperandVal(0);
1855 unsigned NewDmask = 0;
1857 // Try to figure out the used register components
1858 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1861 // Abort if we can't understand the usage
1862 if (!I->isMachineOpcode() ||
1863 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1866 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1867 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1868 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1870 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1872 // Set which texture component corresponds to the lane.
1874 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1876 Comp = countTrailingZeros(Dmask);
1877 Dmask &= ~(1 << Comp);
1880 // Abort if we have more than one user per component
1885 NewDmask |= 1 << Comp;
1888 // Abort if there's no change
1889 if (NewDmask == OldDmask)
1892 // Adjust the writemask in the node
1893 std::vector<SDValue> Ops;
1894 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1895 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1896 Ops.push_back(Node->getOperand(i));
1897 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1899 // If we only got one lane, replace it with a copy
1900 // (if NewDmask has only one bit set...)
1901 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1902 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1903 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1904 SDLoc(), Users[Lane]->getValueType(0),
1905 SDValue(Node, 0), RC);
1906 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1910 // Update the users of the node with the new indices
1911 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1913 SDNode *User = Users[i];
1917 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1918 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1922 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1923 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1924 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1929 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1930 /// with frame index operands.
1931 /// LLVM assumes that inputs are to these instructions are registers.
1932 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1933 SelectionDAG &DAG) const {
1935 SmallVector<SDValue, 8> Ops;
1936 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1937 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1938 Ops.push_back(Node->getOperand(i));
1943 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1944 Node->getOperand(i).getValueType(),
1945 Node->getOperand(i)), 0));
1948 DAG.UpdateNodeOperands(Node, Ops);
1951 /// \brief Fold the instructions after selecting them.
1952 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1953 SelectionDAG &DAG) const {
1954 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1955 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1956 Node = AdjustRegClass(Node, DAG);
1958 if (TII->isMIMG(Node->getMachineOpcode()))
1959 adjustWritemask(Node, DAG);
1961 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1962 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1963 legalizeTargetIndependentNode(Node, DAG);
1967 return legalizeOperands(Node, DAG);
1970 /// \brief Assign the register class depending on the number of
1971 /// bits set in the writemask
1972 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1973 SDNode *Node) const {
1974 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1975 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1977 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1978 TII->legalizeOperands(MI);
1980 if (TII->isMIMG(MI->getOpcode())) {
1981 unsigned VReg = MI->getOperand(0).getReg();
1982 unsigned Writemask = MI->getOperand(1).getImm();
1983 unsigned BitsSet = 0;
1984 for (unsigned i = 0; i < 4; ++i)
1985 BitsSet += Writemask & (1 << i) ? 1 : 0;
1987 const TargetRegisterClass *RC;
1990 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1991 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1992 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1995 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1996 MI->setDesc(TII->get(NewOpcode));
1997 MRI.setRegClass(VReg, RC);
2001 // Replace unused atomics with the no return version.
2002 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2003 if (NoRetAtomicOp != -1) {
2004 if (!Node->hasAnyUseOfValue(0)) {
2005 MI->setDesc(TII->get(NoRetAtomicOp));
2006 MI->RemoveOperand(0);
2013 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2014 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
2015 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2018 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2020 SDValue Ptr) const {
2021 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
2022 getTargetMachine().getSubtargetImpl()->getInstrInfo());
2024 // XXX - Workaround for moveToVALU not handling different register class
2025 // inserts for REG_SEQUENCE.
2027 // Build the half of the subregister with the constants.
2028 const SDValue Ops0[] = {
2029 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2030 buildSMovImm32(DAG, DL, 0),
2031 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2032 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2033 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2036 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2037 MVT::v2i32, Ops0), 0);
2039 // Combine the constants and the pointer.
2040 const SDValue Ops1[] = {
2041 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2043 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2045 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2048 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2050 const SDValue Ops[] = {
2051 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2053 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2054 buildSMovImm32(DAG, DL, 0),
2055 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2056 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2057 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2060 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2065 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2066 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2067 /// of the resource descriptor) to create an offset, which is added to the
2068 /// resource ponter.
2069 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2072 uint32_t RsrcDword1,
2073 uint64_t RsrcDword2And3) const {
2074 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2075 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2077 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2078 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2081 SDValue DataLo = buildSMovImm32(DAG, DL,
2082 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2083 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2085 const SDValue Ops[] = {
2086 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2088 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2090 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2092 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2094 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2097 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2100 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2102 SDValue Ptr) const {
2103 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
2104 getTargetMachine().getSubtargetImpl()->getInstrInfo());
2105 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2108 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2111 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2112 SelectionDAG &DAG) const {
2115 unsigned NewOpcode = N->getMachineOpcode();
2117 switch (N->getMachineOpcode()) {
2119 case AMDGPU::S_LOAD_DWORD_IMM:
2120 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2122 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2123 if (NewOpcode == N->getMachineOpcode()) {
2124 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2127 case AMDGPU::S_LOAD_DWORDX4_IMM:
2128 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2129 if (NewOpcode == N->getMachineOpcode()) {
2130 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2132 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2135 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2137 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2138 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2139 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2141 SmallVector<SDValue, 8> Ops;
2142 Ops.push_back(SDValue(RSrc, 0));
2143 Ops.push_back(N->getOperand(0));
2145 // The immediate offset is in dwords on SI and in bytes on VI.
2146 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2147 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2149 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2151 // Copy remaining operands so we keep any chain and glue nodes that follow
2152 // the normal operands.
2153 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2154 Ops.push_back(N->getOperand(I));
2156 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2161 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2162 const TargetRegisterClass *RC,
2163 unsigned Reg, EVT VT) const {
2164 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2166 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2167 cast<RegisterSDNode>(VReg)->getReg(), VT);