1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Custom DAG lowering for SI
13 //===----------------------------------------------------------------------===//
17 #define _USE_MATH_DEFINES
21 #include "SIISelLowering.h"
23 #include "AMDGPUIntrinsicInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/ADT/SmallString.h"
38 SITargetLowering::SITargetLowering(TargetMachine &TM,
39 const AMDGPUSubtarget &STI)
40 : AMDGPUTargetLowering(TM, STI) {
41 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
42 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
44 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
45 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
47 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
48 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
50 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
51 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
52 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
54 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
55 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
57 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
58 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
60 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
61 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
63 computeRegisterProperties();
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
68 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
71 setOperationAction(ISD::ADDC, MVT::i32, Legal);
72 setOperationAction(ISD::ADDE, MVT::i32, Legal);
73 setOperationAction(ISD::SUBC, MVT::i32, Legal);
74 setOperationAction(ISD::SUBE, MVT::i32, Legal);
76 setOperationAction(ISD::FSIN, MVT::f32, Custom);
77 setOperationAction(ISD::FCOS, MVT::f32, Custom);
79 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
80 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
81 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
82 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
84 // We need to custom lower vector stores from local memory
85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
90 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
92 setOperationAction(ISD::STORE, MVT::i1, Custom);
93 setOperationAction(ISD::STORE, MVT::i32, Custom);
94 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
95 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
97 setOperationAction(ISD::SELECT, MVT::i64, Custom);
98 setOperationAction(ISD::SELECT, MVT::f64, Promote);
99 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
101 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
102 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
103 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
104 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
106 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
107 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
109 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
111 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
115 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
126 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
127 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
128 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
129 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
131 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
132 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
134 for (MVT VT : MVT::integer_valuetypes()) {
138 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
139 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
143 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
144 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
145 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
146 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
148 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
149 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
150 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
151 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
154 for (MVT VT : MVT::integer_vector_valuetypes()) {
155 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
156 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
159 for (MVT VT : MVT::fp_valuetypes())
160 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
162 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
163 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
164 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
165 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
166 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
167 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
169 setOperationAction(ISD::LOAD, MVT::i1, Custom);
171 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
172 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
173 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
175 // These should use UDIVREM, so set them to expand
176 setOperationAction(ISD::UDIV, MVT::i64, Expand);
177 setOperationAction(ISD::UREM, MVT::i64, Expand);
179 // We only support LOAD/STORE and vector manipulation ops for vectors
180 // with > 4 elements.
182 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
185 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
186 setOperationAction(ISD::SELECT, MVT::i1, Promote);
188 for (MVT VT : VecTypes) {
189 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
193 case ISD::BUILD_VECTOR:
195 case ISD::EXTRACT_VECTOR_ELT:
196 case ISD::INSERT_VECTOR_ELT:
197 case ISD::INSERT_SUBVECTOR:
198 case ISD::EXTRACT_SUBVECTOR:
200 case ISD::CONCAT_VECTORS:
201 setOperationAction(Op, VT, Custom);
204 setOperationAction(Op, VT, Expand);
210 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
211 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
212 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
213 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
214 setOperationAction(ISD::FRINT, MVT::f64, Legal);
217 setOperationAction(ISD::FDIV, MVT::f32, Custom);
219 setTargetDAGCombine(ISD::FADD);
220 setTargetDAGCombine(ISD::FSUB);
221 setTargetDAGCombine(ISD::FMINNUM);
222 setTargetDAGCombine(ISD::FMAXNUM);
223 setTargetDAGCombine(ISD::SELECT_CC);
224 setTargetDAGCombine(ISD::SETCC);
225 setTargetDAGCombine(ISD::AND);
226 setTargetDAGCombine(ISD::OR);
227 setTargetDAGCombine(ISD::UINT_TO_FP);
229 // All memory operations. Some folding on the pointer operand is done to help
230 // matching the constant offsets in the addressing modes.
231 setTargetDAGCombine(ISD::LOAD);
232 setTargetDAGCombine(ISD::STORE);
233 setTargetDAGCombine(ISD::ATOMIC_LOAD);
234 setTargetDAGCombine(ISD::ATOMIC_STORE);
235 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
236 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
237 setTargetDAGCombine(ISD::ATOMIC_SWAP);
238 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
249 setSchedulingPreference(Sched::RegPressure);
252 //===----------------------------------------------------------------------===//
253 // TargetLowering queries
254 //===----------------------------------------------------------------------===//
256 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
258 // SI has some legal vector types, but no legal vector operations. Say no
259 // shuffles are legal in order to prefer scalarizing some vector operations.
263 // FIXME: This really needs an address space argument. The immediate offset
264 // size is different for different sets of memory instruction sets.
266 // The single offset DS instructions have a 16-bit unsigned byte offset.
268 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
269 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
270 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
272 // SMRD instructions have an 8-bit, dword offset.
274 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
276 // No global is ever allowed as a base.
280 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
282 if (!isUInt<16>(AM.BaseOffs))
287 case 0: // "r+i" or just "i", depending on HasBaseReg.
290 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
292 // Otherwise we have r+r or r+i.
295 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
299 default: // Don't allow n * r
306 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
309 bool *IsFast) const {
313 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
314 // which isn't a simple VT.
315 if (!VT.isSimple() || VT == MVT::Other)
318 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
319 // see what for specifically. The wording everywhere else seems to be the
322 // XXX - The only mention I see of this in the ISA manual is for LDS direct
323 // reads the "byte address and must be dword aligned". Is it also true for the
324 // normal loads and stores?
325 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
326 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
327 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
328 // with adjacent offsets.
329 return Align % 4 == 0;
332 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
333 // byte-address are ignored, thus forcing Dword alignment.
334 // This applies to private, global, and constant memory.
337 return VT.bitsGT(MVT::i32);
340 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
341 unsigned SrcAlign, bool IsMemset,
344 MachineFunction &MF) const {
345 // FIXME: Should account for address space here.
347 // The default fallback uses the private pointer size as a guess for a type to
348 // use. Make sure we switch these to 64-bit accesses.
350 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
353 if (Size >= 8 && DstAlign >= 4)
360 TargetLoweringBase::LegalizeTypeAction
361 SITargetLowering::getPreferredVectorAction(EVT VT) const {
362 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
363 return TypeSplitVector;
365 return TargetLoweringBase::getPreferredVectorAction(VT);
368 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
370 const SIInstrInfo *TII =
371 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
372 return TII->isInlineConstant(Imm);
375 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
376 SDLoc SL, SDValue Chain,
377 unsigned Offset, bool Signed) const {
378 const DataLayout *DL = getDataLayout();
379 MachineFunction &MF = DAG.getMachineFunction();
380 const SIRegisterInfo *TRI =
381 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
382 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
384 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
386 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
387 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
388 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
389 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
390 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
391 DAG.getConstant(Offset, MVT::i64));
392 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
393 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
395 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
396 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
398 true, // isNonTemporal
400 DL->getABITypeAlignment(Ty)); // Alignment
403 SDValue SITargetLowering::LowerFormalArguments(
404 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
405 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
406 SmallVectorImpl<SDValue> &InVals) const {
407 const SIRegisterInfo *TRI =
408 static_cast<const SIRegisterInfo *>(Subtarget->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);
588 if (Info->getShaderType() != ShaderType::COMPUTE) {
589 unsigned ScratchIdx = CCInfo.getFirstUnallocated(
590 AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs());
591 Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
596 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
597 MachineInstr * MI, MachineBasicBlock * BB) const {
599 MachineBasicBlock::iterator I = *MI;
600 const SIInstrInfo *TII =
601 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
603 switch (MI->getOpcode()) {
605 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
606 case AMDGPU::BRANCH: return BB;
607 case AMDGPU::V_SUB_F64: {
608 unsigned DestReg = MI->getOperand(0).getReg();
609 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
610 .addImm(0) // SRC0 modifiers
611 .addReg(MI->getOperand(1).getReg())
612 .addImm(1) // SRC1 modifiers
613 .addReg(MI->getOperand(2).getReg())
616 MI->eraseFromParent();
619 case AMDGPU::SI_RegisterStorePseudo: {
620 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
621 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
622 MachineInstrBuilder MIB =
623 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
625 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
626 MIB.addOperand(MI->getOperand(i));
628 MI->eraseFromParent();
635 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
636 // This currently forces unfolding various combinations of fsub into fma with
637 // free fneg'd operands. As long as we have fast FMA (controlled by
638 // isFMAFasterThanFMulAndFAdd), we should perform these.
640 // When fma is quarter rate, for f64 where add / sub are at best half rate,
641 // most of these combines appear to be cycle neutral but save on instruction
642 // count / code size.
646 EVT SITargetLowering::getSetCCResultType(LLVMContext &Ctx, EVT VT) const {
647 if (!VT.isVector()) {
650 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
653 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
657 // Answering this is somewhat tricky and depends on the specific device which
658 // have different rates for fma or all f64 operations.
660 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
661 // regardless of which device (although the number of cycles differs between
662 // devices), so it is always profitable for f64.
664 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
665 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
666 // which we can always do even without fused FP ops since it returns the same
667 // result as the separate operations and since it is always full
668 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
669 // however does not support denormals, so we do report fma as faster if we have
670 // a fast fma device and require denormals.
672 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
673 VT = VT.getScalarType();
678 switch (VT.getSimpleVT().SimpleTy) {
680 // This is as fast on some subtargets. However, we always have full rate f32
681 // mad available which returns the same result as the separate operations
682 // which we should prefer over fma.
693 //===----------------------------------------------------------------------===//
694 // Custom DAG Lowering Operations
695 //===----------------------------------------------------------------------===//
697 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
698 switch (Op.getOpcode()) {
699 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
700 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
701 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
703 SDValue Result = LowerLOAD(Op, DAG);
704 assert((!Result.getNode() ||
705 Result.getNode()->getNumValues() == 2) &&
706 "Load should return a value and a chain");
712 return LowerTrig(Op, DAG);
713 case ISD::SELECT: return LowerSELECT(Op, DAG);
714 case ISD::FDIV: return LowerFDIV(Op, DAG);
715 case ISD::STORE: return LowerSTORE(Op, DAG);
716 case ISD::GlobalAddress: {
717 MachineFunction &MF = DAG.getMachineFunction();
718 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
719 return LowerGlobalAddress(MFI, Op, DAG);
721 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
722 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
727 /// \brief Helper function for LowerBRCOND
728 static SDNode *findUser(SDValue Value, unsigned Opcode) {
730 SDNode *Parent = Value.getNode();
731 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
734 if (I.getUse().get() != Value)
737 if (I->getOpcode() == Opcode)
743 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
745 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
746 unsigned FrameIndex = FINode->getIndex();
748 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
751 /// This transforms the control flow intrinsics to get the branch destination as
752 /// last parameter, also switches branch target with BR if the need arise
753 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
754 SelectionDAG &DAG) const {
758 SDNode *Intr = BRCOND.getOperand(1).getNode();
759 SDValue Target = BRCOND.getOperand(2);
760 SDNode *BR = nullptr;
762 if (Intr->getOpcode() == ISD::SETCC) {
763 // As long as we negate the condition everything is fine
764 SDNode *SetCC = Intr;
765 assert(SetCC->getConstantOperandVal(1) == 1);
766 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
768 Intr = SetCC->getOperand(0).getNode();
771 // Get the target from BR if we don't negate the condition
772 BR = findUser(BRCOND, ISD::BR);
773 Target = BR->getOperand(1);
776 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
778 // Build the result and
779 SmallVector<EVT, 4> Res;
780 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
781 Res.push_back(Intr->getValueType(i));
783 // operands of the new intrinsic call
784 SmallVector<SDValue, 4> Ops;
785 Ops.push_back(BRCOND.getOperand(0));
786 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
787 Ops.push_back(Intr->getOperand(i));
788 Ops.push_back(Target);
790 // build the new intrinsic call
791 SDNode *Result = DAG.getNode(
792 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
793 DAG.getVTList(Res), Ops).getNode();
796 // Give the branch instruction our target
801 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
802 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
803 BR = NewBR.getNode();
806 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
808 // Copy the intrinsic results to registers
809 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
810 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
814 Chain = DAG.getCopyToReg(
816 CopyToReg->getOperand(1),
817 SDValue(Result, i - 1),
820 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
823 // Remove the old intrinsic from the chain
824 DAG.ReplaceAllUsesOfValueWith(
825 SDValue(Intr, Intr->getNumValues() - 1),
826 Intr->getOperand(0));
831 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
833 SelectionDAG &DAG) const {
834 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
836 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
837 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
840 const GlobalValue *GV = GSD->getGlobal();
841 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
843 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
844 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
846 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
847 DAG.getConstant(0, MVT::i32));
848 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
849 DAG.getConstant(1, MVT::i32));
851 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
853 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
854 PtrHi, DAG.getConstant(0, MVT::i32),
855 SDValue(Lo.getNode(), 1));
856 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
859 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
860 SelectionDAG &DAG) const {
861 MachineFunction &MF = DAG.getMachineFunction();
862 const SIRegisterInfo *TRI =
863 static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
865 EVT VT = Op.getValueType();
867 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
869 switch (IntrinsicID) {
870 case Intrinsic::r600_read_ngroups_x:
871 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
872 SI::KernelInputOffsets::NGROUPS_X, false);
873 case Intrinsic::r600_read_ngroups_y:
874 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
875 SI::KernelInputOffsets::NGROUPS_Y, false);
876 case Intrinsic::r600_read_ngroups_z:
877 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
878 SI::KernelInputOffsets::NGROUPS_Z, false);
879 case Intrinsic::r600_read_global_size_x:
880 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
881 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
882 case Intrinsic::r600_read_global_size_y:
883 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
884 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
885 case Intrinsic::r600_read_global_size_z:
886 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
887 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
888 case Intrinsic::r600_read_local_size_x:
889 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
890 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
891 case Intrinsic::r600_read_local_size_y:
892 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
893 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
894 case Intrinsic::r600_read_local_size_z:
895 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
896 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
898 case Intrinsic::AMDGPU_read_workdim:
899 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
900 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
903 case Intrinsic::r600_read_tgid_x:
904 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
905 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
906 case Intrinsic::r600_read_tgid_y:
907 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
908 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
909 case Intrinsic::r600_read_tgid_z:
910 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
911 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
912 case Intrinsic::r600_read_tidig_x:
913 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
914 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
915 case Intrinsic::r600_read_tidig_y:
916 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
917 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
918 case Intrinsic::r600_read_tidig_z:
919 return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
920 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
921 case AMDGPUIntrinsic::SI_load_const: {
927 MachineMemOperand *MMO = MF.getMachineMemOperand(
928 MachinePointerInfo(),
929 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
930 VT.getStoreSize(), 4);
931 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
932 Op->getVTList(), Ops, VT, MMO);
934 case AMDGPUIntrinsic::SI_sample:
935 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
936 case AMDGPUIntrinsic::SI_sampleb:
937 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
938 case AMDGPUIntrinsic::SI_sampled:
939 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
940 case AMDGPUIntrinsic::SI_samplel:
941 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
942 case AMDGPUIntrinsic::SI_vs_load_input:
943 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
948 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
952 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
953 SelectionDAG &DAG) const {
954 MachineFunction &MF = DAG.getMachineFunction();
955 SDValue Chain = Op.getOperand(0);
956 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
958 switch (IntrinsicID) {
959 case AMDGPUIntrinsic::SI_tbuffer_store: {
978 EVT VT = Op.getOperand(3).getValueType();
980 MachineMemOperand *MMO = MF.getMachineMemOperand(
981 MachinePointerInfo(),
982 MachineMemOperand::MOStore,
983 VT.getStoreSize(), 4);
984 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
985 Op->getVTList(), Ops, VT, MMO);
992 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
994 LoadSDNode *Load = cast<LoadSDNode>(Op);
996 if (Op.getValueType().isVector()) {
997 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
998 "Custom lowering for non-i32 vectors hasn't been implemented.");
999 unsigned NumElements = Op.getValueType().getVectorNumElements();
1000 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1001 switch (Load->getAddressSpace()) {
1003 case AMDGPUAS::GLOBAL_ADDRESS:
1004 case AMDGPUAS::PRIVATE_ADDRESS:
1005 // v4 loads are supported for private and global memory.
1006 if (NumElements <= 4)
1009 case AMDGPUAS::LOCAL_ADDRESS:
1010 return ScalarizeVectorLoad(Op, DAG);
1014 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1017 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1019 SelectionDAG &DAG) const {
1020 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1026 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1027 if (Op.getValueType() != MVT::i64)
1031 SDValue Cond = Op.getOperand(0);
1033 SDValue Zero = DAG.getConstant(0, MVT::i32);
1034 SDValue One = DAG.getConstant(1, MVT::i32);
1036 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1037 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1039 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1040 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1042 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1044 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1045 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1047 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1049 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1050 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1053 // Catch division cases where we can use shortcuts with rcp and rsq
1055 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1057 SDValue LHS = Op.getOperand(0);
1058 SDValue RHS = Op.getOperand(1);
1059 EVT VT = Op.getValueType();
1060 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1062 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1063 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1064 CLHS->isExactlyValue(1.0)) {
1065 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1066 // the CI documentation has a worst case error of 1 ulp.
1067 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1068 // use it as long as we aren't trying to use denormals.
1070 // 1.0 / sqrt(x) -> rsq(x)
1072 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1073 // error seems really high at 2^29 ULP.
1074 if (RHS.getOpcode() == ISD::FSQRT)
1075 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1077 // 1.0 / x -> rcp(x)
1078 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1083 // Turn into multiply by the reciprocal.
1084 // x / y -> x * (1.0 / y)
1085 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1086 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1092 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1093 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1094 if (FastLowered.getNode())
1097 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1098 // selection error for now rather than do something incorrect.
1099 if (Subtarget->hasFP32Denormals())
1103 SDValue LHS = Op.getOperand(0);
1104 SDValue RHS = Op.getOperand(1);
1106 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1108 const APFloat K0Val(BitsToFloat(0x6f800000));
1109 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1111 const APFloat K1Val(BitsToFloat(0x2f800000));
1112 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1114 const SDValue One = DAG.getConstantFP(1.0, MVT::f32);
1116 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1118 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1120 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1122 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1124 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1126 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1128 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1131 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1135 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1136 EVT VT = Op.getValueType();
1139 return LowerFDIV32(Op, DAG);
1142 return LowerFDIV64(Op, DAG);
1144 llvm_unreachable("Unexpected type for fdiv");
1147 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1149 StoreSDNode *Store = cast<StoreSDNode>(Op);
1150 EVT VT = Store->getMemoryVT();
1152 // These stores are legal.
1153 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1154 VT.isVector() && VT.getVectorNumElements() == 2 &&
1155 VT.getVectorElementType() == MVT::i32)
1158 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1159 if (VT.isVector() && VT.getVectorNumElements() > 4)
1160 return ScalarizeVectorStore(Op, DAG);
1164 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1168 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1169 return ScalarizeVectorStore(Op, DAG);
1172 return DAG.getTruncStore(Store->getChain(), DL,
1173 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1174 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1179 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1180 EVT VT = Op.getValueType();
1181 SDValue Arg = Op.getOperand(0);
1182 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1183 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1184 DAG.getConstantFP(0.5 / M_PI, VT)));
1186 switch (Op.getOpcode()) {
1188 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1190 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1192 llvm_unreachable("Wrong trig opcode");
1196 //===----------------------------------------------------------------------===//
1197 // Custom DAG optimizations
1198 //===----------------------------------------------------------------------===//
1200 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1201 DAGCombinerInfo &DCI) const {
1202 EVT VT = N->getValueType(0);
1203 EVT ScalarVT = VT.getScalarType();
1204 if (ScalarVT != MVT::f32)
1207 SelectionDAG &DAG = DCI.DAG;
1210 SDValue Src = N->getOperand(0);
1211 EVT SrcVT = Src.getValueType();
1213 // TODO: We could try to match extracting the higher bytes, which would be
1214 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1215 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1216 // about in practice.
1217 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1218 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1219 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1220 DCI.AddToWorklist(Cvt.getNode());
1225 // We are primarily trying to catch operations on illegal vector types
1226 // before they are expanded.
1227 // For scalars, we can use the more flexible method of checking masked bits
1228 // after legalization.
1229 if (!DCI.isBeforeLegalize() ||
1230 !SrcVT.isVector() ||
1231 SrcVT.getVectorElementType() != MVT::i8) {
1235 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1237 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1239 unsigned NElts = SrcVT.getVectorNumElements();
1240 if (!SrcVT.isSimple() && NElts != 3)
1243 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1244 // prevent a mess from expanding to v4i32 and repacking.
1245 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1246 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1247 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1248 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1249 LoadSDNode *Load = cast<LoadSDNode>(Src);
1251 unsigned AS = Load->getAddressSpace();
1252 unsigned Align = Load->getAlignment();
1253 Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1254 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1256 // Don't try to replace the load if we have to expand it due to alignment
1257 // problems. Otherwise we will end up scalarizing the load, and trying to
1258 // repack into the vector for no real reason.
1259 if (Align < ABIAlignment &&
1260 !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1264 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1268 Load->getMemOperand());
1270 // Make sure successors of the original load stay after it by updating
1271 // them to use the new Chain.
1272 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1274 SmallVector<SDValue, 4> Elts;
1275 if (RegVT.isVector())
1276 DAG.ExtractVectorElements(NewLoad, Elts);
1278 Elts.push_back(NewLoad);
1280 SmallVector<SDValue, 4> Ops;
1282 unsigned EltIdx = 0;
1283 for (SDValue Elt : Elts) {
1284 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1285 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1286 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1287 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1288 DCI.AddToWorklist(Cvt.getNode());
1295 assert(Ops.size() == NElts);
1297 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1303 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1305 // This is a variant of
1306 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1308 // The normal DAG combiner will do this, but only if the add has one use since
1309 // that would increase the number of instructions.
1311 // This prevents us from seeing a constant offset that can be folded into a
1312 // memory instruction's addressing mode. If we know the resulting add offset of
1313 // a pointer can be folded into an addressing offset, we can replace the pointer
1314 // operand with the add of new constant offset. This eliminates one of the uses,
1315 // and may allow the remaining use to also be simplified.
1317 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1319 DAGCombinerInfo &DCI) const {
1320 SDValue N0 = N->getOperand(0);
1321 SDValue N1 = N->getOperand(1);
1323 if (N0.getOpcode() != ISD::ADD)
1326 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1330 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1334 const SIInstrInfo *TII =
1335 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1337 // If the resulting offset is too large, we can't fold it into the addressing
1339 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1340 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1343 SelectionDAG &DAG = DCI.DAG;
1345 EVT VT = N->getValueType(0);
1347 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1348 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1350 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1353 SDValue SITargetLowering::performAndCombine(SDNode *N,
1354 DAGCombinerInfo &DCI) const {
1355 if (DCI.isBeforeLegalize())
1358 SelectionDAG &DAG = DCI.DAG;
1360 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1361 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1362 SDValue LHS = N->getOperand(0);
1363 SDValue RHS = N->getOperand(1);
1365 if (LHS.getOpcode() == ISD::SETCC &&
1366 RHS.getOpcode() == ISD::SETCC) {
1367 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1368 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1370 SDValue X = LHS.getOperand(0);
1371 SDValue Y = RHS.getOperand(0);
1372 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1375 if (LCC == ISD::SETO) {
1376 if (X != LHS.getOperand(1))
1379 if (RCC == ISD::SETUNE) {
1380 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1381 if (!C1 || !C1->isInfinity() || C1->isNegative())
1384 const uint32_t Mask = SIInstrFlags::N_NORMAL |
1385 SIInstrFlags::N_SUBNORMAL |
1386 SIInstrFlags::N_ZERO |
1387 SIInstrFlags::P_ZERO |
1388 SIInstrFlags::P_SUBNORMAL |
1389 SIInstrFlags::P_NORMAL;
1391 static_assert(((~(SIInstrFlags::S_NAN |
1392 SIInstrFlags::Q_NAN |
1393 SIInstrFlags::N_INFINITY |
1394 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1397 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1398 X, DAG.getConstant(Mask, MVT::i32));
1406 SDValue SITargetLowering::performOrCombine(SDNode *N,
1407 DAGCombinerInfo &DCI) const {
1408 SelectionDAG &DAG = DCI.DAG;
1409 SDValue LHS = N->getOperand(0);
1410 SDValue RHS = N->getOperand(1);
1412 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1413 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1414 RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1415 SDValue Src = LHS.getOperand(0);
1416 if (Src != RHS.getOperand(0))
1419 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1420 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1424 // Only 10 bits are used.
1425 static const uint32_t MaxMask = 0x3ff;
1427 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1428 return DAG.getNode(AMDGPUISD::FP_CLASS, SDLoc(N), MVT::i1,
1429 Src, DAG.getConstant(NewMask, MVT::i32));
1435 SDValue SITargetLowering::performClassCombine(SDNode *N,
1436 DAGCombinerInfo &DCI) const {
1437 SelectionDAG &DAG = DCI.DAG;
1438 SDValue Mask = N->getOperand(1);
1440 // fp_class x, 0 -> false
1441 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1442 if (CMask->isNullValue())
1443 return DAG.getConstant(0, MVT::i1);
1449 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1452 return AMDGPUISD::FMAX3;
1453 case AMDGPUISD::SMAX:
1454 return AMDGPUISD::SMAX3;
1455 case AMDGPUISD::UMAX:
1456 return AMDGPUISD::UMAX3;
1458 return AMDGPUISD::FMIN3;
1459 case AMDGPUISD::SMIN:
1460 return AMDGPUISD::SMIN3;
1461 case AMDGPUISD::UMIN:
1462 return AMDGPUISD::UMIN3;
1464 llvm_unreachable("Not a min/max opcode");
1468 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1469 DAGCombinerInfo &DCI) const {
1470 SelectionDAG &DAG = DCI.DAG;
1472 unsigned Opc = N->getOpcode();
1473 SDValue Op0 = N->getOperand(0);
1474 SDValue Op1 = N->getOperand(1);
1476 // Only do this if the inner op has one use since this will just increases
1477 // register pressure for no benefit.
1479 // max(max(a, b), c)
1480 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1482 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1490 // max(a, max(b, c))
1491 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1493 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1504 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1505 DAGCombinerInfo &DCI) const {
1506 SelectionDAG &DAG = DCI.DAG;
1509 SDValue LHS = N->getOperand(0);
1510 SDValue RHS = N->getOperand(1);
1511 EVT VT = LHS.getValueType();
1513 if (VT != MVT::f32 && VT != MVT::f64)
1516 // Match isinf pattern
1517 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1518 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1519 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1520 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1524 const APFloat &APF = CRHS->getValueAPF();
1525 if (APF.isInfinity() && !APF.isNegative()) {
1526 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1527 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1,
1528 LHS.getOperand(0), DAG.getConstant(Mask, MVT::i32));
1535 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1536 DAGCombinerInfo &DCI) const {
1537 SelectionDAG &DAG = DCI.DAG;
1540 switch (N->getOpcode()) {
1542 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1544 return performSetCCCombine(N, DCI);
1545 case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1547 case AMDGPUISD::SMAX:
1548 case AMDGPUISD::SMIN:
1549 case AMDGPUISD::UMAX:
1550 case AMDGPUISD::UMIN: {
1551 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1552 getTargetMachine().getOptLevel() > CodeGenOpt::None)
1553 return performMin3Max3Combine(N, DCI);
1557 case AMDGPUISD::CVT_F32_UBYTE0:
1558 case AMDGPUISD::CVT_F32_UBYTE1:
1559 case AMDGPUISD::CVT_F32_UBYTE2:
1560 case AMDGPUISD::CVT_F32_UBYTE3: {
1561 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1563 SDValue Src = N->getOperand(0);
1564 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1566 APInt KnownZero, KnownOne;
1567 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1568 !DCI.isBeforeLegalizeOps());
1569 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1570 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1571 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1572 DCI.CommitTargetLoweringOpt(TLO);
1578 case ISD::UINT_TO_FP: {
1579 return performUCharToFloatCombine(N, DCI);
1582 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1585 EVT VT = N->getValueType(0);
1589 SDValue LHS = N->getOperand(0);
1590 SDValue RHS = N->getOperand(1);
1592 // These should really be instruction patterns, but writing patterns with
1593 // source modiifiers is a pain.
1595 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1596 if (LHS.getOpcode() == ISD::FADD) {
1597 SDValue A = LHS.getOperand(0);
1598 if (A == LHS.getOperand(1)) {
1599 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1600 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1604 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1605 if (RHS.getOpcode() == ISD::FADD) {
1606 SDValue A = RHS.getOperand(0);
1607 if (A == RHS.getOperand(1)) {
1608 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1609 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1616 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1619 EVT VT = N->getValueType(0);
1621 // Try to get the fneg to fold into the source modifier. This undoes generic
1622 // DAG combines and folds them into the mad.
1623 if (VT == MVT::f32) {
1624 SDValue LHS = N->getOperand(0);
1625 SDValue RHS = N->getOperand(1);
1627 if (LHS.getOpcode() == ISD::FMUL) {
1628 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1630 SDValue A = LHS.getOperand(0);
1631 SDValue B = LHS.getOperand(1);
1632 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1634 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1637 if (RHS.getOpcode() == ISD::FMUL) {
1638 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1640 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1641 SDValue B = RHS.getOperand(1);
1644 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1647 if (LHS.getOpcode() == ISD::FADD) {
1648 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1650 SDValue A = LHS.getOperand(0);
1651 if (A == LHS.getOperand(1)) {
1652 const SDValue Two = DAG.getConstantFP(2.0, MVT::f32);
1653 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1655 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1659 if (RHS.getOpcode() == ISD::FADD) {
1660 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1662 SDValue A = RHS.getOperand(0);
1663 if (A == RHS.getOperand(1)) {
1664 const SDValue NegTwo = DAG.getConstantFP(-2.0, MVT::f32);
1665 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1675 case ISD::ATOMIC_LOAD:
1676 case ISD::ATOMIC_STORE:
1677 case ISD::ATOMIC_CMP_SWAP:
1678 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1679 case ISD::ATOMIC_SWAP:
1680 case ISD::ATOMIC_LOAD_ADD:
1681 case ISD::ATOMIC_LOAD_SUB:
1682 case ISD::ATOMIC_LOAD_AND:
1683 case ISD::ATOMIC_LOAD_OR:
1684 case ISD::ATOMIC_LOAD_XOR:
1685 case ISD::ATOMIC_LOAD_NAND:
1686 case ISD::ATOMIC_LOAD_MIN:
1687 case ISD::ATOMIC_LOAD_MAX:
1688 case ISD::ATOMIC_LOAD_UMIN:
1689 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1690 if (DCI.isBeforeLegalize())
1693 MemSDNode *MemNode = cast<MemSDNode>(N);
1694 SDValue Ptr = MemNode->getBasePtr();
1696 // TODO: We could also do this for multiplies.
1697 unsigned AS = MemNode->getAddressSpace();
1698 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1699 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1701 SmallVector<SDValue, 8> NewOps;
1702 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1703 NewOps.push_back(MemNode->getOperand(I));
1705 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1706 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1712 return performAndCombine(N, DCI);
1714 return performOrCombine(N, DCI);
1715 case AMDGPUISD::FP_CLASS:
1716 return performClassCombine(N, DCI);
1718 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1721 /// \brief Test if RegClass is one of the VSrc classes
1722 static bool isVSrc(unsigned RegClass) {
1724 default: return false;
1725 case AMDGPU::VS_32RegClassID:
1726 case AMDGPU::VS_64RegClassID:
1731 /// \brief Analyze the possible immediate value Op
1733 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1734 /// and the immediate value if it's a literal immediate
1735 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1737 const SIInstrInfo *TII =
1738 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1740 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1741 if (Node->getZExtValue() >> 32)
1744 if (TII->isInlineConstant(Node->getAPIntValue()))
1747 return Node->getZExtValue();
1750 if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1751 if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1754 if (Node->getValueType(0) == MVT::f32)
1755 return FloatToBits(Node->getValueAPF().convertToFloat());
1763 const TargetRegisterClass *
1764 SITargetLowering::getRegClassForNode(SelectionDAG &DAG,
1765 const SDValue &Op) const {
1766 const SIInstrInfo *TII =
1767 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1768 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1770 if (!Op->isMachineOpcode()) {
1771 switch(Op->getOpcode()) {
1772 case ISD::CopyFromReg: {
1773 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1774 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1775 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1776 return MRI.getRegClass(Reg);
1778 return TRI.getPhysRegClass(Reg);
1780 default: return nullptr;
1783 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1784 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1785 if (OpClassID != -1) {
1786 return TRI.getRegClass(OpClassID);
1788 switch(Op.getMachineOpcode()) {
1789 case AMDGPU::COPY_TO_REGCLASS:
1790 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1791 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1793 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1794 // class, then the register class for the value could be either a
1795 // VReg or and SReg. In order to get a more accurate
1796 if (isVSrc(OpClassID))
1797 return getRegClassForNode(DAG, Op.getOperand(0));
1799 return TRI.getRegClass(OpClassID);
1800 case AMDGPU::EXTRACT_SUBREG: {
1801 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1802 const TargetRegisterClass *SuperClass =
1803 getRegClassForNode(DAG, Op.getOperand(0));
1804 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1806 case AMDGPU::REG_SEQUENCE:
1807 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1808 return TRI.getRegClass(
1809 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1811 return getRegClassFor(Op.getSimpleValueType());
1815 /// \brief Does "Op" fit into register class "RegClass" ?
1816 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1817 unsigned RegClass) const {
1818 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
1819 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1823 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1826 /// \brief Helper function for adjustWritemask
1827 static unsigned SubIdx2Lane(unsigned Idx) {
1830 case AMDGPU::sub0: return 0;
1831 case AMDGPU::sub1: return 1;
1832 case AMDGPU::sub2: return 2;
1833 case AMDGPU::sub3: return 3;
1837 /// \brief Adjust the writemask of MIMG instructions
1838 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1839 SelectionDAG &DAG) const {
1840 SDNode *Users[4] = { };
1842 unsigned OldDmask = Node->getConstantOperandVal(0);
1843 unsigned NewDmask = 0;
1845 // Try to figure out the used register components
1846 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1849 // Abort if we can't understand the usage
1850 if (!I->isMachineOpcode() ||
1851 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1854 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1855 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1856 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1858 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1860 // Set which texture component corresponds to the lane.
1862 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1864 Comp = countTrailingZeros(Dmask);
1865 Dmask &= ~(1 << Comp);
1868 // Abort if we have more than one user per component
1873 NewDmask |= 1 << Comp;
1876 // Abort if there's no change
1877 if (NewDmask == OldDmask)
1880 // Adjust the writemask in the node
1881 std::vector<SDValue> Ops;
1882 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1883 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1884 Ops.push_back(Node->getOperand(i));
1885 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1887 // If we only got one lane, replace it with a copy
1888 // (if NewDmask has only one bit set...)
1889 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1890 SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, MVT::i32);
1891 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1892 SDLoc(), Users[Lane]->getValueType(0),
1893 SDValue(Node, 0), RC);
1894 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1898 // Update the users of the node with the new indices
1899 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1901 SDNode *User = Users[i];
1905 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1906 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1910 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1911 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1912 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1917 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1918 /// with frame index operands.
1919 /// LLVM assumes that inputs are to these instructions are registers.
1920 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1921 SelectionDAG &DAG) const {
1923 SmallVector<SDValue, 8> Ops;
1924 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1925 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1926 Ops.push_back(Node->getOperand(i));
1931 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1932 Node->getOperand(i).getValueType(),
1933 Node->getOperand(i)), 0));
1936 DAG.UpdateNodeOperands(Node, Ops);
1939 /// \brief Fold the instructions after selecting them.
1940 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1941 SelectionDAG &DAG) const {
1942 const SIInstrInfo *TII =
1943 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1944 Node = AdjustRegClass(Node, DAG);
1946 if (TII->isMIMG(Node->getMachineOpcode()))
1947 adjustWritemask(Node, DAG);
1949 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1950 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1951 legalizeTargetIndependentNode(Node, DAG);
1957 /// \brief Assign the register class depending on the number of
1958 /// bits set in the writemask
1959 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1960 SDNode *Node) const {
1961 const SIInstrInfo *TII =
1962 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1964 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1965 TII->legalizeOperands(MI);
1967 if (TII->isMIMG(MI->getOpcode())) {
1968 unsigned VReg = MI->getOperand(0).getReg();
1969 unsigned Writemask = MI->getOperand(1).getImm();
1970 unsigned BitsSet = 0;
1971 for (unsigned i = 0; i < 4; ++i)
1972 BitsSet += Writemask & (1 << i) ? 1 : 0;
1974 const TargetRegisterClass *RC;
1977 case 1: RC = &AMDGPU::VGPR_32RegClass; break;
1978 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1979 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1982 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1983 MI->setDesc(TII->get(NewOpcode));
1984 MRI.setRegClass(VReg, RC);
1988 // Replace unused atomics with the no return version.
1989 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1990 if (NoRetAtomicOp != -1) {
1991 if (!Node->hasAnyUseOfValue(0)) {
1992 MI->setDesc(TII->get(NoRetAtomicOp));
1993 MI->RemoveOperand(0);
2000 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2001 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
2002 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2005 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2007 SDValue Ptr) const {
2008 const SIInstrInfo *TII =
2009 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2011 // XXX - Workaround for moveToVALU not handling different register class
2012 // inserts for REG_SEQUENCE.
2014 // Build the half of the subregister with the constants.
2015 const SDValue Ops0[] = {
2016 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
2017 buildSMovImm32(DAG, DL, 0),
2018 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2019 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2020 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
2023 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2024 MVT::v2i32, Ops0), 0);
2026 // Combine the constants and the pointer.
2027 const SDValue Ops1[] = {
2028 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2030 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2032 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2035 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2037 const SDValue Ops[] = {
2038 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2040 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2041 buildSMovImm32(DAG, DL, 0),
2042 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2043 buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2044 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2047 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2052 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2053 /// The TID (Thread ID) is multipled by the stride value (bits [61:48]
2054 /// of the resource descriptor) to create an offset, which is added to the
2055 /// resource ponter.
2056 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2059 uint32_t RsrcDword1,
2060 uint64_t RsrcDword2And3) const {
2061 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2062 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2064 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2065 DAG.getConstant(RsrcDword1, MVT::i32)), 0);
2068 SDValue DataLo = buildSMovImm32(DAG, DL,
2069 RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2070 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2072 const SDValue Ops[] = {
2073 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2075 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
2077 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32),
2079 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2081 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2084 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2087 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2089 SDValue Ptr) const {
2090 const SIInstrInfo *TII =
2091 static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2092 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2095 return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2098 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2099 SelectionDAG &DAG) const {
2102 unsigned NewOpcode = N->getMachineOpcode();
2104 switch (N->getMachineOpcode()) {
2106 case AMDGPU::S_LOAD_DWORD_IMM:
2107 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2109 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2110 if (NewOpcode == N->getMachineOpcode()) {
2111 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2114 case AMDGPU::S_LOAD_DWORDX4_IMM:
2115 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2116 if (NewOpcode == N->getMachineOpcode()) {
2117 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2119 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2122 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2124 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2125 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2126 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2128 SmallVector<SDValue, 8> Ops;
2129 Ops.push_back(SDValue(RSrc, 0));
2130 Ops.push_back(N->getOperand(0));
2132 // The immediate offset is in dwords on SI and in bytes on VI.
2133 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2134 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue(), MVT::i32));
2136 Ops.push_back(DAG.getTargetConstant(Offset->getSExtValue() << 2, MVT::i32));
2138 // Copy remaining operands so we keep any chain and glue nodes that follow
2139 // the normal operands.
2140 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2141 Ops.push_back(N->getOperand(I));
2143 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2148 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2149 const TargetRegisterClass *RC,
2150 unsigned Reg, EVT VT) const {
2151 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2153 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2154 cast<RegisterSDNode>(VReg)->getReg(), VT);