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 // We need to custom lower vector stores from local memory
94 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
95 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
96 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
98 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
99 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
101 setOperationAction(ISD::STORE, MVT::i1, Custom);
102 setOperationAction(ISD::STORE, MVT::i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
104 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
106 setOperationAction(ISD::SELECT, MVT::f32, Promote);
107 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
108 setOperationAction(ISD::SELECT, MVT::i64, Custom);
109 setOperationAction(ISD::SELECT, MVT::f64, Promote);
110 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
112 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
113 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
114 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
115 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
117 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
118 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
130 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
134 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
136 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
137 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
138 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
139 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
141 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
142 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
144 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
145 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
146 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
147 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
148 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
149 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
151 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
152 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
153 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
154 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
156 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
157 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
158 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
159 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
160 setLoadExtAction(ISD::EXTLOAD, 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::FP_TO_SINT, MVT::i64, Expand);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
178 // These should use UDIVREM, so set them to expand
179 setOperationAction(ISD::UDIV, MVT::i64, Expand);
180 setOperationAction(ISD::UREM, MVT::i64, Expand);
182 // We only support LOAD/STORE and vector manipulation ops for vectors
183 // with > 4 elements.
185 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
188 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189 setOperationAction(ISD::SELECT, MVT::i1, Promote);
191 for (MVT VT : VecTypes) {
192 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
196 case ISD::BUILD_VECTOR:
198 case ISD::EXTRACT_VECTOR_ELT:
199 case ISD::INSERT_VECTOR_ELT:
200 case ISD::INSERT_SUBVECTOR:
201 case ISD::EXTRACT_SUBVECTOR:
203 case ISD::CONCAT_VECTORS:
204 setOperationAction(Op, VT, Custom);
207 setOperationAction(Op, VT, Expand);
213 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
214 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
215 setOperationAction(ISD::FTRUNC, VT, Expand);
216 setOperationAction(ISD::FCEIL, VT, Expand);
217 setOperationAction(ISD::FFLOOR, VT, Expand);
220 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
221 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
222 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
223 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
224 setOperationAction(ISD::FRINT, MVT::f64, Legal);
227 setOperationAction(ISD::FDIV, MVT::f32, Custom);
229 setTargetDAGCombine(ISD::FADD);
230 setTargetDAGCombine(ISD::FSUB);
231 setTargetDAGCombine(ISD::SELECT_CC);
232 setTargetDAGCombine(ISD::SETCC);
234 setTargetDAGCombine(ISD::UINT_TO_FP);
236 // All memory operations. Some folding on the pointer operand is done to help
237 // matching the constant offsets in the addressing modes.
238 setTargetDAGCombine(ISD::LOAD);
239 setTargetDAGCombine(ISD::STORE);
240 setTargetDAGCombine(ISD::ATOMIC_LOAD);
241 setTargetDAGCombine(ISD::ATOMIC_STORE);
242 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
243 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
244 setTargetDAGCombine(ISD::ATOMIC_SWAP);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
256 setSchedulingPreference(Sched::RegPressure);
259 //===----------------------------------------------------------------------===//
260 // TargetLowering queries
261 //===----------------------------------------------------------------------===//
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 = static_cast<const SIInstrInfo *>(
371 getTargetMachine().getSubtargetImpl()->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(
405 CallingConv::ID CallConv,
407 const SmallVectorImpl<ISD::InputArg> &Ins,
408 SDLoc DL, SelectionDAG &DAG,
409 SmallVectorImpl<SDValue> &InVals) const {
411 const TargetMachine &TM = getTargetMachine();
412 const SIRegisterInfo *TRI =
413 static_cast<const SIRegisterInfo*>(TM.getSubtargetImpl()->getRegisterInfo());
415 MachineFunction &MF = DAG.getMachineFunction();
416 FunctionType *FType = MF.getFunction()->getFunctionType();
417 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
419 assert(CallConv == CallingConv::C);
421 SmallVector<ISD::InputArg, 16> Splits;
422 BitVector Skipped(Ins.size());
424 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
425 const ISD::InputArg &Arg = Ins[i];
427 // First check if it's a PS input addr
428 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
429 !Arg.Flags.isByVal()) {
431 assert((PSInputNum <= 15) && "Too many PS inputs!");
434 // We can savely skip PS inputs
440 Info->PSInputAddr |= 1 << PSInputNum++;
443 // Second split vertices into their elements
444 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
445 ISD::InputArg NewArg = Arg;
446 NewArg.Flags.setSplit();
447 NewArg.VT = Arg.VT.getVectorElementType();
449 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
450 // three or five element vertex only needs three or five registers,
451 // NOT four or eigth.
452 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
453 unsigned NumElements = ParamType->getVectorNumElements();
455 for (unsigned j = 0; j != NumElements; ++j) {
456 Splits.push_back(NewArg);
457 NewArg.PartOffset += NewArg.VT.getStoreSize();
460 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
461 Splits.push_back(Arg);
465 SmallVector<CCValAssign, 16> ArgLocs;
466 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
469 // At least one interpolation mode must be enabled or else the GPU will hang.
470 if (Info->getShaderType() == ShaderType::PIXEL &&
471 (Info->PSInputAddr & 0x7F) == 0) {
472 Info->PSInputAddr |= 1;
473 CCInfo.AllocateReg(AMDGPU::VGPR0);
474 CCInfo.AllocateReg(AMDGPU::VGPR1);
477 // The pointer to the list of arguments is stored in SGPR0, SGPR1
478 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
479 if (Info->getShaderType() == ShaderType::COMPUTE) {
480 Info->NumUserSGPRs = 4;
482 unsigned InputPtrReg =
483 TRI->getPreloadedValue(MF, SIRegisterInfo::INPUT_PTR);
484 unsigned InputPtrRegLo =
485 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
486 unsigned InputPtrRegHi =
487 TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
489 unsigned ScratchPtrReg =
490 TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
491 unsigned ScratchPtrRegLo =
492 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 0);
493 unsigned ScratchPtrRegHi =
494 TRI->getPhysRegSubReg(ScratchPtrReg, &AMDGPU::SReg_32RegClass, 1);
496 CCInfo.AllocateReg(InputPtrRegLo);
497 CCInfo.AllocateReg(InputPtrRegHi);
498 CCInfo.AllocateReg(ScratchPtrRegLo);
499 CCInfo.AllocateReg(ScratchPtrRegHi);
500 MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
501 MF.addLiveIn(ScratchPtrReg, &AMDGPU::SReg_64RegClass);
504 if (Info->getShaderType() == ShaderType::COMPUTE) {
505 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
509 AnalyzeFormalArguments(CCInfo, Splits);
511 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
513 const ISD::InputArg &Arg = Ins[i];
515 InVals.push_back(DAG.getUNDEF(Arg.VT));
519 CCValAssign &VA = ArgLocs[ArgIdx++];
520 EVT VT = VA.getLocVT();
524 EVT MemVT = Splits[i].VT;
525 // The first 36 bytes of the input buffer contains information about
526 // thread group and global sizes.
527 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
528 36 + VA.getLocMemOffset(),
529 Ins[i].Flags.isSExt());
531 const PointerType *ParamTy =
532 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
533 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
534 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
535 // On SI local pointers are just offsets into LDS, so they are always
536 // less than 16-bits. On CI and newer they could potentially be
537 // real pointers, so we can't guarantee their size.
538 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
539 DAG.getValueType(MVT::i16));
542 InVals.push_back(Arg);
545 assert(VA.isRegLoc() && "Parameter must be in a register!");
547 unsigned Reg = VA.getLocReg();
549 if (VT == MVT::i64) {
550 // For now assume it is a pointer
551 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
552 &AMDGPU::SReg_64RegClass);
553 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
554 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
558 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
560 Reg = MF.addLiveIn(Reg, RC);
561 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
563 if (Arg.VT.isVector()) {
565 // Build a vector from the registers
566 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
567 unsigned NumElements = ParamType->getVectorNumElements();
569 SmallVector<SDValue, 4> Regs;
571 for (unsigned j = 1; j != NumElements; ++j) {
572 Reg = ArgLocs[ArgIdx++].getLocReg();
573 Reg = MF.addLiveIn(Reg, RC);
574 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
577 // Fill up the missing vector elements
578 NumElements = Arg.VT.getVectorNumElements() - NumElements;
579 for (unsigned j = 0; j != NumElements; ++j)
580 Regs.push_back(DAG.getUNDEF(VT));
582 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
586 InVals.push_back(Val);
591 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
592 MachineInstr * MI, MachineBasicBlock * BB) const {
594 MachineBasicBlock::iterator I = *MI;
595 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
596 getTargetMachine().getSubtargetImpl()->getInstrInfo());
597 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
599 switch (MI->getOpcode()) {
601 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
602 case AMDGPU::BRANCH: return BB;
603 case AMDGPU::SI_ADDR64_RSRC: {
604 unsigned SuperReg = MI->getOperand(0).getReg();
605 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
606 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
607 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
608 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
609 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
610 .addOperand(MI->getOperand(1));
611 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
613 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
614 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
615 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
617 .addImm(AMDGPU::sub0)
619 .addImm(AMDGPU::sub1);
620 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
622 .addImm(AMDGPU::sub0_sub1)
624 .addImm(AMDGPU::sub2_sub3);
625 MI->eraseFromParent();
628 case AMDGPU::SI_BUFFER_RSRC: {
629 unsigned SuperReg = MI->getOperand(0).getReg();
631 for (unsigned i = 0, e = 4; i < e; ++i) {
632 MachineOperand &Arg = MI->getOperand(i + 1);
635 Args[i] = Arg.getReg();
640 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
641 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
642 .addImm(Arg.getImm());
645 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
648 .addImm(AMDGPU::sub0)
650 .addImm(AMDGPU::sub1)
652 .addImm(AMDGPU::sub2)
654 .addImm(AMDGPU::sub3);
655 MI->eraseFromParent();
658 case AMDGPU::V_SUB_F64: {
659 unsigned DestReg = MI->getOperand(0).getReg();
660 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
661 .addImm(0) // SRC0 modifiers
662 .addReg(MI->getOperand(1).getReg())
663 .addImm(1) // SRC1 modifiers
664 .addReg(MI->getOperand(2).getReg())
667 MI->eraseFromParent();
670 case AMDGPU::SI_RegisterStorePseudo: {
671 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
672 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
673 MachineInstrBuilder MIB =
674 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
676 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
677 MIB.addOperand(MI->getOperand(i));
679 MI->eraseFromParent();
682 case AMDGPU::FCLAMP_SI: {
683 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
684 getTargetMachine().getSubtargetImpl()->getInstrInfo());
685 DebugLoc DL = MI->getDebugLoc();
686 unsigned DestReg = MI->getOperand(0).getReg();
687 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
688 .addImm(0) // SRC0 modifiers
689 .addOperand(MI->getOperand(1))
690 .addImm(0) // SRC1 modifiers
694 MI->eraseFromParent();
700 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
701 if (!VT.isVector()) {
704 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
707 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
711 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
712 VT = VT.getScalarType();
717 switch (VT.getSimpleVT().SimpleTy) {
719 return false; /* There is V_MAD_F32 for f32 */
729 //===----------------------------------------------------------------------===//
730 // Custom DAG Lowering Operations
731 //===----------------------------------------------------------------------===//
733 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
734 switch (Op.getOpcode()) {
735 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
736 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
737 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
739 SDValue Result = LowerLOAD(Op, DAG);
740 assert((!Result.getNode() ||
741 Result.getNode()->getNumValues() == 2) &&
742 "Load should return a value and a chain");
748 return LowerTrig(Op, DAG);
749 case ISD::SELECT: return LowerSELECT(Op, DAG);
750 case ISD::FDIV: return LowerFDIV(Op, DAG);
751 case ISD::STORE: return LowerSTORE(Op, DAG);
752 case ISD::GlobalAddress: {
753 MachineFunction &MF = DAG.getMachineFunction();
754 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
755 return LowerGlobalAddress(MFI, Op, DAG);
757 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
758 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
763 /// \brief Helper function for LowerBRCOND
764 static SDNode *findUser(SDValue Value, unsigned Opcode) {
766 SDNode *Parent = Value.getNode();
767 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
770 if (I.getUse().get() != Value)
773 if (I->getOpcode() == Opcode)
779 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
781 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
782 unsigned FrameIndex = FINode->getIndex();
784 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
787 /// This transforms the control flow intrinsics to get the branch destination as
788 /// last parameter, also switches branch target with BR if the need arise
789 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
790 SelectionDAG &DAG) const {
794 SDNode *Intr = BRCOND.getOperand(1).getNode();
795 SDValue Target = BRCOND.getOperand(2);
796 SDNode *BR = nullptr;
798 if (Intr->getOpcode() == ISD::SETCC) {
799 // As long as we negate the condition everything is fine
800 SDNode *SetCC = Intr;
801 assert(SetCC->getConstantOperandVal(1) == 1);
802 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
804 Intr = SetCC->getOperand(0).getNode();
807 // Get the target from BR if we don't negate the condition
808 BR = findUser(BRCOND, ISD::BR);
809 Target = BR->getOperand(1);
812 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
814 // Build the result and
815 SmallVector<EVT, 4> Res;
816 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
817 Res.push_back(Intr->getValueType(i));
819 // operands of the new intrinsic call
820 SmallVector<SDValue, 4> Ops;
821 Ops.push_back(BRCOND.getOperand(0));
822 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
823 Ops.push_back(Intr->getOperand(i));
824 Ops.push_back(Target);
826 // build the new intrinsic call
827 SDNode *Result = DAG.getNode(
828 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
829 DAG.getVTList(Res), Ops).getNode();
832 // Give the branch instruction our target
837 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
838 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
839 BR = NewBR.getNode();
842 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
844 // Copy the intrinsic results to registers
845 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
846 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
850 Chain = DAG.getCopyToReg(
852 CopyToReg->getOperand(1),
853 SDValue(Result, i - 1),
856 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
859 // Remove the old intrinsic from the chain
860 DAG.ReplaceAllUsesOfValueWith(
861 SDValue(Intr, Intr->getNumValues() - 1),
862 Intr->getOperand(0));
867 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
869 SelectionDAG &DAG) const {
870 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
872 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
873 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
876 const GlobalValue *GV = GSD->getGlobal();
877 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
879 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
880 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
882 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
883 DAG.getConstant(0, MVT::i32));
884 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
885 DAG.getConstant(1, MVT::i32));
887 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
889 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
890 PtrHi, DAG.getConstant(0, MVT::i32),
891 SDValue(Lo.getNode(), 1));
892 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
895 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
896 SelectionDAG &DAG) const {
897 MachineFunction &MF = DAG.getMachineFunction();
898 const SIRegisterInfo *TRI =
899 static_cast<const SIRegisterInfo*>(MF.getSubtarget().getRegisterInfo());
901 EVT VT = Op.getValueType();
903 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
905 switch (IntrinsicID) {
906 case Intrinsic::r600_read_ngroups_x:
907 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
908 SI::KernelInputOffsets::NGROUPS_X, false);
909 case Intrinsic::r600_read_ngroups_y:
910 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
911 SI::KernelInputOffsets::NGROUPS_Y, false);
912 case Intrinsic::r600_read_ngroups_z:
913 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
914 SI::KernelInputOffsets::NGROUPS_Z, false);
915 case Intrinsic::r600_read_global_size_x:
916 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
917 SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
918 case Intrinsic::r600_read_global_size_y:
919 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
920 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
921 case Intrinsic::r600_read_global_size_z:
922 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
923 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
924 case Intrinsic::r600_read_local_size_x:
925 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
926 SI::KernelInputOffsets::LOCAL_SIZE_X, false);
927 case Intrinsic::r600_read_local_size_y:
928 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
929 SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
930 case Intrinsic::r600_read_local_size_z:
931 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
932 SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
933 case Intrinsic::r600_read_tgid_x:
934 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
935 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
936 case Intrinsic::r600_read_tgid_y:
937 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
938 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
939 case Intrinsic::r600_read_tgid_z:
940 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
941 TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
942 case Intrinsic::r600_read_tidig_x:
943 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
944 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
945 case Intrinsic::r600_read_tidig_y:
946 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
947 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
948 case Intrinsic::r600_read_tidig_z:
949 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
950 TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
951 case AMDGPUIntrinsic::SI_load_const: {
957 MachineMemOperand *MMO = MF.getMachineMemOperand(
958 MachinePointerInfo(),
959 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
960 VT.getStoreSize(), 4);
961 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
962 Op->getVTList(), Ops, VT, MMO);
964 case AMDGPUIntrinsic::SI_sample:
965 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
966 case AMDGPUIntrinsic::SI_sampleb:
967 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
968 case AMDGPUIntrinsic::SI_sampled:
969 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
970 case AMDGPUIntrinsic::SI_samplel:
971 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
972 case AMDGPUIntrinsic::SI_vs_load_input:
973 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
978 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
982 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
983 SelectionDAG &DAG) const {
984 MachineFunction &MF = DAG.getMachineFunction();
985 SDValue Chain = Op.getOperand(0);
986 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
988 switch (IntrinsicID) {
989 case AMDGPUIntrinsic::SI_tbuffer_store: {
1008 EVT VT = Op.getOperand(3).getValueType();
1010 MachineMemOperand *MMO = MF.getMachineMemOperand(
1011 MachinePointerInfo(),
1012 MachineMemOperand::MOStore,
1013 VT.getStoreSize(), 4);
1014 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1015 Op->getVTList(), Ops, VT, MMO);
1022 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1024 LoadSDNode *Load = cast<LoadSDNode>(Op);
1026 if (Op.getValueType().isVector()) {
1027 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1028 "Custom lowering for non-i32 vectors hasn't been implemented.");
1029 unsigned NumElements = Op.getValueType().getVectorNumElements();
1030 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1031 switch (Load->getAddressSpace()) {
1033 case AMDGPUAS::GLOBAL_ADDRESS:
1034 case AMDGPUAS::PRIVATE_ADDRESS:
1035 // v4 loads are supported for private and global memory.
1036 if (NumElements <= 4)
1039 case AMDGPUAS::LOCAL_ADDRESS:
1040 return ScalarizeVectorLoad(Op, DAG);
1044 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1047 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1049 SelectionDAG &DAG) const {
1050 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1056 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1057 if (Op.getValueType() != MVT::i64)
1061 SDValue Cond = Op.getOperand(0);
1063 SDValue Zero = DAG.getConstant(0, MVT::i32);
1064 SDValue One = DAG.getConstant(1, MVT::i32);
1066 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1067 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1069 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1070 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1072 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1074 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1075 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1077 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1079 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1080 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1083 // Catch division cases where we can use shortcuts with rcp and rsq
1085 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1087 SDValue LHS = Op.getOperand(0);
1088 SDValue RHS = Op.getOperand(1);
1089 EVT VT = Op.getValueType();
1090 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1092 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1093 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1094 CLHS->isExactlyValue(1.0)) {
1095 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1096 // the CI documentation has a worst case error of 1 ulp.
1097 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1098 // use it as long as we aren't trying to use denormals.
1100 // 1.0 / sqrt(x) -> rsq(x)
1102 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1103 // error seems really high at 2^29 ULP.
1104 if (RHS.getOpcode() == ISD::FSQRT)
1105 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1107 // 1.0 / x -> rcp(x)
1108 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1113 // Turn into multiply by the reciprocal.
1114 // x / y -> x * (1.0 / y)
1115 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1116 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1122 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1123 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1124 if (FastLowered.getNode())
1127 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1128 // selection error for now rather than do something incorrect.
1129 if (Subtarget->hasFP32Denormals())
1133 SDValue LHS = Op.getOperand(0);
1134 SDValue RHS = Op.getOperand(1);
1136 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1138 const APFloat K0Val(BitsToFloat(0x6f800000));
1139 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1141 const APFloat K1Val(BitsToFloat(0x2f800000));
1142 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1144 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1146 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1148 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1150 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1152 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1154 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1156 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1158 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1161 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1165 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1166 EVT VT = Op.getValueType();
1169 return LowerFDIV32(Op, DAG);
1172 return LowerFDIV64(Op, DAG);
1174 llvm_unreachable("Unexpected type for fdiv");
1177 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1179 StoreSDNode *Store = cast<StoreSDNode>(Op);
1180 EVT VT = Store->getMemoryVT();
1182 // These stores are legal.
1183 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1184 VT.isVector() && VT.getVectorNumElements() == 2 &&
1185 VT.getVectorElementType() == MVT::i32)
1188 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1189 if (VT.isVector() && VT.getVectorNumElements() > 4)
1190 return ScalarizeVectorStore(Op, DAG);
1194 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1198 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1199 return ScalarizeVectorStore(Op, DAG);
1202 return DAG.getTruncStore(Store->getChain(), DL,
1203 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1204 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1209 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1210 EVT VT = Op.getValueType();
1211 SDValue Arg = Op.getOperand(0);
1212 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1213 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1214 DAG.getConstantFP(0.5 / M_PI, VT)));
1216 switch (Op.getOpcode()) {
1218 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1220 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1222 llvm_unreachable("Wrong trig opcode");
1226 //===----------------------------------------------------------------------===//
1227 // Custom DAG optimizations
1228 //===----------------------------------------------------------------------===//
1230 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1231 DAGCombinerInfo &DCI) {
1232 EVT VT = N->getValueType(0);
1233 EVT ScalarVT = VT.getScalarType();
1234 if (ScalarVT != MVT::f32)
1237 SelectionDAG &DAG = DCI.DAG;
1240 SDValue Src = N->getOperand(0);
1241 EVT SrcVT = Src.getValueType();
1243 // TODO: We could try to match extracting the higher bytes, which would be
1244 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1245 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1246 // about in practice.
1247 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1248 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1249 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1250 DCI.AddToWorklist(Cvt.getNode());
1255 // We are primarily trying to catch operations on illegal vector types
1256 // before they are expanded.
1257 // For scalars, we can use the more flexible method of checking masked bits
1258 // after legalization.
1259 if (!DCI.isBeforeLegalize() ||
1260 !SrcVT.isVector() ||
1261 SrcVT.getVectorElementType() != MVT::i8) {
1265 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1267 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1269 unsigned NElts = SrcVT.getVectorNumElements();
1270 if (!SrcVT.isSimple() && NElts != 3)
1273 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1274 // prevent a mess from expanding to v4i32 and repacking.
1275 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1276 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1277 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1278 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1280 LoadSDNode *Load = cast<LoadSDNode>(Src);
1281 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1285 Load->getMemOperand());
1287 // Make sure successors of the original load stay after it by updating
1288 // them to use the new Chain.
1289 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1291 SmallVector<SDValue, 4> Elts;
1292 if (RegVT.isVector())
1293 DAG.ExtractVectorElements(NewLoad, Elts);
1295 Elts.push_back(NewLoad);
1297 SmallVector<SDValue, 4> Ops;
1299 unsigned EltIdx = 0;
1300 for (SDValue Elt : Elts) {
1301 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1302 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1303 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1304 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1305 DCI.AddToWorklist(Cvt.getNode());
1312 assert(Ops.size() == NElts);
1314 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1320 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1322 // This is a variant of
1323 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1325 // The normal DAG combiner will do this, but only if the add has one use since
1326 // that would increase the number of instructions.
1328 // This prevents us from seeing a constant offset that can be folded into a
1329 // memory instruction's addressing mode. If we know the resulting add offset of
1330 // a pointer can be folded into an addressing offset, we can replace the pointer
1331 // operand with the add of new constant offset. This eliminates one of the uses,
1332 // and may allow the remaining use to also be simplified.
1334 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1336 DAGCombinerInfo &DCI) const {
1337 SDValue N0 = N->getOperand(0);
1338 SDValue N1 = N->getOperand(1);
1340 if (N0.getOpcode() != ISD::ADD)
1343 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1347 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1351 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1352 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1354 // If the resulting offset is too large, we can't fold it into the addressing
1356 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1357 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1360 SelectionDAG &DAG = DCI.DAG;
1362 EVT VT = N->getValueType(0);
1364 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1365 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1367 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1370 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1371 DAGCombinerInfo &DCI) const {
1372 SelectionDAG &DAG = DCI.DAG;
1374 EVT VT = N->getValueType(0);
1376 switch (N->getOpcode()) {
1377 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1379 SDValue Arg0 = N->getOperand(0);
1380 SDValue Arg1 = N->getOperand(1);
1381 SDValue CC = N->getOperand(2);
1382 ConstantSDNode * C = nullptr;
1383 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1385 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1387 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1388 && Arg0.getOperand(0).getValueType() == MVT::i1
1389 && (C = dyn_cast<ConstantSDNode>(Arg1))
1391 && CCOp == ISD::SETNE) {
1392 return SimplifySetCC(VT, Arg0.getOperand(0),
1393 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1398 case AMDGPUISD::CVT_F32_UBYTE0:
1399 case AMDGPUISD::CVT_F32_UBYTE1:
1400 case AMDGPUISD::CVT_F32_UBYTE2:
1401 case AMDGPUISD::CVT_F32_UBYTE3: {
1402 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1404 SDValue Src = N->getOperand(0);
1405 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1407 APInt KnownZero, KnownOne;
1408 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1409 !DCI.isBeforeLegalizeOps());
1410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1411 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1412 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1413 DCI.CommitTargetLoweringOpt(TLO);
1419 case ISD::UINT_TO_FP: {
1420 return performUCharToFloatCombine(N, DCI);
1423 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1426 EVT VT = N->getValueType(0);
1430 SDValue LHS = N->getOperand(0);
1431 SDValue RHS = N->getOperand(1);
1433 // These should really be instruction patterns, but writing patterns with
1434 // source modiifiers is a pain.
1436 // fadd (fadd (a, a), b) -> mad 2.0, a, b
1437 if (LHS.getOpcode() == ISD::FADD) {
1438 SDValue A = LHS.getOperand(0);
1439 if (A == LHS.getOperand(1)) {
1440 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1441 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, RHS);
1445 // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1446 if (RHS.getOpcode() == ISD::FADD) {
1447 SDValue A = RHS.getOperand(0);
1448 if (A == RHS.getOperand(1)) {
1449 const SDValue Two = DAG.getTargetConstantFP(2.0, MVT::f32);
1450 return DAG.getNode(AMDGPUISD::MAD, DL, VT, Two, A, LHS);
1457 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1460 EVT VT = N->getValueType(0);
1462 // Try to get the fneg to fold into the source modifier. This undoes generic
1463 // DAG combines and folds them into the mad.
1464 if (VT == MVT::f32) {
1465 SDValue LHS = N->getOperand(0);
1466 SDValue RHS = N->getOperand(1);
1468 if (LHS.getOpcode() == ISD::FMUL) {
1469 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1471 SDValue A = LHS.getOperand(0);
1472 SDValue B = LHS.getOperand(1);
1473 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1475 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1478 if (RHS.getOpcode() == ISD::FMUL) {
1479 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1481 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1482 SDValue B = RHS.getOperand(1);
1485 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1494 case ISD::ATOMIC_LOAD:
1495 case ISD::ATOMIC_STORE:
1496 case ISD::ATOMIC_CMP_SWAP:
1497 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1498 case ISD::ATOMIC_SWAP:
1499 case ISD::ATOMIC_LOAD_ADD:
1500 case ISD::ATOMIC_LOAD_SUB:
1501 case ISD::ATOMIC_LOAD_AND:
1502 case ISD::ATOMIC_LOAD_OR:
1503 case ISD::ATOMIC_LOAD_XOR:
1504 case ISD::ATOMIC_LOAD_NAND:
1505 case ISD::ATOMIC_LOAD_MIN:
1506 case ISD::ATOMIC_LOAD_MAX:
1507 case ISD::ATOMIC_LOAD_UMIN:
1508 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1509 if (DCI.isBeforeLegalize())
1512 MemSDNode *MemNode = cast<MemSDNode>(N);
1513 SDValue Ptr = MemNode->getBasePtr();
1515 // TODO: We could also do this for multiplies.
1516 unsigned AS = MemNode->getAddressSpace();
1517 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1518 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1520 SmallVector<SDValue, 8> NewOps;
1521 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1522 NewOps.push_back(MemNode->getOperand(I));
1524 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1525 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1531 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1534 /// \brief Test if RegClass is one of the VSrc classes
1535 static bool isVSrc(unsigned RegClass) {
1537 default: return false;
1538 case AMDGPU::VSrc_32RegClassID:
1539 case AMDGPU::VCSrc_32RegClassID:
1540 case AMDGPU::VSrc_64RegClassID:
1541 case AMDGPU::VCSrc_64RegClassID:
1546 /// \brief Test if RegClass is one of the SSrc classes
1547 static bool isSSrc(unsigned RegClass) {
1548 return AMDGPU::SSrc_32RegClassID == RegClass ||
1549 AMDGPU::SSrc_64RegClassID == RegClass;
1552 /// \brief Analyze the possible immediate value Op
1554 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1555 /// and the immediate value if it's a literal immediate
1556 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1563 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1564 if (Node->getZExtValue() >> 32) {
1567 Imm.I = Node->getSExtValue();
1568 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1569 if (N->getValueType(0) != MVT::f32)
1571 Imm.F = Node->getValueAPF().convertToFloat();
1573 return -1; // It isn't an immediate
1575 if ((Imm.I >= -16 && Imm.I <= 64) ||
1576 Imm.F == 0.5f || Imm.F == -0.5f ||
1577 Imm.F == 1.0f || Imm.F == -1.0f ||
1578 Imm.F == 2.0f || Imm.F == -2.0f ||
1579 Imm.F == 4.0f || Imm.F == -4.0f)
1580 return 0; // It's an inline immediate
1582 return Imm.I; // It's a literal immediate
1585 /// \brief Try to fold an immediate directly into an instruction
1586 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1587 bool &ScalarSlotUsed) const {
1589 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1590 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1591 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1592 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1595 const SDValue &Op = Mov->getOperand(0);
1596 int32_t Value = analyzeImmediate(Op.getNode());
1598 // Not an immediate at all
1601 } else if (Value == 0) {
1602 // Inline immediates can always be fold
1606 } else if (Value == Immediate) {
1607 // Already fold literal immediate
1611 } else if (!ScalarSlotUsed && !Immediate) {
1612 // Fold this literal immediate
1613 ScalarSlotUsed = true;
1623 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1624 SelectionDAG &DAG, const SDValue &Op) const {
1625 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1626 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1627 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1629 if (!Op->isMachineOpcode()) {
1630 switch(Op->getOpcode()) {
1631 case ISD::CopyFromReg: {
1632 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1633 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1634 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1635 return MRI.getRegClass(Reg);
1637 return TRI.getPhysRegClass(Reg);
1639 default: return nullptr;
1642 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1643 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1644 if (OpClassID != -1) {
1645 return TRI.getRegClass(OpClassID);
1647 switch(Op.getMachineOpcode()) {
1648 case AMDGPU::COPY_TO_REGCLASS:
1649 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1650 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1652 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1653 // class, then the register class for the value could be either a
1654 // VReg or and SReg. In order to get a more accurate
1655 if (isVSrc(OpClassID))
1656 return getRegClassForNode(DAG, Op.getOperand(0));
1658 return TRI.getRegClass(OpClassID);
1659 case AMDGPU::EXTRACT_SUBREG: {
1660 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1661 const TargetRegisterClass *SuperClass =
1662 getRegClassForNode(DAG, Op.getOperand(0));
1663 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1665 case AMDGPU::REG_SEQUENCE:
1666 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1667 return TRI.getRegClass(
1668 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1670 return getRegClassFor(Op.getSimpleValueType());
1674 /// \brief Does "Op" fit into register class "RegClass" ?
1675 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1676 unsigned RegClass) const {
1677 const TargetRegisterInfo *TRI =
1678 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1679 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1683 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1686 /// \returns true if \p Node's operands are different from the SDValue list
1688 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1689 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1690 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1697 /// TODO: This needs to be removed. It's current primary purpose is to fold
1698 /// immediates into operands when legal. The legalization parts are redundant
1699 /// with SIInstrInfo::legalizeOperands which is called in a post-isel hook.
1700 SDNode *SITargetLowering::legalizeOperands(MachineSDNode *Node,
1701 SelectionDAG &DAG) const {
1702 // Original encoding (either e32 or e64)
1703 int Opcode = Node->getMachineOpcode();
1704 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1705 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1706 const MCInstrDesc *Desc = &TII->get(Opcode);
1708 unsigned NumDefs = Desc->getNumDefs();
1709 unsigned NumOps = Desc->getNumOperands();
1711 // Commuted opcode if available
1712 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1713 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1715 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1716 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1718 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1719 bool HaveVSrc = false, HaveSSrc = false;
1721 // First figure out what we already have in this instruction.
1722 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1723 i != e && Op < NumOps; ++i, ++Op) {
1725 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1726 if (isVSrc(RegClass))
1728 else if (isSSrc(RegClass))
1733 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1734 if (Imm != -1 && Imm != 0) {
1735 // Literal immediate
1740 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1741 if (!HaveVSrc && !HaveSSrc)
1744 // No scalar allowed when we have both VSrc and SSrc
1745 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1747 // If this instruction has an implicit use of VCC, then it can't use the
1749 for (unsigned i = 0, e = Desc->getNumImplicitUses(); i != e; ++i) {
1750 if (Desc->ImplicitUses[i] == AMDGPU::VCC) {
1751 ScalarSlotUsed = true;
1756 // Second go over the operands and try to fold them
1757 std::vector<SDValue> Ops;
1758 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1759 i != e && Op < NumOps; ++i, ++Op) {
1761 const SDValue &Operand = Node->getOperand(i);
1762 Ops.push_back(Operand);
1764 // Already folded immediate?
1765 if (isa<ConstantSDNode>(Operand.getNode()) ||
1766 isa<ConstantFPSDNode>(Operand.getNode()))
1769 // Is this a VSrc or SSrc operand?
1770 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1771 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1772 // Try to fold the immediates. If this ends up with multiple constant bus
1773 // uses, it will be legalized later.
1774 foldImm(Ops[i], Immediate, ScalarSlotUsed);
1778 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1780 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1781 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1783 // Test if it makes sense to swap operands
1784 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1785 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1786 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1788 // Swap commutable operands
1789 std::swap(Ops[0], Ops[1]);
1798 // Add optional chain and glue
1799 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1800 Ops.push_back(Node->getOperand(i));
1802 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1803 // this case a brand new node is always be created, even if the operands
1804 // are the same as before. So, manually check if anything has been changed.
1805 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1809 // Create a complete new instruction
1810 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1813 /// \brief Helper function for adjustWritemask
1814 static unsigned SubIdx2Lane(unsigned Idx) {
1817 case AMDGPU::sub0: return 0;
1818 case AMDGPU::sub1: return 1;
1819 case AMDGPU::sub2: return 2;
1820 case AMDGPU::sub3: return 3;
1824 /// \brief Adjust the writemask of MIMG instructions
1825 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1826 SelectionDAG &DAG) const {
1827 SDNode *Users[4] = { };
1829 unsigned OldDmask = Node->getConstantOperandVal(0);
1830 unsigned NewDmask = 0;
1832 // Try to figure out the used register components
1833 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1836 // Abort if we can't understand the usage
1837 if (!I->isMachineOpcode() ||
1838 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1841 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1842 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1843 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1845 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1847 // Set which texture component corresponds to the lane.
1849 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1851 Comp = countTrailingZeros(Dmask);
1852 Dmask &= ~(1 << Comp);
1855 // Abort if we have more than one user per component
1860 NewDmask |= 1 << Comp;
1863 // Abort if there's no change
1864 if (NewDmask == OldDmask)
1867 // Adjust the writemask in the node
1868 std::vector<SDValue> Ops;
1869 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1870 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1871 Ops.push_back(Node->getOperand(i));
1872 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1874 // If we only got one lane, replace it with a copy
1875 // (if NewDmask has only one bit set...)
1876 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1877 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1878 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1879 SDLoc(), Users[Lane]->getValueType(0),
1880 SDValue(Node, 0), RC);
1881 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1885 // Update the users of the node with the new indices
1886 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1888 SDNode *User = Users[i];
1892 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1893 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1897 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1898 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1899 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1904 /// \brief Fold the instructions after selecting them.
1905 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1906 SelectionDAG &DAG) const {
1907 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1908 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1909 Node = AdjustRegClass(Node, DAG);
1911 if (TII->isMIMG(Node->getMachineOpcode()))
1912 adjustWritemask(Node, DAG);
1914 return legalizeOperands(Node, DAG);
1917 /// \brief Assign the register class depending on the number of
1918 /// bits set in the writemask
1919 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1920 SDNode *Node) const {
1921 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1922 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1924 TII->legalizeOperands(MI);
1926 if (TII->isMIMG(MI->getOpcode())) {
1927 unsigned VReg = MI->getOperand(0).getReg();
1928 unsigned Writemask = MI->getOperand(1).getImm();
1929 unsigned BitsSet = 0;
1930 for (unsigned i = 0; i < 4; ++i)
1931 BitsSet += Writemask & (1 << i) ? 1 : 0;
1933 const TargetRegisterClass *RC;
1936 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1937 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1938 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1941 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1942 MI->setDesc(TII->get(NewOpcode));
1943 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1944 MRI.setRegClass(VReg, RC);
1948 // Replace unused atomics with the no return version.
1949 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1950 if (NoRetAtomicOp != -1) {
1951 if (!Node->hasAnyUseOfValue(0)) {
1952 MI->setDesc(TII->get(NoRetAtomicOp));
1953 MI->RemoveOperand(0);
1960 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1961 SelectionDAG &DAG) const {
1964 unsigned NewOpcode = N->getMachineOpcode();
1966 switch (N->getMachineOpcode()) {
1968 case AMDGPU::S_LOAD_DWORD_IMM:
1969 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1971 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1972 if (NewOpcode == N->getMachineOpcode()) {
1973 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1976 case AMDGPU::S_LOAD_DWORDX4_IMM:
1977 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1978 if (NewOpcode == N->getMachineOpcode()) {
1979 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1981 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1984 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1985 MachineSDNode *RSrc = DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL,
1987 DAG.getConstant(0, MVT::i64));
1989 SmallVector<SDValue, 8> Ops;
1990 Ops.push_back(SDValue(RSrc, 0));
1991 Ops.push_back(N->getOperand(0));
1992 Ops.push_back(DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32));
1994 // Copy remaining operands so we keep any chain and glue nodes that follow
1995 // the normal operands.
1996 for (unsigned I = 2, E = N->getNumOperands(); I != E; ++I)
1997 Ops.push_back(N->getOperand(I));
1999 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2004 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2005 const TargetRegisterClass *RC,
2006 unsigned Reg, EVT VT) const {
2007 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2009 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2010 cast<RegisterSDNode>(VReg)->getReg(), VT);