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::i64, Custom);
97 setOperationAction(ISD::SELECT, MVT::f64, Promote);
98 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
100 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
101 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
105 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
106 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
108 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
110 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
114 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
125 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
130 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
131 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
135 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
136 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
137 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
138 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
140 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
141 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
142 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
143 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
145 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
146 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
147 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
148 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
149 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
151 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
152 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
153 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
154 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
156 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
158 setOperationAction(ISD::LOAD, MVT::i1, Custom);
160 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
161 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
162 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
164 // These should use UDIVREM, so set them to expand
165 setOperationAction(ISD::UDIV, MVT::i64, Expand);
166 setOperationAction(ISD::UREM, MVT::i64, Expand);
168 // We only support LOAD/STORE and vector manipulation ops for vectors
169 // with > 4 elements.
171 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
174 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
175 setOperationAction(ISD::SELECT, MVT::i1, Promote);
177 for (MVT VT : VecTypes) {
178 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
182 case ISD::BUILD_VECTOR:
184 case ISD::EXTRACT_VECTOR_ELT:
185 case ISD::INSERT_VECTOR_ELT:
186 case ISD::INSERT_SUBVECTOR:
187 case ISD::EXTRACT_SUBVECTOR:
189 case ISD::CONCAT_VECTORS:
190 setOperationAction(Op, VT, Custom);
193 setOperationAction(Op, VT, Expand);
199 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
200 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
201 setOperationAction(ISD::FTRUNC, VT, Expand);
202 setOperationAction(ISD::FCEIL, VT, Expand);
203 setOperationAction(ISD::FFLOOR, VT, Expand);
206 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
207 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
208 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
209 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
210 setOperationAction(ISD::FRINT, MVT::f64, Legal);
213 setOperationAction(ISD::FDIV, MVT::f32, Custom);
215 setTargetDAGCombine(ISD::FADD);
216 setTargetDAGCombine(ISD::FSUB);
217 setTargetDAGCombine(ISD::FMINNUM);
218 setTargetDAGCombine(ISD::FMAXNUM);
219 setTargetDAGCombine(ISD::SELECT_CC);
220 setTargetDAGCombine(ISD::SETCC);
222 setTargetDAGCombine(ISD::UINT_TO_FP);
224 // All memory operations. Some folding on the pointer operand is done to help
225 // matching the constant offsets in the addressing modes.
226 setTargetDAGCombine(ISD::LOAD);
227 setTargetDAGCombine(ISD::STORE);
228 setTargetDAGCombine(ISD::ATOMIC_LOAD);
229 setTargetDAGCombine(ISD::ATOMIC_STORE);
230 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
231 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
232 setTargetDAGCombine(ISD::ATOMIC_SWAP);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
234 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
235 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
236 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
244 setSchedulingPreference(Sched::RegPressure);
247 //===----------------------------------------------------------------------===//
248 // TargetLowering queries
249 //===----------------------------------------------------------------------===//
251 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
253 // SI has some legal vector types, but no legal vector operations. Say no
254 // shuffles are legal in order to prefer scalarizing some vector operations.
258 // FIXME: This really needs an address space argument. The immediate offset
259 // size is different for different sets of memory instruction sets.
261 // The single offset DS instructions have a 16-bit unsigned byte offset.
263 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
264 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
265 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
267 // SMRD instructions have an 8-bit, dword offset.
269 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
271 // No global is ever allowed as a base.
275 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
277 if (!isUInt<16>(AM.BaseOffs))
282 case 0: // "r+i" or just "i", depending on HasBaseReg.
285 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
287 // Otherwise we have r+r or r+i.
290 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
294 default: // Don't allow n * r
301 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
304 bool *IsFast) const {
308 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
309 // which isn't a simple VT.
310 if (!VT.isSimple() || VT == MVT::Other)
313 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
314 // see what for specifically. The wording everywhere else seems to be the
317 // XXX - The only mention I see of this in the ISA manual is for LDS direct
318 // reads the "byte address and must be dword aligned". Is it also true for the
319 // normal loads and stores?
320 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
321 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
322 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
323 // with adjacent offsets.
324 return Align % 4 == 0;
327 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
328 // byte-address are ignored, thus forcing Dword alignment.
329 // This applies to private, global, and constant memory.
332 return VT.bitsGT(MVT::i32);
335 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
336 unsigned SrcAlign, bool IsMemset,
339 MachineFunction &MF) const {
340 // FIXME: Should account for address space here.
342 // The default fallback uses the private pointer size as a guess for a type to
343 // use. Make sure we switch these to 64-bit accesses.
345 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
348 if (Size >= 8 && DstAlign >= 4)
355 TargetLoweringBase::LegalizeTypeAction
356 SITargetLowering::getPreferredVectorAction(EVT VT) const {
357 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
358 return TypeSplitVector;
360 return TargetLoweringBase::getPreferredVectorAction(VT);
363 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
365 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
366 getTargetMachine().getSubtargetImpl()->getInstrInfo());
367 return TII->isInlineConstant(Imm);
370 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
371 SDLoc SL, SDValue Chain,
372 unsigned Offset, bool Signed) const {
373 const DataLayout *DL = getDataLayout();
374 MachineFunction &MF = DAG.getMachineFunction();
375 const SIRegisterInfo *TRI =
376 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
377 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
379 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
381 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
382 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
383 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
384 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
385 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
386 DAG.getConstant(Offset, MVT::i64));
387 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
388 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
390 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
391 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
393 true, // isNonTemporal
395 DL->getABITypeAlignment(Ty)); // Alignment
398 SDValue SITargetLowering::LowerFormalArguments(
400 CallingConv::ID CallConv,
402 const SmallVectorImpl<ISD::InputArg> &Ins,
403 SDLoc DL, SelectionDAG &DAG,
404 SmallVectorImpl<SDValue> &InVals) const {
406 const TargetMachine &TM = getTargetMachine();
407 const SIRegisterInfo *TRI =
408 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
410 MachineFunction &MF = DAG.getMachineFunction();
411 FunctionType *FType = MF.getFunction()->getFunctionType();
412 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
414 assert(CallConv == CallingConv::C);
416 SmallVector<ISD::InputArg, 16> Splits;
417 BitVector Skipped(Ins.size());
419 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
420 const ISD::InputArg &Arg = Ins[i];
422 // First check if it's a PS input addr
423 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
424 !Arg.Flags.isByVal()) {
426 assert((PSInputNum <= 15) && "Too many PS inputs!");
429 // We can savely skip PS inputs
435 Info->PSInputAddr |= 1 << PSInputNum++;
438 // Second split vertices into their elements
439 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
440 ISD::InputArg NewArg = Arg;
441 NewArg.Flags.setSplit();
442 NewArg.VT = Arg.VT.getVectorElementType();
444 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
445 // three or five element vertex only needs three or five registers,
446 // NOT four or eigth.
447 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
448 unsigned NumElements = ParamType->getVectorNumElements();
450 for (unsigned j = 0; j != NumElements; ++j) {
451 Splits.push_back(NewArg);
452 NewArg.PartOffset += NewArg.VT.getStoreSize();
455 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
456 Splits.push_back(Arg);
460 SmallVector<CCValAssign, 16> ArgLocs;
461 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
464 // At least one interpolation mode must be enabled or else the GPU will hang.
465 if (Info->getShaderType() == ShaderType::PIXEL &&
466 (Info->PSInputAddr & 0x7F) == 0) {
467 Info->PSInputAddr |= 1;
468 CCInfo.AllocateReg(AMDGPU::VGPR0);
469 CCInfo.AllocateReg(AMDGPU::VGPR1);
472 // The pointer to the list of arguments is stored in SGPR0, SGPR1
473 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
474 if (Info->getShaderType() == ShaderType::COMPUTE) {
475 if (Subtarget->isAmdHsaOS())
476 Info->NumUserSGPRs = 2; // FIXME: Need to support scratch buffers.
478 Info->NumUserSGPRs = 4;
480 unsigned InputPtrReg =
481 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
482 unsigned InputPtrRegLo =
483 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
484 unsigned InputPtrRegHi =
485 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
487 unsigned ScratchPtrReg =
488 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
489 unsigned ScratchPtrRegLo =
490 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
491 unsigned ScratchPtrRegHi =
492 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
494 CCInfo.AllocateReg(InputPtrRegLo);
495 CCInfo.AllocateReg(InputPtrRegHi);
496 CCInfo.AllocateReg(ScratchPtrRegLo);
497 CCInfo.AllocateReg(ScratchPtrRegHi);
498 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
499 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
502 if (Info->getShaderType() == ShaderType::COMPUTE) {
503 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
507 AnalyzeFormalArguments(CCInfo, Splits);
509 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
511 const ISD::InputArg &Arg = Ins[i];
513 InVals.push_back(DAG.getUNDEF(Arg.VT));
517 CCValAssign &VA = ArgLocs[ArgIdx++];
518 MVT VT = VA.getLocVT();
522 EVT MemVT = Splits[i].VT;
523 const unsigned Offset = 36 + VA.getLocMemOffset();
524 // The first 36 bytes of the input buffer contains information about
525 // thread group and global sizes.
526 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
527 Offset, Ins[i].Flags.isSExt());
529 const PointerType *ParamTy =
530 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
531 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
532 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
533 // On SI local pointers are just offsets into LDS, so they are always
534 // less than 16-bits. On CI and newer they could potentially be
535 // real pointers, so we can't guarantee their size.
536 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
537 DAG.getValueType(MVT::i16));
540 InVals.push_back(Arg);
541 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
544 assert(VA.isRegLoc() && "Parameter must be in a register!");
546 unsigned Reg = VA.getLocReg();
548 if (VT == MVT::i64) {
549 // For now assume it is a pointer
550 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
551 &AMDGPU::SReg_64RegClass);
552 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
553 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
557 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
559 Reg = MF.addLiveIn(Reg, RC);
560 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
562 if (Arg.VT.isVector()) {
564 // Build a vector from the registers
565 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
566 unsigned NumElements = ParamType->getVectorNumElements();
568 SmallVector<SDValue, 4> Regs;
570 for (unsigned j = 1; j != NumElements; ++j) {
571 Reg = ArgLocs[ArgIdx++].getLocReg();
572 Reg = MF.addLiveIn(Reg, RC);
573 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
576 // Fill up the missing vector elements
577 NumElements = Arg.VT.getVectorNumElements() - NumElements;
578 for (unsigned j = 0; j != NumElements; ++j)
579 Regs.push_back(DAG.getUNDEF(VT));
581 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
585 InVals.push_back(Val);
590 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
591 MachineInstr * MI, MachineBasicBlock * BB) const {
593 MachineBasicBlock::iterator I = *MI;
594 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
595 getTargetMachine().getSubtargetImpl()->getInstrInfo());
597 switch (MI->getOpcode()) {
599 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
600 case AMDGPU::BRANCH: return BB;
601 case AMDGPU::V_SUB_F64: {
602 unsigned DestReg = MI->getOperand(0).getReg();
603 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
604 .addImm(0) // SRC0 modifiers
605 .addReg(MI->getOperand(1).getReg())
606 .addImm(1) // SRC1 modifiers
607 .addReg(MI->getOperand(2).getReg())
610 MI->eraseFromParent();
613 case AMDGPU::SI_RegisterStorePseudo: {
614 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
615 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
616 MachineInstrBuilder MIB =
617 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
619 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
620 MIB.addOperand(MI->getOperand(i));
622 MI->eraseFromParent();
629 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
630 if (!VT.isVector()) {
633 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
636 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
640 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
641 VT = VT.getScalarType();
646 switch (VT.getSimpleVT().SimpleTy) {
648 return false; /* There is V_MAD_F32 for f32 */
658 //===----------------------------------------------------------------------===//
659 // Custom DAG Lowering Operations
660 //===----------------------------------------------------------------------===//
662 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
663 switch (Op.getOpcode()) {
664 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
665 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
666 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
668 SDValue Result = LowerLOAD(Op, DAG);
669 assert((!Result.getNode() ||
670 Result.getNode()->getNumValues() == 2) &&
671 "Load should return a value and a chain");
677 return LowerTrig(Op, DAG);
678 case ISD::SELECT: return LowerSELECT(Op, DAG);
679 case ISD::FDIV: return LowerFDIV(Op, DAG);
680 case ISD::STORE: return LowerSTORE(Op, DAG);
681 case ISD::GlobalAddress: {
682 MachineFunction &MF = DAG.getMachineFunction();
683 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
684 return LowerGlobalAddress(MFI, Op, DAG);
686 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
687 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
692 /// \brief Helper function for LowerBRCOND
693 static SDNode *findUser(SDValue Value, unsigned Opcode) {
695 SDNode *Parent = Value.getNode();
696 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
699 if (I.getUse().get() != Value)
702 if (I->getOpcode() == Opcode)
708 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
710 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
711 unsigned FrameIndex = FINode->getIndex();
713 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
716 /// This transforms the control flow intrinsics to get the branch destination as
717 /// last parameter, also switches branch target with BR if the need arise
718 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
719 SelectionDAG &DAG) const {
723 SDNode *Intr = BRCOND.getOperand(1).getNode();
724 SDValue Target = BRCOND.getOperand(2);
725 SDNode *BR = nullptr;
727 if (Intr->getOpcode() == ISD::SETCC) {
728 // As long as we negate the condition everything is fine
729 SDNode *SetCC = Intr;
730 assert(SetCC->getConstantOperandVal(1) == 1);
731 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
733 Intr = SetCC->getOperand(0).getNode();
736 // Get the target from BR if we don't negate the condition
737 BR = findUser(BRCOND, ISD::BR);
738 Target = BR->getOperand(1);
741 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
743 // Build the result and
744 SmallVector<EVT, 4> Res;
745 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
746 Res.push_back(Intr->getValueType(i));
748 // operands of the new intrinsic call
749 SmallVector<SDValue, 4> Ops;
750 Ops.push_back(BRCOND.getOperand(0));
751 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
752 Ops.push_back(Intr->getOperand(i));
753 Ops.push_back(Target);
755 // build the new intrinsic call
756 SDNode *Result = DAG.getNode(
757 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
758 DAG.getVTList(Res), Ops).getNode();
761 // Give the branch instruction our target
766 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
767 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
768 BR = NewBR.getNode();
771 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
773 // Copy the intrinsic results to registers
774 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
775 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
779 Chain = DAG.getCopyToReg(
781 CopyToReg->getOperand(1),
782 SDValue(Result, i - 1),
785 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
788 // Remove the old intrinsic from the chain
789 DAG.ReplaceAllUsesOfValueWith(
790 SDValue(Intr, Intr->getNumValues() - 1),
791 Intr->getOperand(0));
796 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
798 SelectionDAG &DAG) const {
799 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
801 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
802 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
805 const GlobalValue *GV = GSD->getGlobal();
806 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
808 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
809 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
811 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
812 DAG.getConstant(0, MVT::i32));
813 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
814 DAG.getConstant(1, MVT::i32));
816 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
818 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
819 PtrHi, DAG.getConstant(0, MVT::i32),
820 SDValue(Lo.getNode(), 1));
821 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
824 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
825 SelectionDAG &DAG) const {
826 MachineFunction &MF = DAG.getMachineFunction();
827 const SIRegisterInfo *TRI =
828 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
830 EVT VT = Op.getValueType();
832 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
834 switch (IntrinsicID) {
835 case Intrinsic::r600_read_ngroups_x:
836 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
837 SI::KernelInputOffsets::NGROUPS_X, false);
838 case Intrinsic::r600_read_ngroups_y:
839 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
840 SI::KernelInputOffsets::NGROUPS_Y, false);
841 case Intrinsic::r600_read_ngroups_z:
842 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
843 SI::KernelInputOffsets::NGROUPS_Z, false);
844 case Intrinsic::r600_read_global_size_x:
845 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
846 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
847 case Intrinsic::r600_read_global_size_y:
848 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
849 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
850 case Intrinsic::r600_read_global_size_z:
851 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
852 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
853 case Intrinsic::r600_read_local_size_x:
854 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
855 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
856 case Intrinsic::r600_read_local_size_y:
857 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
858 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
859 case Intrinsic::r600_read_local_size_z:
860 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
861 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
863 case Intrinsic::AMDGPU_read_workdim:
864 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
865 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
868 case Intrinsic::r600_read_tgid_x:
869 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
870 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
871 case Intrinsic::r600_read_tgid_y:
872 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
873 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
874 case Intrinsic::r600_read_tgid_z:
875 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
876 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
877 case Intrinsic::r600_read_tidig_x:
878 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
879 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
880 case Intrinsic::r600_read_tidig_y:
881 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
882 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
883 case Intrinsic::r600_read_tidig_z:
884 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
885 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
886 case AMDGPUIntrinsic::SI_load_const: {
892 MachineMemOperand *MMO = MF.getMachineMemOperand(
893 MachinePointerInfo(),
894 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
895 VT.getStoreSize(), 4);
896 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
897 Op->getVTList(), Ops, VT, MMO);
899 case AMDGPUIntrinsic::SI_sample:
900 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
901 case AMDGPUIntrinsic::SI_sampleb:
902 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
903 case AMDGPUIntrinsic::SI_sampled:
904 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
905 case AMDGPUIntrinsic::SI_samplel:
906 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
907 case AMDGPUIntrinsic::SI_vs_load_input:
908 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
913 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
917 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
918 SelectionDAG &DAG) const {
919 MachineFunction &MF = DAG.getMachineFunction();
920 SDValue Chain = Op.getOperand(0);
921 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
923 switch (IntrinsicID) {
924 case AMDGPUIntrinsic::SI_tbuffer_store: {
943 EVT VT = Op.getOperand(3).getValueType();
945 MachineMemOperand *MMO = MF.getMachineMemOperand(
946 MachinePointerInfo(),
947 MachineMemOperand::MOStore,
948 VT.getStoreSize(), 4);
949 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
950 Op->getVTList(), Ops, VT, MMO);
957 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
959 LoadSDNode *Load = cast<LoadSDNode>(Op);
961 if (Op.getValueType().isVector()) {
962 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
963 "Custom lowering for non-i32 vectors hasn't been implemented.");
964 unsigned NumElements = Op.getValueType().getVectorNumElements();
965 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
966 switch (Load->getAddressSpace()) {
968 case AMDGPUAS::GLOBAL_ADDRESS:
969 case AMDGPUAS::PRIVATE_ADDRESS:
970 // v4 loads are supported for private and global memory.
971 if (NumElements <= 4)
974 case AMDGPUAS::LOCAL_ADDRESS:
975 return ScalarizeVectorLoad(Op, DAG);
979 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
982 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
984 SelectionDAG &DAG) const {
985 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
991 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
992 if (Op.getValueType() != MVT::i64)
996 SDValue Cond = Op.getOperand(0);
998 SDValue Zero = DAG.getConstant(0, MVT::i32);
999 SDValue One = DAG.getConstant(1, MVT::i32);
1001 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1002 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1004 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1005 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1007 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1009 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1010 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1012 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1014 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1015 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1018 // Catch division cases where we can use shortcuts with rcp and rsq
1020 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1022 SDValue LHS = Op.getOperand(0);
1023 SDValue RHS = Op.getOperand(1);
1024 EVT VT = Op.getValueType();
1025 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1027 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1028 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1029 CLHS->isExactlyValue(1.0)) {
1030 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1031 // the CI documentation has a worst case error of 1 ulp.
1032 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1033 // use it as long as we aren't trying to use denormals.
1035 // 1.0 / sqrt(x) -> rsq(x)
1037 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1038 // error seems really high at 2^29 ULP.
1039 if (RHS.getOpcode() == ISD::FSQRT)
1040 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1042 // 1.0 / x -> rcp(x)
1043 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1048 // Turn into multiply by the reciprocal.
1049 // x / y -> x * (1.0 / y)
1050 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1051 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1057 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1058 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1059 if (FastLowered.getNode())
1062 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1063 // selection error for now rather than do something incorrect.
1064 if (Subtarget->hasFP32Denormals())
1068 SDValue LHS = Op.getOperand(0);
1069 SDValue RHS = Op.getOperand(1);
1071 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1073 const APFloat K0Val(BitsToFloat(0x6f800000));
1074 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1076 const APFloat K1Val(BitsToFloat(0x2f800000));
1077 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1079 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1081 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1083 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1085 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1087 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1089 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1091 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1093 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1096 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1100 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1101 EVT VT = Op.getValueType();
1104 return LowerFDIV32(Op, DAG);
1107 return LowerFDIV64(Op, DAG);
1109 llvm_unreachable("Unexpected type for fdiv");
1112 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1114 StoreSDNode *Store = cast<StoreSDNode>(Op);
1115 EVT VT = Store->getMemoryVT();
1117 // These stores are legal.
1118 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1119 VT.isVector() && VT.getVectorNumElements() == 2 &&
1120 VT.getVectorElementType() == MVT::i32)
1123 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1124 if (VT.isVector() && VT.getVectorNumElements() > 4)
1125 return ScalarizeVectorStore(Op, DAG);
1129 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1133 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1134 return ScalarizeVectorStore(Op, DAG);
1137 return DAG.getTruncStore(Store->getChain(), DL,
1138 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1139 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1144 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1145 EVT VT = Op.getValueType();
1146 SDValue Arg = Op.getOperand(0);
1147 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1148 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1149 DAG.getConstantFP(0.5 / M_PI, VT)));
1151 switch (Op.getOpcode()) {
1153 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1155 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1157 llvm_unreachable("Wrong trig opcode");
1161 //===----------------------------------------------------------------------===//
1162 // Custom DAG optimizations
1163 //===----------------------------------------------------------------------===//
1165 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1166 DAGCombinerInfo &DCI) {
1167 EVT VT = N->getValueType(0);
1168 EVT ScalarVT = VT.getScalarType();
1169 if (ScalarVT != MVT::f32)
1172 SelectionDAG &DAG = DCI.DAG;
1175 SDValue Src = N->getOperand(0);
1176 EVT SrcVT = Src.getValueType();
1178 // TODO: We could try to match extracting the higher bytes, which would be
1179 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1180 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1181 // about in practice.
1182 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1183 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1184 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1185 DCI.AddToWorklist(Cvt.getNode());
1190 // We are primarily trying to catch operations on illegal vector types
1191 // before they are expanded.
1192 // For scalars, we can use the more flexible method of checking masked bits
1193 // after legalization.
1194 if (!DCI.isBeforeLegalize() ||
1195 !SrcVT.isVector() ||
1196 SrcVT.getVectorElementType() != MVT::i8) {
1200 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1202 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1204 unsigned NElts = SrcVT.getVectorNumElements();
1205 if (!SrcVT.isSimple() && NElts != 3)
1208 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1209 // prevent a mess from expanding to v4i32 and repacking.
1210 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1211 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1212 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1213 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1215 LoadSDNode *Load = cast<LoadSDNode>(Src);
1216 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1220 Load->getMemOperand());
1222 // Make sure successors of the original load stay after it by updating
1223 // them to use the new Chain.
1224 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1226 SmallVector<SDValue, 4> Elts;
1227 if (RegVT.isVector())
1228 DAG.ExtractVectorElements(NewLoad, Elts);
1230 Elts.push_back(NewLoad);
1232 SmallVector<SDValue, 4> Ops;
1234 unsigned EltIdx = 0;
1235 for (SDValue Elt : Elts) {
1236 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1237 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1238 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1239 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1240 DCI.AddToWorklist(Cvt.getNode());
1247 assert(Ops.size() == NElts);
1249 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1255 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1257 // This is a variant of
1258 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1260 // The normal DAG combiner will do this, but only if the add has one use since
1261 // that would increase the number of instructions.
1263 // This prevents us from seeing a constant offset that can be folded into a
1264 // memory instruction's addressing mode. If we know the resulting add offset of
1265 // a pointer can be folded into an addressing offset, we can replace the pointer
1266 // operand with the add of new constant offset. This eliminates one of the uses,
1267 // and may allow the remaining use to also be simplified.
1269 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1271 DAGCombinerInfo &DCI) const {
1272 SDValue N0 = N->getOperand(0);
1273 SDValue N1 = N->getOperand(1);
1275 if (N0.getOpcode() != ISD::ADD)
1278 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1282 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1286 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1287 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1289 // If the resulting offset is too large, we can't fold it into the addressing
1291 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1292 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1295 SelectionDAG &DAG = DCI.DAG;
1297 EVT VT = N->getValueType(0);
1299 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1300 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1302 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1305 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1308 return AMDGPUISD::FMAX3;
1309 case AMDGPUISD::SMAX:
1310 return AMDGPUISD::SMAX3;
1311 case AMDGPUISD::UMAX:
1312 return AMDGPUISD::UMAX3;
1314 return AMDGPUISD::FMIN3;
1315 case AMDGPUISD::SMIN:
1316 return AMDGPUISD::SMIN3;
1317 case AMDGPUISD::UMIN:
1318 return AMDGPUISD::UMIN3;
1320 llvm_unreachable("Not a min/max opcode");
1324 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1325 DAGCombinerInfo &DCI) const {
1326 SelectionDAG &DAG = DCI.DAG;
1328 unsigned Opc = N->getOpcode();
1329 SDValue Op0 = N->getOperand(0);
1330 SDValue Op1 = N->getOperand(1);
1332 // Only do this if the inner op has one use since this will just increases
1333 // register pressure for no benefit.
1335 // max(max(a, b), c)
1336 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1338 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1346 // max(a, max(b, c))
1347 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1349 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1360 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1361 DAGCombinerInfo &DCI) const {
1362 SelectionDAG &DAG = DCI.DAG;
1364 EVT VT = N->getValueType(0);
1366 switch (N->getOpcode()) {
1367 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1369 SDValue Arg0 = N->getOperand(0);
1370 SDValue Arg1 = N->getOperand(1);
1371 SDValue CC = N->getOperand(2);
1372 ConstantSDNode * C = nullptr;
1373 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1375 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1377 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1378 && Arg0.getOperand(0).getValueType() == MVT::i1
1379 && (C = dyn_cast<ConstantSDNode>(Arg1))
1381 && CCOp == ISD::SETNE) {
1382 return SimplifySetCC(VT, Arg0.getOperand(0),
1383 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1387 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1389 case AMDGPUISD::SMAX:
1390 case AMDGPUISD::SMIN:
1391 case AMDGPUISD::UMAX:
1392 case AMDGPUISD::UMIN: {
1393 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1394 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1395 return performMin3Max3Combine(N, DCI);
1399 case AMDGPUISD::CVT_F32_UBYTE0:
1400 case AMDGPUISD::CVT_F32_UBYTE1:
1401 case AMDGPUISD::CVT_F32_UBYTE2:
1402 case AMDGPUISD::CVT_F32_UBYTE3: {
1403 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1405 SDValue Src = N->getOperand(0);
1406 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1408 APInt KnownZero, KnownOne;
1409 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1410 !DCI.isBeforeLegalizeOps());
1411 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1412 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1413 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1414 DCI.CommitTargetLoweringOpt(TLO);
1420 case ISD::UINT_TO_FP: {
1421 return performUCharToFloatCombine(N, DCI);
1424 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1427 EVT VT = N->getValueType(0);
1431 SDValue LHS = N->getOperand(0);
1432 SDValue RHS = N->getOperand(1);
1434 // These should really be instruction patterns, but writing patterns with
1435 // source modiifiers is a pain.
1437 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1438 if (LHS.getOpcode() == ISD::FADD) {
1439 SDValue A = LHS.getOperand(0);
1440 if (A == LHS.getOperand(1)) {
1441 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1442 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1446 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1447 if (RHS.getOpcode() == ISD::FADD) {
1448 SDValue A = RHS.getOperand(0);
1449 if (A == RHS.getOperand(1)) {
1450 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1451 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1458 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1461 EVT VT = N->getValueType(0);
1463 // Try to get the fneg to fold into the source modifier. This undoes generic
1464 // DAG combines and folds them into the mad.
1465 if (VT == MVT::f32) {
1466 SDValue LHS = N->getOperand(0);
1467 SDValue RHS = N->getOperand(1);
1469 if (LHS.getOpcode() == ISD::FMUL) {
1470 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1472 SDValue A = LHS.getOperand(0);
1473 SDValue B = LHS.getOperand(1);
1474 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1476 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1479 if (RHS.getOpcode() == ISD::FMUL) {
1480 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1482 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1483 SDValue B = RHS.getOperand(1);
1486 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1489 if (LHS.getOpcode() == ISD::FADD) {
1490 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1492 SDValue A = LHS.getOperand(0);
1493 if (A == LHS.getOperand(1)) {
1494 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1495 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1497 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1501 if (RHS.getOpcode() == ISD::FADD) {
1502 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1504 SDValue A = RHS.getOperand(0);
1505 if (A == RHS.getOperand(1)) {
1506 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1507 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1517 case ISD::ATOMIC_LOAD:
1518 case ISD::ATOMIC_STORE:
1519 case ISD::ATOMIC_CMP_SWAP:
1520 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1521 case ISD::ATOMIC_SWAP:
1522 case ISD::ATOMIC_LOAD_ADD:
1523 case ISD::ATOMIC_LOAD_SUB:
1524 case ISD::ATOMIC_LOAD_AND:
1525 case ISD::ATOMIC_LOAD_OR:
1526 case ISD::ATOMIC_LOAD_XOR:
1527 case ISD::ATOMIC_LOAD_NAND:
1528 case ISD::ATOMIC_LOAD_MIN:
1529 case ISD::ATOMIC_LOAD_MAX:
1530 case ISD::ATOMIC_LOAD_UMIN:
1531 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1532 if (DCI.isBeforeLegalize())
1535 MemSDNode *MemNode = cast<MemSDNode>(N);
1536 SDValue Ptr = MemNode->getBasePtr();
1538 // TODO: We could also do this for multiplies.
1539 unsigned AS = MemNode->getAddressSpace();
1540 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1541 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1543 SmallVector<SDValue, 8> NewOps;
1544 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1545 NewOps.push_back(MemNode->getOperand(I));
1547 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1548 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1554 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1557 /// \brief Test if RegClass is one of the VSrc classes
1558 static bool isVSrc(unsigned RegClass) {
1560 default: return false;
1561 case AMDGPU::VSrc_32RegClassID:
1562 case AMDGPU::VCSrc_32RegClassID:
1563 case AMDGPU::VSrc_64RegClassID:
1564 case AMDGPU::VCSrc_64RegClassID:
1569 /// \brief Test if RegClass is one of the SSrc classes
1570 static bool isSSrc(unsigned RegClass) {
1571 return AMDGPU::SSrc_32RegClassID == RegClass ||
1572 AMDGPU::SSrc_64RegClassID == RegClass;
1575 /// \brief Analyze the possible immediate value Op
1577 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1578 /// and the immediate value if it's a literal immediate
1579 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1581 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1582 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1584 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1585 if (Node->getZExtValue() >> 32)
1588 if (TII->isInlineConstant(Node->getAPIntValue()))
1591 return Node->getZExtValue();
1594 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1595 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1598 if (Node->getValueType(0) == MVT::f32)
1599 return FloatToBits(Node->getValueAPF().convertToFloat());
1607 /// \brief Try to fold an immediate directly into an instruction
1608 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1609 bool &ScalarSlotUsed) const {
1611 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1612 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1613 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1614 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1617 const SDValue &Op = Mov->getOperand(0);
1618 int32_t Value = analyzeImmediate(Op.getNode());
1620 // Not an immediate at all
1623 } else if (Value == 0) {
1624 // Inline immediates can always be fold
1628 } else if (Value == Immediate) {
1629 // Already fold literal immediate
1633 } else if (!ScalarSlotUsed && !Immediate) {
1634 // Fold this literal immediate
1635 ScalarSlotUsed = true;
1645 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1646 SelectionDAG &DAG, const SDValue &Op) const {
1647 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1648 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1649 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1651 if (!Op->isMachineOpcode()) {
1652 switch(Op->getOpcode()) {
1653 case ISD::CopyFromReg: {
1654 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1655 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1656 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1657 return MRI.getRegClass(Reg);
1659 return TRI.getPhysRegClass(Reg);
1661 default: return nullptr;
1664 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1665 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1666 if (OpClassID != -1) {
1667 return TRI.getRegClass(OpClassID);
1669 switch(Op.getMachineOpcode()) {
1670 case AMDGPU::COPY_TO_REGCLASS:
1671 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1672 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1674 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1675 // class, then the register class for the value could be either a
1676 // VReg or and SReg. In order to get a more accurate
1677 if (isVSrc(OpClassID))
1678 return getRegClassForNode(DAG, Op.getOperand(0));
1680 return TRI.getRegClass(OpClassID);
1681 case AMDGPU::EXTRACT_SUBREG: {
1682 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1683 const TargetRegisterClass *SuperClass =
1684 getRegClassForNode(DAG, Op.getOperand(0));
1685 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1687 case AMDGPU::REG_SEQUENCE:
1688 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1689 return TRI.getRegClass(
1690 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1692 return getRegClassFor(Op.getSimpleValueType());
1696 /// \brief Does "Op" fit into register class "RegClass" ?
1697 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1698 unsigned RegClass) const {
1699 const TargetRegisterInfo *TRI =
1700 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1701 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1705 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1708 /// \returns true if \p Node's operands are different from the SDValue list
1710 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1711 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1712 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1719 /// TODO: This needs to be removed. It's current primary purpose is to fold
1720 /// immediates into operands when legal. The legalization parts are redundant
1721 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1722 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1723 SelectionDAG &DAG) const {
1724 // Original encoding (either e32 or e64)
1725 int Opcode = Node->getMachineOpcode();
1726 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1727 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1728 const MCInstrDesc *Desc = &TII->get(Opcode);
1730 unsigned NumDefs = Desc->getNumDefs();
1731 unsigned NumOps = Desc->getNumOperands();
1733 // Commuted opcode if available
1734 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1735 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1737 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1738 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1740 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1741 bool HaveVSrc = false, HaveSSrc = false;
1743 // First figure out what we already have in this instruction.
1744 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1745 i != e && Op < NumOps; ++i, ++Op) {
1747 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1748 if (isVSrc(RegClass))
1750 else if (isSSrc(RegClass))
1755 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1756 if (Imm != -1 && Imm != 0) {
1757 // Literal immediate
1762 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1763 if (!HaveVSrc && !HaveSSrc)
1766 // No scalar allowed when we have both VSrc and SSrc
1767 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1769 // If this instruction has an implicit use of VCC, then it can't use the
1771 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1772 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1773 ScalarSlotUsed = true;
1778 // Second go over the operands and try to fold them
1779 std::vector<SDValue> Ops;
1780 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1781 i != e && Op < NumOps; ++i, ++Op) {
1783 const SDValue &Operand = Node->getOperand(i);
1784 Ops.push_back(Operand);
1786 // Already folded immediate?
1787 if (isa<ConstantSDNode>(Operand.getNode()) ||
1788 isa<ConstantFPSDNode>(Operand.getNode()))
1791 // Is this a VSrc or SSrc operand?
1792 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1793 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1794 // Try to fold the immediates. If this ends up with multiple constant bus
1795 // uses, it will be legalized later.
1796 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1800 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1802 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1803 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1805 // Test if it makes sense to swap operands
1806 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1807 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1808 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1810 // Swap commutable operands
1811 std::swap(Ops[0], Ops[1]);
1820 // Add optional chain and glue
1821 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1822 Ops.push_back(Node->getOperand(i));
1824 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1825 // this case a brand new node is always be created, even if the operands
1826 // are the same as before. So, manually check if anything has been changed.
1827 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1831 // Create a complete new instruction
1832 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1835 /// \brief Helper function for adjustWritemask
1836 static unsigned SubIdx2Lane(unsigned Idx) {
1839 case AMDGPU::sub0: return 0;
1840 case AMDGPU::sub1: return 1;
1841 case AMDGPU::sub2: return 2;
1842 case AMDGPU::sub3: return 3;
1846 /// \brief Adjust the writemask of MIMG instructions
1847 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1848 SelectionDAG &DAG) const {
1849 SDNode *Users[4] = { };
1851 unsigned OldDmask = Node->getConstantOperandVal(0);
1852 unsigned NewDmask = 0;
1854 // Try to figure out the used register components
1855 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1858 // Abort if we can't understand the usage
1859 if (!I->isMachineOpcode() ||
1860 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1863 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1864 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1865 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1867 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1869 // Set which texture component corresponds to the lane.
1871 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1873 Comp = countTrailingZeros(Dmask);
1874 Dmask &= ~(1 << Comp);
1877 // Abort if we have more than one user per component
1882 NewDmask |= 1 << Comp;
1885 // Abort if there's no change
1886 if (NewDmask == OldDmask)
1889 // Adjust the writemask in the node
1890 std::vector<SDValue> Ops;
1891 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1892 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1893 Ops.push_back(Node->getOperand(i));
1894 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1896 // If we only got one lane, replace it with a copy
1897 // (if NewDmask has only one bit set...)
1898 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1899 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1900 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1901 SDLoc(), Users[Lane]->getValueType(0),
1902 SDValue(Node, 0), RC);
1903 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1907 // Update the users of the node with the new indices
1908 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1910 SDNode *User = Users[i];
1914 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1915 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1919 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1920 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1921 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1926 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1927 /// with frame index operands.
1928 /// LLVM assumes that inputs are to these instructions are registers.
1929 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1930 SelectionDAG &DAG) const {
1932 SmallVector<SDValue, 8> Ops;
1933 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1934 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1935 Ops.push_back(Node->getOperand(i));
1940 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1941 Node->getOperand(i).getValueType(),
1942 Node->getOperand(i)), 0));
1945 DAG.UpdateNodeOperands(Node, Ops);
1948 /// \brief Fold the instructions after selecting them.
1949 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1950 SelectionDAG &DAG) const {
1951 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1952 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1953 Node = AdjustRegClass(Node, DAG);
1955 if (TII->isMIMG(Node->getMachineOpcode()))
1956 adjustWritemask(Node, DAG);
1958 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1959 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1960 legalizeTargetIndependentNode(Node, DAG);
1964 return legalizeOperands(Node, DAG);
1967 /// \brief Assign the register class depending on the number of
1968 /// bits set in the writemask
1969 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1970 SDNode *Node) const {
1971 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1972 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1974 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1975 TII->legalizeOperands(MI);
1977 if (TII->isMIMG(MI->getOpcode())) {
1978 unsigned VReg = MI->getOperand(0).getReg();
1979 unsigned Writemask = MI->getOperand(1).getImm();
1980 unsigned BitsSet = 0;
1981 for (unsigned i = 0; i < 4; ++i)
1982 BitsSet += Writemask & (1 << i) ? 1 : 0;
1984 const TargetRegisterClass *RC;
1987 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1988 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1989 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1992 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1993 MI->setDesc(TII->get(NewOpcode));
1994 MRI.setRegClass(VReg, RC);
1998 // Replace unused atomics with the no return version.
1999 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2000 if (NoRetAtomicOp != -1) {
2001 if (!Node->hasAnyUseOfValue(0)) {
2002 MI->setDesc(TII->get(NoRetAtomicOp));
2003 MI->RemoveOperand(0);
2010 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2011 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
2012 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2015 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2017 SDValue Ptr) const {
2018 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
2019 getTargetMachine().getSubtargetImpl()->getInstrInfo());
2021 // XXX - Workaround for moveToVALU not handling different register class
2022 // inserts for REG_SEQUENCE.
2024 // Build the half of the subregister with the constants.
2025 const SDValue Ops0[] = {
2026 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2027 buildSMovImm32(DAG, DL, 0),
2028 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2029 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2030 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2033 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2034 MVT::v2i32, Ops0), 0);
2036 // Combine the constants and the pointer.
2037 const SDValue Ops1[] = {
2038 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2040 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2042 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2045 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2047 const SDValue Ops[] = {
2048 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2050 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2051 buildSMovImm32(DAG, DL, 0),
2052 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2053 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2054 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2057 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2062 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2063 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2064 /// of the resource descriptor) to create an offset, which is added to the
2065 /// resource ponter.
2066 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2069 uint32_t RsrcDword1,
2070 uint64_t RsrcDword2And3) const {
2071 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2072 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2074 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2075 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2078 SDValue DataLo = buildSMovImm32(DAG, DL,
2079 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2080 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2082 const SDValue Ops[] = {
2083 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2085 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2087 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2089 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2091 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2094 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2097 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2099 SDValue Ptr) const {
2100 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
2101 getTargetMachine().getSubtargetImpl()->getInstrInfo());
2102 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2105 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2108 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2109 SelectionDAG &DAG) const {
2112 unsigned NewOpcode = N->getMachineOpcode();
2114 switch (N->getMachineOpcode()) {
2116 case AMDGPU::S_LOAD_DWORD_IMM:
2117 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2119 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2120 if (NewOpcode == N->getMachineOpcode()) {
2121 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2124 case AMDGPU::S_LOAD_DWORDX4_IMM:
2125 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2126 if (NewOpcode == N->getMachineOpcode()) {
2127 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2129 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2132 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2134 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2135 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2136 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2138 SmallVector<SDValue, 8> Ops;
2139 Ops.push_back(SDValue(RSrc, 0));
2140 Ops.push_back(N->getOperand(0));
2142 // The immediate offset is in dwords on SI and in bytes on VI.
2143 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2144 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2146 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2148 // Copy remaining operands so we keep any chain and glue nodes that follow
2149 // the normal operands.
2150 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2151 Ops.push_back(N->getOperand(I));
2153 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2158 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2159 const TargetRegisterClass *RC,
2160 unsigned Reg, EVT VT) const {
2161 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2163 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2164 cast<RegisterSDNode>(VReg)->getReg(), VT);