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::VReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
65 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
66 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
67 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
68 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
69 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
70 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
72 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
73 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
74 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
75 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
76 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
77 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
79 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
80 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
81 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
82 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
84 setOperationAction(ISD::ADD, MVT::i32, Legal);
85 setOperationAction(ISD::ADDC, MVT::i32, Legal);
86 setOperationAction(ISD::ADDE, MVT::i32, Legal);
87 setOperationAction(ISD::SUBC, MVT::i32, Legal);
88 setOperationAction(ISD::SUBE, MVT::i32, Legal);
90 setOperationAction(ISD::FSIN, MVT::f32, Custom);
91 setOperationAction(ISD::FCOS, MVT::f32, Custom);
93 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
94 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
95 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
96 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
98 // We need to custom lower vector stores from local memory
99 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
100 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
101 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
104 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
106 setOperationAction(ISD::STORE, MVT::i1, Custom);
107 setOperationAction(ISD::STORE, MVT::i32, Custom);
108 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
109 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
111 setOperationAction(ISD::SELECT, MVT::f32, Promote);
112 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
113 setOperationAction(ISD::SELECT, MVT::i64, Custom);
114 setOperationAction(ISD::SELECT, MVT::f64, Promote);
115 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
117 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
118 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
119 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
120 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
122 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
123 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
125 setOperationAction(ISD::BSWAP, MVT::i32, Legal);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
135 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
136 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
137 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
139 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
141 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
143 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
144 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
145 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
146 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
148 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
149 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
151 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
152 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
153 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
154 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
155 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
156 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
158 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
159 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
160 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
161 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
163 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
164 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
165 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
166 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
167 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
169 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
170 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
171 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
172 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
173 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
174 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
176 setOperationAction(ISD::LOAD, MVT::i1, Custom);
178 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
179 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
180 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
182 // These should use UDIVREM, so set them to expand
183 setOperationAction(ISD::UDIV, MVT::i64, Expand);
184 setOperationAction(ISD::UREM, MVT::i64, Expand);
186 // We only support LOAD/STORE and vector manipulation ops for vectors
187 // with > 4 elements.
189 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
192 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
193 setOperationAction(ISD::SELECT, MVT::i1, Promote);
195 for (MVT VT : VecTypes) {
196 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
200 case ISD::BUILD_VECTOR:
202 case ISD::EXTRACT_VECTOR_ELT:
203 case ISD::INSERT_VECTOR_ELT:
204 case ISD::INSERT_SUBVECTOR:
205 case ISD::EXTRACT_SUBVECTOR:
207 case ISD::CONCAT_VECTORS:
208 setOperationAction(Op, VT, Custom);
211 setOperationAction(Op, VT, Expand);
217 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
218 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
219 setOperationAction(ISD::FTRUNC, VT, Expand);
220 setOperationAction(ISD::FCEIL, VT, Expand);
221 setOperationAction(ISD::FFLOOR, VT, Expand);
224 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
225 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
226 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
227 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
228 setOperationAction(ISD::FRINT, MVT::f64, Legal);
231 setOperationAction(ISD::FDIV, MVT::f32, Custom);
233 setTargetDAGCombine(ISD::FADD);
234 setTargetDAGCombine(ISD::FSUB);
235 setTargetDAGCombine(ISD::SELECT_CC);
236 setTargetDAGCombine(ISD::SETCC);
238 setTargetDAGCombine(ISD::UINT_TO_FP);
240 // All memory operations. Some folding on the pointer operand is done to help
241 // matching the constant offsets in the addressing modes.
242 setTargetDAGCombine(ISD::LOAD);
243 setTargetDAGCombine(ISD::STORE);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD);
245 setTargetDAGCombine(ISD::ATOMIC_STORE);
246 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
247 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
248 setTargetDAGCombine(ISD::ATOMIC_SWAP);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
255 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
256 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
257 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
258 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
260 setSchedulingPreference(Sched::RegPressure);
263 //===----------------------------------------------------------------------===//
264 // TargetLowering queries
265 //===----------------------------------------------------------------------===//
267 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
269 // SI has some legal vector types, but no legal vector operations. Say no
270 // shuffles are legal in order to prefer scalarizing some vector operations.
274 // FIXME: This really needs an address space argument. The immediate offset
275 // size is different for different sets of memory instruction sets.
277 // The single offset DS instructions have a 16-bit unsigned byte offset.
279 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
280 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
281 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
283 // SMRD instructions have an 8-bit, dword offset.
285 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
287 // No global is ever allowed as a base.
291 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
293 if (!isUInt<16>(AM.BaseOffs))
298 case 0: // "r+i" or just "i", depending on HasBaseReg.
301 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
303 // Otherwise we have r+r or r+i.
306 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
310 default: // Don't allow n * r
317 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
320 bool *IsFast) const {
324 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
325 // which isn't a simple VT.
326 if (!VT.isSimple() || VT == MVT::Other)
329 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
330 // see what for specifically. The wording everywhere else seems to be the
333 // XXX - The only mention I see of this in the ISA manual is for LDS direct
334 // reads the "byte address and must be dword aligned". Is it also true for the
335 // normal loads and stores?
336 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
337 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
338 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
339 // with adjacent offsets.
340 return Align % 4 == 0;
343 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
344 // byte-address are ignored, thus forcing Dword alignment.
345 // This applies to private, global, and constant memory.
348 return VT.bitsGT(MVT::i32);
351 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
352 unsigned SrcAlign, bool IsMemset,
355 MachineFunction &MF) const {
356 // FIXME: Should account for address space here.
358 // The default fallback uses the private pointer size as a guess for a type to
359 // use. Make sure we switch these to 64-bit accesses.
361 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
364 if (Size >= 8 && DstAlign >= 4)
371 TargetLoweringBase::LegalizeTypeAction
372 SITargetLowering::getPreferredVectorAction(EVT VT) const {
373 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
374 return TypeSplitVector;
376 return TargetLoweringBase::getPreferredVectorAction(VT);
379 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
381 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
382 getTargetMachine().getSubtargetImpl()->getInstrInfo());
383 return TII->isInlineConstant(Imm);
386 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
387 SDLoc SL, SDValue Chain,
388 unsigned Offset, bool Signed) const {
389 const DataLayout *DL = getDataLayout();
390 MachineFunction &MF = DAG.getMachineFunction();
391 const SIRegisterInfo *TRI =
392 static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
393 unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
395 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
397 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
398 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
399 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
400 MRI.getLiveInVirtReg(InputPtrReg), MVT::i64);
401 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
402 DAG.getConstant(Offset, MVT::i64));
403 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
404 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
406 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
407 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
409 true, // isNonTemporal
411 DL->getABITypeAlignment(Ty)); // Alignment
414 SDValue SITargetLowering::LowerFormalArguments(
416 CallingConv::ID CallConv,
418 const SmallVectorImpl<ISD::InputArg> &Ins,
419 SDLoc DL, SelectionDAG &DAG,
420 SmallVectorImpl<SDValue> &InVals) const {
422 const TargetMachine &TM = getTargetMachine();
423 const SIRegisterInfo *TRI =
424 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
426 MachineFunction &MF = DAG.getMachineFunction();
427 FunctionType *FType = MF.getFunction()->getFunctionType();
428 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
430 assert(CallConv == CallingConv::C);
432 SmallVector<ISD::InputArg, 16> Splits;
433 BitVector Skipped(Ins.size());
435 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
436 const ISD::InputArg &Arg = Ins[i];
438 // First check if it's a PS input addr
439 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
440 !Arg.Flags.isByVal()) {
442 assert((PSInputNum <= 15) && "Too many PS inputs!");
445 // We can savely skip PS inputs
451 Info->PSInputAddr |= 1 << PSInputNum++;
454 // Second split vertices into their elements
455 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
456 ISD::InputArg NewArg = Arg;
457 NewArg.Flags.setSplit();
458 NewArg.VT = Arg.VT.getVectorElementType();
460 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
461 // three or five element vertex only needs three or five registers,
462 // NOT four or eigth.
463 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
464 unsigned NumElements = ParamType->getVectorNumElements();
466 for (unsigned j = 0; j != NumElements; ++j) {
467 Splits.push_back(NewArg);
468 NewArg.PartOffset += NewArg.VT.getStoreSize();
471 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
472 Splits.push_back(Arg);
476 SmallVector<CCValAssign, 16> ArgLocs;
477 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
480 // At least one interpolation mode must be enabled or else the GPU will hang.
481 if (Info->getShaderType() == ShaderType::PIXEL &&
482 (Info->PSInputAddr & 0x7F) == 0) {
483 Info->PSInputAddr |= 1;
484 CCInfo.AllocateReg(AMDGPU::VGPR0);
485 CCInfo.AllocateReg(AMDGPU::VGPR1);
488 // The pointer to the list of arguments is stored in SGPR0, SGPR1
489 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
490 if (Info->getShaderType() == ShaderType::COMPUTE) {
491 Info->NumUserSGPRs = 4;
493 unsigned InputPtrReg =
494 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
495 unsigned InputPtrRegLo =
496 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
497 unsigned InputPtrRegHi =
498 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
500 unsigned ScratchPtrReg =
501 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
502 unsigned ScratchPtrRegLo =
503 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
504 unsigned ScratchPtrRegHi =
505 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
507 CCInfo.AllocateReg(InputPtrRegLo);
508 CCInfo.AllocateReg(InputPtrRegHi);
509 CCInfo.AllocateReg(ScratchPtrRegLo);
510 CCInfo.AllocateReg(ScratchPtrRegHi);
511 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
512 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
515 if (Info->getShaderType() == ShaderType::COMPUTE) {
516 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
520 AnalyzeFormalArguments(CCInfo, Splits);
522 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
524 const ISD::InputArg &Arg = Ins[i];
526 InVals.push_back(DAG.getUNDEF(Arg.VT));
530 CCValAssign &VA = ArgLocs[ArgIdx++];
531 EVT VT = VA.getLocVT();
535 EVT MemVT = Splits[i].VT;
536 const unsigned Offset = 36 + VA.getLocMemOffset();
537 // The first 36 bytes of the input buffer contains information about
538 // thread group and global sizes.
539 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
540 Offset, Ins[i].Flags.isSExt());
542 const PointerType *ParamTy =
543 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
544 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
545 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
546 // On SI local pointers are just offsets into LDS, so they are always
547 // less than 16-bits. On CI and newer they could potentially be
548 // real pointers, so we can't guarantee their size.
549 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
550 DAG.getValueType(MVT::i16));
553 InVals.push_back(Arg);
554 Info->ABIArgOffset = Offset + MemVT.getStoreSize();
557 assert(VA.isRegLoc() && "Parameter must be in a register!");
559 unsigned Reg = VA.getLocReg();
561 if (VT == MVT::i64) {
562 // For now assume it is a pointer
563 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
564 &AMDGPU::SReg_64RegClass);
565 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
566 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
570 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
572 Reg = MF.addLiveIn(Reg, RC);
573 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
575 if (Arg.VT.isVector()) {
577 // Build a vector from the registers
578 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
579 unsigned NumElements = ParamType->getVectorNumElements();
581 SmallVector<SDValue, 4> Regs;
583 for (unsigned j = 1; j != NumElements; ++j) {
584 Reg = ArgLocs[ArgIdx++].getLocReg();
585 Reg = MF.addLiveIn(Reg, RC);
586 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
589 // Fill up the missing vector elements
590 NumElements = Arg.VT.getVectorNumElements() - NumElements;
591 for (unsigned j = 0; j != NumElements; ++j)
592 Regs.push_back(DAG.getUNDEF(VT));
594 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
598 InVals.push_back(Val);
603 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
604 MachineInstr * MI, MachineBasicBlock * BB) const {
606 MachineBasicBlock::iterator I = *MI;
607 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
608 getTargetMachine().getSubtargetImpl()->getInstrInfo());
610 switch (MI->getOpcode()) {
612 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
613 case AMDGPU::BRANCH: return BB;
614 case AMDGPU::V_SUB_F64: {
615 unsigned DestReg = MI->getOperand(0).getReg();
616 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
617 .addImm(0) // SRC0 modifiers
618 .addReg(MI->getOperand(1).getReg())
619 .addImm(1) // SRC1 modifiers
620 .addReg(MI->getOperand(2).getReg())
623 MI->eraseFromParent();
626 case AMDGPU::SI_RegisterStorePseudo: {
627 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
628 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
629 MachineInstrBuilder MIB =
630 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
632 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
633 MIB.addOperand(MI->getOperand(i));
635 MI->eraseFromParent();
638 case AMDGPU::FCLAMP_SI: {
639 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
640 getTargetMachine().getSubtargetImpl()->getInstrInfo());
641 DebugLoc DL = MI->getDebugLoc();
642 unsigned DestReg = MI->getOperand(0).getReg();
643 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
644 .addImm(0) // SRC0 modifiers
645 .addOperand(MI->getOperand(1))
646 .addImm(0) // SRC1 modifiers
650 MI->eraseFromParent();
656 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
657 if (!VT.isVector()) {
660 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
663 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
667 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
668 VT = VT.getScalarType();
673 switch (VT.getSimpleVT().SimpleTy) {
675 return false; /* There is V_MAD_F32 for f32 */
685 //===----------------------------------------------------------------------===//
686 // Custom DAG Lowering Operations
687 //===----------------------------------------------------------------------===//
689 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
690 switch (Op.getOpcode()) {
691 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
692 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
693 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
695 SDValue Result = LowerLOAD(Op, DAG);
696 assert((!Result.getNode() ||
697 Result.getNode()->getNumValues() == 2) &&
698 "Load should return a value and a chain");
704 return LowerTrig(Op, DAG);
705 case ISD::SELECT: return LowerSELECT(Op, DAG);
706 case ISD::FDIV: return LowerFDIV(Op, DAG);
707 case ISD::STORE: return LowerSTORE(Op, DAG);
708 case ISD::GlobalAddress: {
709 MachineFunction &MF = DAG.getMachineFunction();
710 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
711 return LowerGlobalAddress(MFI, Op, DAG);
713 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
714 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
719 /// \brief Helper function for LowerBRCOND
720 static SDNode *findUser(SDValue Value, unsigned Opcode) {
722 SDNode *Parent = Value.getNode();
723 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
726 if (I.getUse().get() != Value)
729 if (I->getOpcode() == Opcode)
735 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
737 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
738 unsigned FrameIndex = FINode->getIndex();
740 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
743 /// This transforms the control flow intrinsics to get the branch destination as
744 /// last parameter, also switches branch target with BR if the need arise
745 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
746 SelectionDAG &DAG) const {
750 SDNode *Intr = BRCOND.getOperand(1).getNode();
751 SDValue Target = BRCOND.getOperand(2);
752 SDNode *BR = nullptr;
754 if (Intr->getOpcode() == ISD::SETCC) {
755 // As long as we negate the condition everything is fine
756 SDNode *SetCC = Intr;
757 assert(SetCC->getConstantOperandVal(1) == 1);
758 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
760 Intr = SetCC->getOperand(0).getNode();
763 // Get the target from BR if we don't negate the condition
764 BR = findUser(BRCOND, ISD::BR);
765 Target = BR->getOperand(1);
768 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
770 // Build the result and
771 SmallVector<EVT, 4> Res;
772 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
773 Res.push_back(Intr->getValueType(i));
775 // operands of the new intrinsic call
776 SmallVector<SDValue, 4> Ops;
777 Ops.push_back(BRCOND.getOperand(0));
778 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
779 Ops.push_back(Intr->getOperand(i));
780 Ops.push_back(Target);
782 // build the new intrinsic call
783 SDNode *Result = DAG.getNode(
784 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
785 DAG.getVTList(Res), Ops).getNode();
788 // Give the branch instruction our target
793 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
794 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
795 BR = NewBR.getNode();
798 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
800 // Copy the intrinsic results to registers
801 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
802 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
806 Chain = DAG.getCopyToReg(
808 CopyToReg->getOperand(1),
809 SDValue(Result, i - 1),
812 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
815 // Remove the old intrinsic from the chain
816 DAG.ReplaceAllUsesOfValueWith(
817 SDValue(Intr, Intr->getNumValues() - 1),
818 Intr->getOperand(0));
823 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
825 SelectionDAG &DAG) const {
826 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
828 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
829 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
832 const GlobalValue *GV = GSD->getGlobal();
833 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
835 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
836 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
838 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
839 DAG.getConstant(0, MVT::i32));
840 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
841 DAG.getConstant(1, MVT::i32));
843 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
845 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
846 PtrHi, DAG.getConstant(0, MVT::i32),
847 SDValue(Lo.getNode(), 1));
848 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
851 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
852 SelectionDAG &DAG) const {
853 MachineFunction &MF = DAG.getMachineFunction();
854 const SIRegisterInfo *TRI =
855 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
857 EVT VT = Op.getValueType();
859 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
861 switch (IntrinsicID) {
862 case Intrinsic::r600_read_ngroups_x:
863 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
864 SI::KernelInputOffsets::NGROUPS_X, false);
865 case Intrinsic::r600_read_ngroups_y:
866 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
867 SI::KernelInputOffsets::NGROUPS_Y, false);
868 case Intrinsic::r600_read_ngroups_z:
869 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
870 SI::KernelInputOffsets::NGROUPS_Z, false);
871 case Intrinsic::r600_read_global_size_x:
872 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
873 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
874 case Intrinsic::r600_read_global_size_y:
875 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
876 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
877 case Intrinsic::r600_read_global_size_z:
878 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
879 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
880 case Intrinsic::r600_read_local_size_x:
881 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
882 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
883 case Intrinsic::r600_read_local_size_y:
884 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
885 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
886 case Intrinsic::r600_read_local_size_z:
887 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
888 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
890 case Intrinsic::AMDGPU_read_workdim:
891 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
892 MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
895 case Intrinsic::r600_read_tgid_x:
896 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
897 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
898 case Intrinsic::r600_read_tgid_y:
899 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
900 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
901 case Intrinsic::r600_read_tgid_z:
902 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
903 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
904 case Intrinsic::r600_read_tidig_x:
905 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
906 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
907 case Intrinsic::r600_read_tidig_y:
908 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
909 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
910 case Intrinsic::r600_read_tidig_z:
911 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
912 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
913 case AMDGPUIntrinsic::SI_load_const: {
919 MachineMemOperand *MMO = MF.getMachineMemOperand(
920 MachinePointerInfo(),
921 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
922 VT.getStoreSize(), 4);
923 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
924 Op->getVTList(), Ops, VT, MMO);
926 case AMDGPUIntrinsic::SI_sample:
927 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
928 case AMDGPUIntrinsic::SI_sampleb:
929 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
930 case AMDGPUIntrinsic::SI_sampled:
931 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
932 case AMDGPUIntrinsic::SI_samplel:
933 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
934 case AMDGPUIntrinsic::SI_vs_load_input:
935 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
940 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
944 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
945 SelectionDAG &DAG) const {
946 MachineFunction &MF = DAG.getMachineFunction();
947 SDValue Chain = Op.getOperand(0);
948 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
950 switch (IntrinsicID) {
951 case AMDGPUIntrinsic::SI_tbuffer_store: {
970 EVT VT = Op.getOperand(3).getValueType();
972 MachineMemOperand *MMO = MF.getMachineMemOperand(
973 MachinePointerInfo(),
974 MachineMemOperand::MOStore,
975 VT.getStoreSize(), 4);
976 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
977 Op->getVTList(), Ops, VT, MMO);
984 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
986 LoadSDNode *Load = cast<LoadSDNode>(Op);
988 if (Op.getValueType().isVector()) {
989 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
990 "Custom lowering for non-i32 vectors hasn't been implemented.");
991 unsigned NumElements = Op.getValueType().getVectorNumElements();
992 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
993 switch (Load->getAddressSpace()) {
995 case AMDGPUAS::GLOBAL_ADDRESS:
996 case AMDGPUAS::PRIVATE_ADDRESS:
997 // v4 loads are supported for private and global memory.
998 if (NumElements <= 4)
1001 case AMDGPUAS::LOCAL_ADDRESS:
1002 return ScalarizeVectorLoad(Op, DAG);
1006 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1009 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1011 SelectionDAG &DAG) const {
1012 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1018 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1019 if (Op.getValueType() != MVT::i64)
1023 SDValue Cond = Op.getOperand(0);
1025 SDValue Zero = DAG.getConstant(0, MVT::i32);
1026 SDValue One = DAG.getConstant(1, MVT::i32);
1028 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1029 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1031 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1032 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1034 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1036 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1037 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1039 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1041 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1042 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1045 // Catch division cases where we can use shortcuts with rcp and rsq
1047 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1049 SDValue LHS = Op.getOperand(0);
1050 SDValue RHS = Op.getOperand(1);
1051 EVT VT = Op.getValueType();
1052 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1054 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1055 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1056 CLHS->isExactlyValue(1.0)) {
1057 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1058 // the CI documentation has a worst case error of 1 ulp.
1059 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1060 // use it as long as we aren't trying to use denormals.
1062 // 1.0 / sqrt(x) -> rsq(x)
1064 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1065 // error seems really high at 2^29 ULP.
1066 if (RHS.getOpcode() == ISD::FSQRT)
1067 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1069 // 1.0 / x -> rcp(x)
1070 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1075 // Turn into multiply by the reciprocal.
1076 // x / y -> x * (1.0 / y)
1077 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1078 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1084 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1085 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1086 if (FastLowered.getNode())
1089 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1090 // selection error for now rather than do something incorrect.
1091 if (Subtarget->hasFP32Denormals())
1095 SDValue LHS = Op.getOperand(0);
1096 SDValue RHS = Op.getOperand(1);
1098 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1100 const APFloat K0Val(BitsToFloat(0x6f800000));
1101 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1103 const APFloat K1Val(BitsToFloat(0x2f800000));
1104 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1106 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1108 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1110 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1112 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1114 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1116 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1118 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1120 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1123 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1127 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1128 EVT VT = Op.getValueType();
1131 return LowerFDIV32(Op, DAG);
1134 return LowerFDIV64(Op, DAG);
1136 llvm_unreachable("Unexpected type for fdiv");
1139 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1141 StoreSDNode *Store = cast<StoreSDNode>(Op);
1142 EVT VT = Store->getMemoryVT();
1144 // These stores are legal.
1145 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1146 VT.isVector() && VT.getVectorNumElements() == 2 &&
1147 VT.getVectorElementType() == MVT::i32)
1150 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1151 if (VT.isVector() && VT.getVectorNumElements() > 4)
1152 return ScalarizeVectorStore(Op, DAG);
1156 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1160 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1161 return ScalarizeVectorStore(Op, DAG);
1164 return DAG.getTruncStore(Store->getChain(), DL,
1165 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1166 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1171 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1172 EVT VT = Op.getValueType();
1173 SDValue Arg = Op.getOperand(0);
1174 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1175 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1176 DAG.getConstantFP(0.5 / M_PI, VT)));
1178 switch (Op.getOpcode()) {
1180 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1182 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1184 llvm_unreachable("Wrong trig opcode");
1188 //===----------------------------------------------------------------------===//
1189 // Custom DAG optimizations
1190 //===----------------------------------------------------------------------===//
1192 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1193 DAGCombinerInfo &DCI) {
1194 EVT VT = N->getValueType(0);
1195 EVT ScalarVT = VT.getScalarType();
1196 if (ScalarVT != MVT::f32)
1199 SelectionDAG &DAG = DCI.DAG;
1202 SDValue Src = N->getOperand(0);
1203 EVT SrcVT = Src.getValueType();
1205 // TODO: We could try to match extracting the higher bytes, which would be
1206 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1207 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1208 // about in practice.
1209 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1210 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1211 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1212 DCI.AddToWorklist(Cvt.getNode());
1217 // We are primarily trying to catch operations on illegal vector types
1218 // before they are expanded.
1219 // For scalars, we can use the more flexible method of checking masked bits
1220 // after legalization.
1221 if (!DCI.isBeforeLegalize() ||
1222 !SrcVT.isVector() ||
1223 SrcVT.getVectorElementType() != MVT::i8) {
1227 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1229 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1231 unsigned NElts = SrcVT.getVectorNumElements();
1232 if (!SrcVT.isSimple() && NElts != 3)
1235 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1236 // prevent a mess from expanding to v4i32 and repacking.
1237 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1238 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1239 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1240 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1242 LoadSDNode *Load = cast<LoadSDNode>(Src);
1243 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1247 Load->getMemOperand());
1249 // Make sure successors of the original load stay after it by updating
1250 // them to use the new Chain.
1251 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1253 SmallVector<SDValue, 4> Elts;
1254 if (RegVT.isVector())
1255 DAG.ExtractVectorElements(NewLoad, Elts);
1257 Elts.push_back(NewLoad);
1259 SmallVector<SDValue, 4> Ops;
1261 unsigned EltIdx = 0;
1262 for (SDValue Elt : Elts) {
1263 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1264 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1265 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1266 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1267 DCI.AddToWorklist(Cvt.getNode());
1274 assert(Ops.size() == NElts);
1276 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1282 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1284 // This is a variant of
1285 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1287 // The normal DAG combiner will do this, but only if the add has one use since
1288 // that would increase the number of instructions.
1290 // This prevents us from seeing a constant offset that can be folded into a
1291 // memory instruction's addressing mode. If we know the resulting add offset of
1292 // a pointer can be folded into an addressing offset, we can replace the pointer
1293 // operand with the add of new constant offset. This eliminates one of the uses,
1294 // and may allow the remaining use to also be simplified.
1296 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1298 DAGCombinerInfo &DCI) const {
1299 SDValue N0 = N->getOperand(0);
1300 SDValue N1 = N->getOperand(1);
1302 if (N0.getOpcode() != ISD::ADD)
1305 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1309 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1313 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1314 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1316 // If the resulting offset is too large, we can't fold it into the addressing
1318 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1319 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1322 SelectionDAG &DAG = DCI.DAG;
1324 EVT VT = N->getValueType(0);
1326 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1327 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1329 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1332 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1333 DAGCombinerInfo &DCI) const {
1334 SelectionDAG &DAG = DCI.DAG;
1336 EVT VT = N->getValueType(0);
1338 switch (N->getOpcode()) {
1339 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1341 SDValue Arg0 = N->getOperand(0);
1342 SDValue Arg1 = N->getOperand(1);
1343 SDValue CC = N->getOperand(2);
1344 ConstantSDNode * C = nullptr;
1345 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1347 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1349 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1350 && Arg0.getOperand(0).getValueType() == MVT::i1
1351 && (C = dyn_cast<ConstantSDNode>(Arg1))
1353 && CCOp == ISD::SETNE) {
1354 return SimplifySetCC(VT, Arg0.getOperand(0),
1355 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1360 case AMDGPUISD::CVT_F32_UBYTE0:
1361 case AMDGPUISD::CVT_F32_UBYTE1:
1362 case AMDGPUISD::CVT_F32_UBYTE2:
1363 case AMDGPUISD::CVT_F32_UBYTE3: {
1364 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1366 SDValue Src = N->getOperand(0);
1367 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1369 APInt KnownZero, KnownOne;
1370 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1371 !DCI.isBeforeLegalizeOps());
1372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1373 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1374 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1375 DCI.CommitTargetLoweringOpt(TLO);
1381 case ISD::UINT_TO_FP: {
1382 return performUCharToFloatCombine(N, DCI);
1385 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1388 EVT VT = N->getValueType(0);
1392 SDValue LHS = N->getOperand(0);
1393 SDValue RHS = N->getOperand(1);
1395 // These should really be instruction patterns, but writing patterns with
1396 // source modiifiers is a pain.
1398 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1399 if (LHS.getOpcode() == ISD::FADD) {
1400 SDValue A = LHS.getOperand(0);
1401 if (A == LHS.getOperand(1)) {
1402 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1403 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1407 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1408 if (RHS.getOpcode() == ISD::FADD) {
1409 SDValue A = RHS.getOperand(0);
1410 if (A == RHS.getOperand(1)) {
1411 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1412 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1419 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1422 EVT VT = N->getValueType(0);
1424 // Try to get the fneg to fold into the source modifier. This undoes generic
1425 // DAG combines and folds them into the mad.
1426 if (VT == MVT::f32) {
1427 SDValue LHS = N->getOperand(0);
1428 SDValue RHS = N->getOperand(1);
1430 if (LHS.getOpcode() == ISD::FMUL) {
1431 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1433 SDValue A = LHS.getOperand(0);
1434 SDValue B = LHS.getOperand(1);
1435 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1437 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1440 if (RHS.getOpcode() == ISD::FMUL) {
1441 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1443 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1444 SDValue B = RHS.getOperand(1);
1447 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1450 if (LHS.getOpcode() == ISD::FADD) {
1451 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1453 SDValue A = LHS.getOperand(0);
1454 if (A == LHS.getOperand(1)) {
1455 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1456 SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1458 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, NegRHS);
1462 if (RHS.getOpcode() == ISD::FADD) {
1463 // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1465 SDValue A = RHS.getOperand(0);
1466 if (A == RHS.getOperand(1)) {
1467 const SDValue NegTwo = DAG.getTargetConstantFP(-2.0, MVT::f32);
1468 return DAG.getNode(AMDGPUISD::MAD, DL, VT, NegTwo, A, LHS);
1478 case ISD::ATOMIC_LOAD:
1479 case ISD::ATOMIC_STORE:
1480 case ISD::ATOMIC_CMP_SWAP:
1481 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1482 case ISD::ATOMIC_SWAP:
1483 case ISD::ATOMIC_LOAD_ADD:
1484 case ISD::ATOMIC_LOAD_SUB:
1485 case ISD::ATOMIC_LOAD_AND:
1486 case ISD::ATOMIC_LOAD_OR:
1487 case ISD::ATOMIC_LOAD_XOR:
1488 case ISD::ATOMIC_LOAD_NAND:
1489 case ISD::ATOMIC_LOAD_MIN:
1490 case ISD::ATOMIC_LOAD_MAX:
1491 case ISD::ATOMIC_LOAD_UMIN:
1492 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1493 if (DCI.isBeforeLegalize())
1496 MemSDNode *MemNode = cast<MemSDNode>(N);
1497 SDValue Ptr = MemNode->getBasePtr();
1499 // TODO: We could also do this for multiplies.
1500 unsigned AS = MemNode->getAddressSpace();
1501 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1502 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1504 SmallVector<SDValue, 8> NewOps;
1505 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1506 NewOps.push_back(MemNode->getOperand(I));
1508 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1509 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1515 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1518 /// \brief Test if RegClass is one of the VSrc classes
1519 static bool isVSrc(unsigned RegClass) {
1521 default: return false;
1522 case AMDGPU::VSrc_32RegClassID:
1523 case AMDGPU::VCSrc_32RegClassID:
1524 case AMDGPU::VSrc_64RegClassID:
1525 case AMDGPU::VCSrc_64RegClassID:
1530 /// \brief Test if RegClass is one of the SSrc classes
1531 static bool isSSrc(unsigned RegClass) {
1532 return AMDGPU::SSrc_32RegClassID == RegClass ||
1533 AMDGPU::SSrc_64RegClassID == RegClass;
1536 /// \brief Analyze the possible immediate value Op
1538 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1539 /// and the immediate value if it's a literal immediate
1540 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1547 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1548 if (Node->getZExtValue() >> 32) {
1551 Imm.I = Node->getSExtValue();
1552 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1553 if (N->getValueType(0) != MVT::f32)
1555 Imm.F = Node->getValueAPF().convertToFloat();
1557 return -1; // It isn't an immediate
1559 if ((Imm.I >= -16 && Imm.I <= 64) ||
1560 Imm.F == 0.5f || Imm.F == -0.5f ||
1561 Imm.F == 1.0f || Imm.F == -1.0f ||
1562 Imm.F == 2.0f || Imm.F == -2.0f ||
1563 Imm.F == 4.0f || Imm.F == -4.0f)
1564 return 0; // It's an inline immediate
1566 return Imm.I; // It's a literal immediate
1569 /// \brief Try to fold an immediate directly into an instruction
1570 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1571 bool &ScalarSlotUsed) const {
1573 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1574 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1575 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1576 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1579 const SDValue &Op = Mov->getOperand(0);
1580 int32_t Value = analyzeImmediate(Op.getNode());
1582 // Not an immediate at all
1585 } else if (Value == 0) {
1586 // Inline immediates can always be fold
1590 } else if (Value == Immediate) {
1591 // Already fold literal immediate
1595 } else if (!ScalarSlotUsed && !Immediate) {
1596 // Fold this literal immediate
1597 ScalarSlotUsed = true;
1607 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1608 SelectionDAG &DAG, const SDValue &Op) const {
1609 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1610 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1611 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1613 if (!Op->isMachineOpcode()) {
1614 switch(Op->getOpcode()) {
1615 case ISD::CopyFromReg: {
1616 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1617 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1618 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1619 return MRI.getRegClass(Reg);
1621 return TRI.getPhysRegClass(Reg);
1623 default: return nullptr;
1626 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1627 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1628 if (OpClassID != -1) {
1629 return TRI.getRegClass(OpClassID);
1631 switch(Op.getMachineOpcode()) {
1632 case AMDGPU::COPY_TO_REGCLASS:
1633 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1634 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1636 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1637 // class, then the register class for the value could be either a
1638 // VReg or and SReg. In order to get a more accurate
1639 if (isVSrc(OpClassID))
1640 return getRegClassForNode(DAG, Op.getOperand(0));
1642 return TRI.getRegClass(OpClassID);
1643 case AMDGPU::EXTRACT_SUBREG: {
1644 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1645 const TargetRegisterClass *SuperClass =
1646 getRegClassForNode(DAG, Op.getOperand(0));
1647 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1649 case AMDGPU::REG_SEQUENCE:
1650 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1651 return TRI.getRegClass(
1652 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1654 return getRegClassFor(Op.getSimpleValueType());
1658 /// \brief Does "Op" fit into register class "RegClass" ?
1659 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1660 unsigned RegClass) const {
1661 const TargetRegisterInfo *TRI =
1662 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1663 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1667 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1670 /// \returns true if \p Node's operands are different from the SDValue list
1672 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1673 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1674 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1681 /// TODO: This needs to be removed. It's current primary purpose is to fold
1682 /// immediates into operands when legal. The legalization parts are redundant
1683 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1684 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1685 SelectionDAG &DAG) const {
1686 // Original encoding (either e32 or e64)
1687 int Opcode = Node->getMachineOpcode();
1688 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1689 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1690 const MCInstrDesc *Desc = &TII->get(Opcode);
1692 unsigned NumDefs = Desc->getNumDefs();
1693 unsigned NumOps = Desc->getNumOperands();
1695 // Commuted opcode if available
1696 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1697 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1699 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1700 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1702 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1703 bool HaveVSrc = false, HaveSSrc = false;
1705 // First figure out what we already have in this instruction.
1706 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1707 i != e && Op < NumOps; ++i, ++Op) {
1709 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1710 if (isVSrc(RegClass))
1712 else if (isSSrc(RegClass))
1717 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1718 if (Imm != -1 && Imm != 0) {
1719 // Literal immediate
1724 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1725 if (!HaveVSrc && !HaveSSrc)
1728 // No scalar allowed when we have both VSrc and SSrc
1729 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1731 // If this instruction has an implicit use of VCC, then it can't use the
1733 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1734 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1735 ScalarSlotUsed = true;
1740 // Second go over the operands and try to fold them
1741 std::vector<SDValue> Ops;
1742 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1743 i != e && Op < NumOps; ++i, ++Op) {
1745 const SDValue &Operand = Node->getOperand(i);
1746 Ops.push_back(Operand);
1748 // Already folded immediate?
1749 if (isa<ConstantSDNode>(Operand.getNode()) ||
1750 isa<ConstantFPSDNode>(Operand.getNode()))
1753 // Is this a VSrc or SSrc operand?
1754 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1755 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1756 // Try to fold the immediates. If this ends up with multiple constant bus
1757 // uses, it will be legalized later.
1758 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1762 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1764 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1765 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1767 // Test if it makes sense to swap operands
1768 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1769 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1770 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1772 // Swap commutable operands
1773 std::swap(Ops[0], Ops[1]);
1782 // Add optional chain and glue
1783 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1784 Ops.push_back(Node->getOperand(i));
1786 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1787 // this case a brand new node is always be created, even if the operands
1788 // are the same as before. So, manually check if anything has been changed.
1789 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1793 // Create a complete new instruction
1794 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1797 /// \brief Helper function for adjustWritemask
1798 static unsigned SubIdx2Lane(unsigned Idx) {
1801 case AMDGPU::sub0: return 0;
1802 case AMDGPU::sub1: return 1;
1803 case AMDGPU::sub2: return 2;
1804 case AMDGPU::sub3: return 3;
1808 /// \brief Adjust the writemask of MIMG instructions
1809 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1810 SelectionDAG &DAG) const {
1811 SDNode *Users[4] = { };
1813 unsigned OldDmask = Node->getConstantOperandVal(0);
1814 unsigned NewDmask = 0;
1816 // Try to figure out the used register components
1817 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1820 // Abort if we can't understand the usage
1821 if (!I->isMachineOpcode() ||
1822 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1825 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1826 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1827 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1829 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1831 // Set which texture component corresponds to the lane.
1833 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1835 Comp = countTrailingZeros(Dmask);
1836 Dmask &= ~(1 << Comp);
1839 // Abort if we have more than one user per component
1844 NewDmask |= 1 << Comp;
1847 // Abort if there's no change
1848 if (NewDmask == OldDmask)
1851 // Adjust the writemask in the node
1852 std::vector<SDValue> Ops;
1853 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1854 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1855 Ops.push_back(Node->getOperand(i));
1856 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1858 // If we only got one lane, replace it with a copy
1859 // (if NewDmask has only one bit set...)
1860 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1861 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1862 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1863 SDLoc(), Users[Lane]->getValueType(0),
1864 SDValue(Node, 0), RC);
1865 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1869 // Update the users of the node with the new indices
1870 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1872 SDNode *User = Users[i];
1876 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1877 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1881 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1882 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1883 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1888 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
1889 /// with frame index operands.
1890 /// LLVM assumes that inputs are to these instructions are registers.
1891 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
1892 SelectionDAG &DAG) const {
1894 SmallVector<SDValue, 8> Ops;
1895 for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
1896 if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
1897 Ops.push_back(Node->getOperand(i));
1902 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
1903 Node->getOperand(i).getValueType(),
1904 Node->getOperand(i)), 0));
1907 DAG.UpdateNodeOperands(Node, Ops);
1910 /// \brief Fold the instructions after selecting them.
1911 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1912 SelectionDAG &DAG) const {
1913 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1914 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1915 Node = AdjustRegClass(Node, DAG);
1917 if (TII->isMIMG(Node->getMachineOpcode()))
1918 adjustWritemask(Node, DAG);
1920 if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
1921 Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
1922 legalizeTargetIndependentNode(Node, DAG);
1926 return legalizeOperands(Node, DAG);
1929 /// \brief Assign the register class depending on the number of
1930 /// bits set in the writemask
1931 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1932 SDNode *Node) const {
1933 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1934 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1936 TII->legalizeOperands(MI);
1938 if (TII->isMIMG(MI->getOpcode())) {
1939 unsigned VReg = MI->getOperand(0).getReg();
1940 unsigned Writemask = MI->getOperand(1).getImm();
1941 unsigned BitsSet = 0;
1942 for (unsigned i = 0; i < 4; ++i)
1943 BitsSet += Writemask & (1 << i) ? 1 : 0;
1945 const TargetRegisterClass *RC;
1948 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1949 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1950 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1953 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1954 MI->setDesc(TII->get(NewOpcode));
1955 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1956 MRI.setRegClass(VReg, RC);
1960 // Replace unused atomics with the no return version.
1961 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1962 if (NoRetAtomicOp != -1) {
1963 if (!Node->hasAnyUseOfValue(0)) {
1964 MI->setDesc(TII->get(NoRetAtomicOp));
1965 MI->RemoveOperand(0);
1972 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
1973 SDValue K = DAG.getTargetConstant(Val, MVT::i32);
1974 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
1977 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
1979 SDValue Ptr) const {
1981 // XXX - Workaround for moveToVALU not handling different register class
1982 // inserts for REG_SEQUENCE.
1984 // Build the half of the subregister with the constants.
1985 const SDValue Ops0[] = {
1986 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, MVT::i32),
1987 buildSMovImm32(DAG, DL, 0),
1988 DAG.getTargetConstant(AMDGPU::sub0, MVT::i32),
1989 buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
1990 DAG.getTargetConstant(AMDGPU::sub1, MVT::i32)
1993 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
1994 MVT::v2i32, Ops0), 0);
1996 // Combine the constants and the pointer.
1997 const SDValue Ops1[] = {
1998 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2000 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2002 DAG.getTargetConstant(AMDGPU::sub2_sub3, MVT::i32)
2005 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2007 const SDValue Ops[] = {
2008 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2010 DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2011 buildSMovImm32(DAG, DL, 0),
2012 DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2013 buildSMovImm32(DAG, DL, AMDGPU::RSRC_DATA_FORMAT >> 32),
2014 DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2017 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2022 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
2023 SelectionDAG &DAG) const {
2026 unsigned NewOpcode = N->getMachineOpcode();
2028 switch (N->getMachineOpcode()) {
2030 case AMDGPU::S_LOAD_DWORD_IMM:
2031 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2033 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2034 if (NewOpcode == N->getMachineOpcode()) {
2035 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2038 case AMDGPU::S_LOAD_DWORDX4_IMM:
2039 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2040 if (NewOpcode == N->getMachineOpcode()) {
2041 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2043 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2046 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2048 const SDValue Zero64 = DAG.getTargetConstant(0, MVT::i64);
2049 SDValue Ptr(DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64, Zero64), 0);
2050 MachineSDNode *RSrc = wrapAddr64Rsrc(DAG, DL, Ptr);
2052 SmallVector<SDValue, 8> Ops;
2053 Ops.push_back(SDValue(RSrc, 0));
2054 Ops.push_back(N->getOperand(0));
2055 Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
2057 // Copy remaining operands so we keep any chain and glue nodes that follow
2058 // the normal operands.
2059 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
2060 Ops.push_back(N->getOperand(I));
2062 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2067 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2068 const TargetRegisterClass *RC,
2069 unsigned Reg, EVT VT) const {
2070 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2072 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2073 cast<RegisterSDNode>(VReg)->getReg(), VT);