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::FSUB);
230 setTargetDAGCombine(ISD::SELECT_CC);
231 setTargetDAGCombine(ISD::SETCC);
233 setTargetDAGCombine(ISD::UINT_TO_FP);
235 // All memory operations. Some folding on the pointer operand is done to help
236 // matching the constant offsets in the addressing modes.
237 setTargetDAGCombine(ISD::LOAD);
238 setTargetDAGCombine(ISD::STORE);
239 setTargetDAGCombine(ISD::ATOMIC_LOAD);
240 setTargetDAGCombine(ISD::ATOMIC_STORE);
241 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
242 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
243 setTargetDAGCombine(ISD::ATOMIC_SWAP);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
255 setSchedulingPreference(Sched::RegPressure);
258 //===----------------------------------------------------------------------===//
259 // TargetLowering queries
260 //===----------------------------------------------------------------------===//
262 // FIXME: This really needs an address space argument. The immediate offset
263 // size is different for different sets of memory instruction sets.
265 // The single offset DS instructions have a 16-bit unsigned byte offset.
267 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
268 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
269 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
271 // SMRD instructions have an 8-bit, dword offset.
273 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
275 // No global is ever allowed as a base.
279 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
281 if (!isUInt<16>(AM.BaseOffs))
286 case 0: // "r+i" or just "i", depending on HasBaseReg.
289 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
291 // Otherwise we have r+r or r+i.
294 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
298 default: // Don't allow n * r
305 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
308 bool *IsFast) const {
312 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
313 // which isn't a simple VT.
314 if (!VT.isSimple() || VT == MVT::Other)
317 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
318 // see what for specifically. The wording everywhere else seems to be the
321 // XXX - The only mention I see of this in the ISA manual is for LDS direct
322 // reads the "byte address and must be dword aligned". Is it also true for the
323 // normal loads and stores?
324 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
325 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
326 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
327 // with adjacent offsets.
328 return Align % 4 == 0;
331 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
332 // byte-address are ignored, thus forcing Dword alignment.
333 // This applies to private, global, and constant memory.
336 return VT.bitsGT(MVT::i32);
339 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
340 unsigned SrcAlign, bool IsMemset,
343 MachineFunction &MF) const {
344 // FIXME: Should account for address space here.
346 // The default fallback uses the private pointer size as a guess for a type to
347 // use. Make sure we switch these to 64-bit accesses.
349 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
352 if (Size >= 8 && DstAlign >= 4)
359 TargetLoweringBase::LegalizeTypeAction
360 SITargetLowering::getPreferredVectorAction(EVT VT) const {
361 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
362 return TypeSplitVector;
364 return TargetLoweringBase::getPreferredVectorAction(VT);
367 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
369 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
370 getTargetMachine().getSubtargetImpl()->getInstrInfo());
371 return TII->isInlineConstant(Imm);
374 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
375 SDLoc SL, SDValue Chain,
376 unsigned Offset, bool Signed) const {
377 const DataLayout *DL = getDataLayout();
379 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
381 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
382 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
383 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
384 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
385 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
386 DAG.getConstant(Offset, MVT::i64));
387 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
388 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
390 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
391 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
393 true, // isNonTemporal
395 DL->getABITypeAlignment(Ty)); // Alignment
398 SDValue SITargetLowering::LowerFormalArguments(
400 CallingConv::ID CallConv,
402 const SmallVectorImpl<ISD::InputArg> &Ins,
403 SDLoc DL, SelectionDAG &DAG,
404 SmallVectorImpl<SDValue> &InVals) const {
406 const TargetRegisterInfo *TRI =
407 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
409 MachineFunction &MF = DAG.getMachineFunction();
410 FunctionType *FType = MF.getFunction()->getFunctionType();
411 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
413 assert(CallConv == CallingConv::C);
415 SmallVector<ISD::InputArg, 16> Splits;
416 BitVector Skipped(Ins.size());
418 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
419 const ISD::InputArg &Arg = Ins[i];
421 // First check if it's a PS input addr
422 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
423 !Arg.Flags.isByVal()) {
425 assert((PSInputNum <= 15) && "Too many PS inputs!");
428 // We can savely skip PS inputs
434 Info->PSInputAddr |= 1 << PSInputNum++;
437 // Second split vertices into their elements
438 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
439 ISD::InputArg NewArg = Arg;
440 NewArg.Flags.setSplit();
441 NewArg.VT = Arg.VT.getVectorElementType();
443 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
444 // three or five element vertex only needs three or five registers,
445 // NOT four or eigth.
446 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
447 unsigned NumElements = ParamType->getVectorNumElements();
449 for (unsigned j = 0; j != NumElements; ++j) {
450 Splits.push_back(NewArg);
451 NewArg.PartOffset += NewArg.VT.getStoreSize();
454 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
455 Splits.push_back(Arg);
459 SmallVector<CCValAssign, 16> ArgLocs;
460 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
463 // At least one interpolation mode must be enabled or else the GPU will hang.
464 if (Info->getShaderType() == ShaderType::PIXEL &&
465 (Info->PSInputAddr & 0x7F) == 0) {
466 Info->PSInputAddr |= 1;
467 CCInfo.AllocateReg(AMDGPU::VGPR0);
468 CCInfo.AllocateReg(AMDGPU::VGPR1);
471 // The pointer to the list of arguments is stored in SGPR0, SGPR1
472 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
473 if (Info->getShaderType() == ShaderType::COMPUTE) {
474 Info->NumUserSGPRs = 4;
475 CCInfo.AllocateReg(AMDGPU::SGPR0);
476 CCInfo.AllocateReg(AMDGPU::SGPR1);
477 CCInfo.AllocateReg(AMDGPU::SGPR2);
478 CCInfo.AllocateReg(AMDGPU::SGPR3);
479 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
480 MF.addLiveIn(AMDGPU::SGPR2_SGPR3, &AMDGPU::SReg_64RegClass);
483 if (Info->getShaderType() == ShaderType::COMPUTE) {
484 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
488 AnalyzeFormalArguments(CCInfo, Splits);
490 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
492 const ISD::InputArg &Arg = Ins[i];
494 InVals.push_back(DAG.getUNDEF(Arg.VT));
498 CCValAssign &VA = ArgLocs[ArgIdx++];
499 EVT VT = VA.getLocVT();
503 EVT MemVT = Splits[i].VT;
504 // The first 36 bytes of the input buffer contains information about
505 // thread group and global sizes.
506 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
507 36 + VA.getLocMemOffset(),
508 Ins[i].Flags.isSExt());
510 const PointerType *ParamTy =
511 dyn_cast<PointerType>(FType->getParamType(Ins[i].OrigArgIndex));
512 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
513 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
514 // On SI local pointers are just offsets into LDS, so they are always
515 // less than 16-bits. On CI and newer they could potentially be
516 // real pointers, so we can't guarantee their size.
517 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
518 DAG.getValueType(MVT::i16));
521 InVals.push_back(Arg);
524 assert(VA.isRegLoc() && "Parameter must be in a register!");
526 unsigned Reg = VA.getLocReg();
528 if (VT == MVT::i64) {
529 // For now assume it is a pointer
530 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
531 &AMDGPU::SReg_64RegClass);
532 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
533 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
537 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
539 Reg = MF.addLiveIn(Reg, RC);
540 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
542 if (Arg.VT.isVector()) {
544 // Build a vector from the registers
545 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
546 unsigned NumElements = ParamType->getVectorNumElements();
548 SmallVector<SDValue, 4> Regs;
550 for (unsigned j = 1; j != NumElements; ++j) {
551 Reg = ArgLocs[ArgIdx++].getLocReg();
552 Reg = MF.addLiveIn(Reg, RC);
553 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
556 // Fill up the missing vector elements
557 NumElements = Arg.VT.getVectorNumElements() - NumElements;
558 for (unsigned j = 0; j != NumElements; ++j)
559 Regs.push_back(DAG.getUNDEF(VT));
561 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
565 InVals.push_back(Val);
570 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
571 MachineInstr * MI, MachineBasicBlock * BB) const {
573 MachineBasicBlock::iterator I = *MI;
574 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
575 getTargetMachine().getSubtargetImpl()->getInstrInfo());
576 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
578 switch (MI->getOpcode()) {
580 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
581 case AMDGPU::BRANCH: return BB;
582 case AMDGPU::SI_ADDR64_RSRC: {
583 unsigned SuperReg = MI->getOperand(0).getReg();
584 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
585 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
586 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
587 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
588 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
589 .addOperand(MI->getOperand(1));
590 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
592 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
593 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
594 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
596 .addImm(AMDGPU::sub0)
598 .addImm(AMDGPU::sub1);
599 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
601 .addImm(AMDGPU::sub0_sub1)
603 .addImm(AMDGPU::sub2_sub3);
604 MI->eraseFromParent();
607 case AMDGPU::SI_BUFFER_RSRC: {
608 unsigned SuperReg = MI->getOperand(0).getReg();
610 for (unsigned i = 0, e = 4; i < e; ++i) {
611 MachineOperand &Arg = MI->getOperand(i + 1);
614 Args[i] = Arg.getReg();
619 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
620 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
621 .addImm(Arg.getImm());
624 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
627 .addImm(AMDGPU::sub0)
629 .addImm(AMDGPU::sub1)
631 .addImm(AMDGPU::sub2)
633 .addImm(AMDGPU::sub3);
634 MI->eraseFromParent();
637 case AMDGPU::V_SUB_F64: {
638 unsigned DestReg = MI->getOperand(0).getReg();
639 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
640 .addImm(0) // SRC0 modifiers
641 .addReg(MI->getOperand(1).getReg())
642 .addImm(1) // SRC1 modifiers
643 .addReg(MI->getOperand(2).getReg())
646 MI->eraseFromParent();
649 case AMDGPU::SI_RegisterStorePseudo: {
650 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
651 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
652 MachineInstrBuilder MIB =
653 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
655 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
656 MIB.addOperand(MI->getOperand(i));
658 MI->eraseFromParent();
661 case AMDGPU::FCLAMP_SI: {
662 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
663 getTargetMachine().getSubtargetImpl()->getInstrInfo());
664 DebugLoc DL = MI->getDebugLoc();
665 unsigned DestReg = MI->getOperand(0).getReg();
666 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
667 .addImm(0) // SRC0 modifiers
668 .addOperand(MI->getOperand(1))
669 .addImm(0) // SRC1 modifiers
673 MI->eraseFromParent();
679 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
680 if (!VT.isVector()) {
683 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
686 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
690 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
691 VT = VT.getScalarType();
696 switch (VT.getSimpleVT().SimpleTy) {
698 return false; /* There is V_MAD_F32 for f32 */
708 //===----------------------------------------------------------------------===//
709 // Custom DAG Lowering Operations
710 //===----------------------------------------------------------------------===//
712 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
713 switch (Op.getOpcode()) {
714 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
715 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
716 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
718 SDValue Result = LowerLOAD(Op, DAG);
719 assert((!Result.getNode() ||
720 Result.getNode()->getNumValues() == 2) &&
721 "Load should return a value and a chain");
727 return LowerTrig(Op, DAG);
728 case ISD::SELECT: return LowerSELECT(Op, DAG);
729 case ISD::FDIV: return LowerFDIV(Op, DAG);
730 case ISD::STORE: return LowerSTORE(Op, DAG);
731 case ISD::GlobalAddress: {
732 MachineFunction &MF = DAG.getMachineFunction();
733 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
734 return LowerGlobalAddress(MFI, Op, DAG);
736 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
737 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
742 /// \brief Helper function for LowerBRCOND
743 static SDNode *findUser(SDValue Value, unsigned Opcode) {
745 SDNode *Parent = Value.getNode();
746 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
749 if (I.getUse().get() != Value)
752 if (I->getOpcode() == Opcode)
758 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
760 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
761 unsigned FrameIndex = FINode->getIndex();
763 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
766 /// This transforms the control flow intrinsics to get the branch destination as
767 /// last parameter, also switches branch target with BR if the need arise
768 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
769 SelectionDAG &DAG) const {
773 SDNode *Intr = BRCOND.getOperand(1).getNode();
774 SDValue Target = BRCOND.getOperand(2);
775 SDNode *BR = nullptr;
777 if (Intr->getOpcode() == ISD::SETCC) {
778 // As long as we negate the condition everything is fine
779 SDNode *SetCC = Intr;
780 assert(SetCC->getConstantOperandVal(1) == 1);
781 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
783 Intr = SetCC->getOperand(0).getNode();
786 // Get the target from BR if we don't negate the condition
787 BR = findUser(BRCOND, ISD::BR);
788 Target = BR->getOperand(1);
791 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
793 // Build the result and
794 SmallVector<EVT, 4> Res;
795 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
796 Res.push_back(Intr->getValueType(i));
798 // operands of the new intrinsic call
799 SmallVector<SDValue, 4> Ops;
800 Ops.push_back(BRCOND.getOperand(0));
801 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
802 Ops.push_back(Intr->getOperand(i));
803 Ops.push_back(Target);
805 // build the new intrinsic call
806 SDNode *Result = DAG.getNode(
807 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
808 DAG.getVTList(Res), Ops).getNode();
811 // Give the branch instruction our target
816 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
817 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
818 BR = NewBR.getNode();
821 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
823 // Copy the intrinsic results to registers
824 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
825 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
829 Chain = DAG.getCopyToReg(
831 CopyToReg->getOperand(1),
832 SDValue(Result, i - 1),
835 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
838 // Remove the old intrinsic from the chain
839 DAG.ReplaceAllUsesOfValueWith(
840 SDValue(Intr, Intr->getNumValues() - 1),
841 Intr->getOperand(0));
846 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
848 SelectionDAG &DAG) const {
849 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
851 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
852 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
855 const GlobalValue *GV = GSD->getGlobal();
856 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
858 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
859 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
861 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
862 DAG.getConstant(0, MVT::i32));
863 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
864 DAG.getConstant(1, MVT::i32));
866 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
868 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
869 PtrHi, DAG.getConstant(0, MVT::i32),
870 SDValue(Lo.getNode(), 1));
871 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
874 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
875 SelectionDAG &DAG) const {
876 MachineFunction &MF = DAG.getMachineFunction();
877 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
879 EVT VT = Op.getValueType();
881 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
883 switch (IntrinsicID) {
884 case Intrinsic::r600_read_ngroups_x:
885 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
886 case Intrinsic::r600_read_ngroups_y:
887 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
888 case Intrinsic::r600_read_ngroups_z:
889 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
890 case Intrinsic::r600_read_global_size_x:
891 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
892 case Intrinsic::r600_read_global_size_y:
893 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
894 case Intrinsic::r600_read_global_size_z:
895 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
896 case Intrinsic::r600_read_local_size_x:
897 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
898 case Intrinsic::r600_read_local_size_y:
899 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
900 case Intrinsic::r600_read_local_size_z:
901 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
902 case Intrinsic::r600_read_tgid_x:
903 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
904 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
905 case Intrinsic::r600_read_tgid_y:
906 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
907 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
908 case Intrinsic::r600_read_tgid_z:
909 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
910 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
911 case Intrinsic::r600_read_tidig_x:
912 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
914 case Intrinsic::r600_read_tidig_y:
915 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
917 case Intrinsic::r600_read_tidig_z:
918 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
920 case AMDGPUIntrinsic::SI_load_const: {
926 MachineMemOperand *MMO = MF.getMachineMemOperand(
927 MachinePointerInfo(),
928 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
929 VT.getStoreSize(), 4);
930 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
931 Op->getVTList(), Ops, VT, MMO);
933 case AMDGPUIntrinsic::SI_sample:
934 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
935 case AMDGPUIntrinsic::SI_sampleb:
936 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
937 case AMDGPUIntrinsic::SI_sampled:
938 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
939 case AMDGPUIntrinsic::SI_samplel:
940 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
941 case AMDGPUIntrinsic::SI_vs_load_input:
942 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
947 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
951 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
952 SelectionDAG &DAG) const {
953 MachineFunction &MF = DAG.getMachineFunction();
954 SDValue Chain = Op.getOperand(0);
955 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
957 switch (IntrinsicID) {
958 case AMDGPUIntrinsic::SI_tbuffer_store: {
977 EVT VT = Op.getOperand(3).getValueType();
979 MachineMemOperand *MMO = MF.getMachineMemOperand(
980 MachinePointerInfo(),
981 MachineMemOperand::MOStore,
982 VT.getStoreSize(), 4);
983 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
984 Op->getVTList(), Ops, VT, MMO);
991 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
993 LoadSDNode *Load = cast<LoadSDNode>(Op);
995 if (Op.getValueType().isVector()) {
996 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
997 "Custom lowering for non-i32 vectors hasn't been implemented.");
998 unsigned NumElements = Op.getValueType().getVectorNumElements();
999 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1000 switch (Load->getAddressSpace()) {
1002 case AMDGPUAS::GLOBAL_ADDRESS:
1003 case AMDGPUAS::PRIVATE_ADDRESS:
1004 // v4 loads are supported for private and global memory.
1005 if (NumElements <= 4)
1008 case AMDGPUAS::LOCAL_ADDRESS:
1009 return ScalarizeVectorLoad(Op, DAG);
1013 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1016 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1018 SelectionDAG &DAG) const {
1019 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1025 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1026 if (Op.getValueType() != MVT::i64)
1030 SDValue Cond = Op.getOperand(0);
1032 SDValue Zero = DAG.getConstant(0, MVT::i32);
1033 SDValue One = DAG.getConstant(1, MVT::i32);
1035 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1036 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1038 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1039 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1041 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1043 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1044 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1046 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1048 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1049 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1052 // Catch division cases where we can use shortcuts with rcp and rsq
1054 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1056 SDValue LHS = Op.getOperand(0);
1057 SDValue RHS = Op.getOperand(1);
1058 EVT VT = Op.getValueType();
1059 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1061 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1062 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1063 CLHS->isExactlyValue(1.0)) {
1064 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1065 // the CI documentation has a worst case error of 1 ulp.
1066 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1067 // use it as long as we aren't trying to use denormals.
1069 // 1.0 / sqrt(x) -> rsq(x)
1071 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1072 // error seems really high at 2^29 ULP.
1073 if (RHS.getOpcode() == ISD::FSQRT)
1074 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1076 // 1.0 / x -> rcp(x)
1077 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1082 // Turn into multiply by the reciprocal.
1083 // x / y -> x * (1.0 / y)
1084 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1085 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1091 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1092 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1093 if (FastLowered.getNode())
1096 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1097 // selection error for now rather than do something incorrect.
1098 if (Subtarget->hasFP32Denormals())
1102 SDValue LHS = Op.getOperand(0);
1103 SDValue RHS = Op.getOperand(1);
1105 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1107 const APFloat K0Val(BitsToFloat(0x6f800000));
1108 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1110 const APFloat K1Val(BitsToFloat(0x2f800000));
1111 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1113 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1115 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1117 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1119 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1121 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1123 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1125 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1127 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1130 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1134 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1135 EVT VT = Op.getValueType();
1138 return LowerFDIV32(Op, DAG);
1141 return LowerFDIV64(Op, DAG);
1143 llvm_unreachable("Unexpected type for fdiv");
1146 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1148 StoreSDNode *Store = cast<StoreSDNode>(Op);
1149 EVT VT = Store->getMemoryVT();
1151 // These stores are legal.
1152 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1153 VT.isVector() && VT.getVectorNumElements() == 2 &&
1154 VT.getVectorElementType() == MVT::i32)
1157 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1158 if (VT.isVector() && VT.getVectorNumElements() > 4)
1159 return ScalarizeVectorStore(Op, DAG);
1163 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1167 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1168 return ScalarizeVectorStore(Op, DAG);
1171 return DAG.getTruncStore(Store->getChain(), DL,
1172 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1173 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1178 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1179 EVT VT = Op.getValueType();
1180 SDValue Arg = Op.getOperand(0);
1181 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1182 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1183 DAG.getConstantFP(0.5 / M_PI, VT)));
1185 switch (Op.getOpcode()) {
1187 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1189 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1191 llvm_unreachable("Wrong trig opcode");
1195 //===----------------------------------------------------------------------===//
1196 // Custom DAG optimizations
1197 //===----------------------------------------------------------------------===//
1199 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1200 DAGCombinerInfo &DCI) {
1201 EVT VT = N->getValueType(0);
1202 EVT ScalarVT = VT.getScalarType();
1203 if (ScalarVT != MVT::f32)
1206 SelectionDAG &DAG = DCI.DAG;
1209 SDValue Src = N->getOperand(0);
1210 EVT SrcVT = Src.getValueType();
1212 // TODO: We could try to match extracting the higher bytes, which would be
1213 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1214 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1215 // about in practice.
1216 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1217 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1218 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1219 DCI.AddToWorklist(Cvt.getNode());
1224 // We are primarily trying to catch operations on illegal vector types
1225 // before they are expanded.
1226 // For scalars, we can use the more flexible method of checking masked bits
1227 // after legalization.
1228 if (!DCI.isBeforeLegalize() ||
1229 !SrcVT.isVector() ||
1230 SrcVT.getVectorElementType() != MVT::i8) {
1234 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1236 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1238 unsigned NElts = SrcVT.getVectorNumElements();
1239 if (!SrcVT.isSimple() && NElts != 3)
1242 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1243 // prevent a mess from expanding to v4i32 and repacking.
1244 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1245 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1246 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1247 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1249 LoadSDNode *Load = cast<LoadSDNode>(Src);
1250 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1254 Load->getMemOperand());
1256 // Make sure successors of the original load stay after it by updating
1257 // them to use the new Chain.
1258 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1260 SmallVector<SDValue, 4> Elts;
1261 if (RegVT.isVector())
1262 DAG.ExtractVectorElements(NewLoad, Elts);
1264 Elts.push_back(NewLoad);
1266 SmallVector<SDValue, 4> Ops;
1268 unsigned EltIdx = 0;
1269 for (SDValue Elt : Elts) {
1270 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1271 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1272 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1273 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1274 DCI.AddToWorklist(Cvt.getNode());
1281 assert(Ops.size() == NElts);
1283 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1289 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1291 // This is a variant of
1292 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1294 // The normal DAG combiner will do this, but only if the add has one use since
1295 // that would increase the number of instructions.
1297 // This prevents us from seeing a constant offset that can be folded into a
1298 // memory instruction's addressing mode. If we know the resulting add offset of
1299 // a pointer can be folded into an addressing offset, we can replace the pointer
1300 // operand with the add of new constant offset. This eliminates one of the uses,
1301 // and may allow the remaining use to also be simplified.
1303 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1305 DAGCombinerInfo &DCI) const {
1306 SDValue N0 = N->getOperand(0);
1307 SDValue N1 = N->getOperand(1);
1309 if (N0.getOpcode() != ISD::ADD)
1312 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1316 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1320 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1321 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1323 // If the resulting offset is too large, we can't fold it into the addressing
1325 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1326 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1329 SelectionDAG &DAG = DCI.DAG;
1331 EVT VT = N->getValueType(0);
1333 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1334 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1336 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1339 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1340 DAGCombinerInfo &DCI) const {
1341 SelectionDAG &DAG = DCI.DAG;
1343 EVT VT = N->getValueType(0);
1345 switch (N->getOpcode()) {
1346 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1348 SDValue Arg0 = N->getOperand(0);
1349 SDValue Arg1 = N->getOperand(1);
1350 SDValue CC = N->getOperand(2);
1351 ConstantSDNode * C = nullptr;
1352 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1354 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1356 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1357 && Arg0.getOperand(0).getValueType() == MVT::i1
1358 && (C = dyn_cast<ConstantSDNode>(Arg1))
1360 && CCOp == ISD::SETNE) {
1361 return SimplifySetCC(VT, Arg0.getOperand(0),
1362 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1367 case AMDGPUISD::CVT_F32_UBYTE0:
1368 case AMDGPUISD::CVT_F32_UBYTE1:
1369 case AMDGPUISD::CVT_F32_UBYTE2:
1370 case AMDGPUISD::CVT_F32_UBYTE3: {
1371 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1373 SDValue Src = N->getOperand(0);
1374 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1376 APInt KnownZero, KnownOne;
1377 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1378 !DCI.isBeforeLegalizeOps());
1379 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1380 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1381 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1382 DCI.CommitTargetLoweringOpt(TLO);
1388 case ISD::UINT_TO_FP: {
1389 return performUCharToFloatCombine(N, DCI);
1392 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1395 EVT VT = N->getValueType(0);
1397 // Try to get the fneg to fold into the source modifier. This undoes generic
1398 // DAG combines and folds them into the mad.
1399 if (VT == MVT::f32) {
1400 SDValue LHS = N->getOperand(0);
1401 SDValue RHS = N->getOperand(1);
1403 if (LHS.getOpcode() == ISD::FMUL) {
1404 // (fsub (fmul a, b), c) -> mad a, b, (fneg c)
1406 SDValue A = LHS.getOperand(0);
1407 SDValue B = LHS.getOperand(1);
1408 SDValue C = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1410 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1413 if (RHS.getOpcode() == ISD::FMUL) {
1414 // (fsub c, (fmul a, b)) -> mad (fneg a), b, c
1416 SDValue A = DAG.getNode(ISD::FNEG, DL, VT, RHS.getOperand(0));
1417 SDValue B = RHS.getOperand(1);
1420 return DAG.getNode(AMDGPUISD::MAD, DL, VT, A, B, C);
1429 case ISD::ATOMIC_LOAD:
1430 case ISD::ATOMIC_STORE:
1431 case ISD::ATOMIC_CMP_SWAP:
1432 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1433 case ISD::ATOMIC_SWAP:
1434 case ISD::ATOMIC_LOAD_ADD:
1435 case ISD::ATOMIC_LOAD_SUB:
1436 case ISD::ATOMIC_LOAD_AND:
1437 case ISD::ATOMIC_LOAD_OR:
1438 case ISD::ATOMIC_LOAD_XOR:
1439 case ISD::ATOMIC_LOAD_NAND:
1440 case ISD::ATOMIC_LOAD_MIN:
1441 case ISD::ATOMIC_LOAD_MAX:
1442 case ISD::ATOMIC_LOAD_UMIN:
1443 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1444 if (DCI.isBeforeLegalize())
1447 MemSDNode *MemNode = cast<MemSDNode>(N);
1448 SDValue Ptr = MemNode->getBasePtr();
1450 // TODO: We could also do this for multiplies.
1451 unsigned AS = MemNode->getAddressSpace();
1452 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1453 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1455 SmallVector<SDValue, 8> NewOps;
1456 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1457 NewOps.push_back(MemNode->getOperand(I));
1459 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1460 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1466 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1469 /// \brief Test if RegClass is one of the VSrc classes
1470 static bool isVSrc(unsigned RegClass) {
1471 return AMDGPU::VSrc_32RegClassID == RegClass ||
1472 AMDGPU::VSrc_64RegClassID == RegClass;
1475 /// \brief Test if RegClass is one of the SSrc classes
1476 static bool isSSrc(unsigned RegClass) {
1477 return AMDGPU::SSrc_32RegClassID == RegClass ||
1478 AMDGPU::SSrc_64RegClassID == RegClass;
1481 /// \brief Analyze the possible immediate value Op
1483 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1484 /// and the immediate value if it's a literal immediate
1485 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1492 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1493 if (Node->getZExtValue() >> 32) {
1496 Imm.I = Node->getSExtValue();
1497 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1498 if (N->getValueType(0) != MVT::f32)
1500 Imm.F = Node->getValueAPF().convertToFloat();
1502 return -1; // It isn't an immediate
1504 if ((Imm.I >= -16 && Imm.I <= 64) ||
1505 Imm.F == 0.5f || Imm.F == -0.5f ||
1506 Imm.F == 1.0f || Imm.F == -1.0f ||
1507 Imm.F == 2.0f || Imm.F == -2.0f ||
1508 Imm.F == 4.0f || Imm.F == -4.0f)
1509 return 0; // It's an inline immediate
1511 return Imm.I; // It's a literal immediate
1514 /// \brief Try to fold an immediate directly into an instruction
1515 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1516 bool &ScalarSlotUsed) const {
1518 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1519 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1520 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1521 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1524 const SDValue &Op = Mov->getOperand(0);
1525 int32_t Value = analyzeImmediate(Op.getNode());
1527 // Not an immediate at all
1530 } else if (Value == 0) {
1531 // Inline immediates can always be fold
1535 } else if (Value == Immediate) {
1536 // Already fold literal immediate
1540 } else if (!ScalarSlotUsed && !Immediate) {
1541 // Fold this literal immediate
1542 ScalarSlotUsed = true;
1552 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1553 SelectionDAG &DAG, const SDValue &Op) const {
1554 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1555 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1556 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1558 if (!Op->isMachineOpcode()) {
1559 switch(Op->getOpcode()) {
1560 case ISD::CopyFromReg: {
1561 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1562 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1563 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1564 return MRI.getRegClass(Reg);
1566 return TRI.getPhysRegClass(Reg);
1568 default: return nullptr;
1571 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1572 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1573 if (OpClassID != -1) {
1574 return TRI.getRegClass(OpClassID);
1576 switch(Op.getMachineOpcode()) {
1577 case AMDGPU::COPY_TO_REGCLASS:
1578 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1579 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1581 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1582 // class, then the register class for the value could be either a
1583 // VReg or and SReg. In order to get a more accurate
1584 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1585 OpClassID == AMDGPU::VSrc_64RegClassID) {
1586 return getRegClassForNode(DAG, Op.getOperand(0));
1588 return TRI.getRegClass(OpClassID);
1589 case AMDGPU::EXTRACT_SUBREG: {
1590 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1591 const TargetRegisterClass *SuperClass =
1592 getRegClassForNode(DAG, Op.getOperand(0));
1593 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1595 case AMDGPU::REG_SEQUENCE:
1596 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1597 return TRI.getRegClass(
1598 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1600 return getRegClassFor(Op.getSimpleValueType());
1604 /// \brief Does "Op" fit into register class "RegClass" ?
1605 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1606 unsigned RegClass) const {
1607 const TargetRegisterInfo *TRI =
1608 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1609 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1613 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1616 /// \brief Make sure that we don't exeed the number of allowed scalars
1617 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1619 bool &ScalarSlotUsed) const {
1621 // First map the operands register class to a destination class
1622 if (RegClass == AMDGPU::VSrc_32RegClassID)
1623 RegClass = AMDGPU::VReg_32RegClassID;
1624 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1625 RegClass = AMDGPU::VReg_64RegClassID;
1629 // Nothing to do if they fit naturally
1630 if (fitsRegClass(DAG, Operand, RegClass))
1633 // If the scalar slot isn't used yet use it now
1634 if (!ScalarSlotUsed) {
1635 ScalarSlotUsed = true;
1639 // This is a conservative aproach. It is possible that we can't determine the
1640 // correct register class and copy too often, but better safe than sorry.
1643 // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1644 if (isa<FrameIndexSDNode>(Operand) ||
1645 isa<GlobalAddressSDNode>(Operand)) {
1646 unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1647 AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1648 Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1651 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1652 Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1653 Operand.getValueType(), Operand, RC);
1655 Operand = SDValue(Node, 0);
1658 /// \returns true if \p Node's operands are different from the SDValue list
1660 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1661 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1662 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1669 /// \brief Try to fold the Nodes operands into the Node
1670 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1671 SelectionDAG &DAG) const {
1673 // Original encoding (either e32 or e64)
1674 int Opcode = Node->getMachineOpcode();
1675 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1676 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1677 const MCInstrDesc *Desc = &TII->get(Opcode);
1679 unsigned NumDefs = Desc->getNumDefs();
1680 unsigned NumOps = Desc->getNumOperands();
1682 // Commuted opcode if available
1683 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1684 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1686 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1687 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1689 // e64 version if available, -1 otherwise
1690 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1691 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1692 int InputModifiers[3] = {0};
1694 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1696 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1697 bool HaveVSrc = false, HaveSSrc = false;
1699 // First figure out what we already have in this instruction.
1700 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1701 i != e && Op < NumOps; ++i, ++Op) {
1703 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1704 if (isVSrc(RegClass))
1706 else if (isSSrc(RegClass))
1711 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1712 if (Imm != -1 && Imm != 0) {
1713 // Literal immediate
1718 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1719 if (!HaveVSrc && !HaveSSrc)
1722 // No scalar allowed when we have both VSrc and SSrc
1723 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1725 // Second go over the operands and try to fold them
1726 std::vector<SDValue> Ops;
1727 bool Promote2e64 = false;
1728 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1729 i != e && Op < NumOps; ++i, ++Op) {
1731 const SDValue &Operand = Node->getOperand(i);
1732 Ops.push_back(Operand);
1734 // Already folded immediate?
1735 if (isa<ConstantSDNode>(Operand.getNode()) ||
1736 isa<ConstantFPSDNode>(Operand.getNode()))
1739 // Is this a VSrc or SSrc operand?
1740 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1741 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1742 // Try to fold the immediates
1743 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1744 // Folding didn't work, make sure we don't hit the SReg limit.
1745 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1749 // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1750 // These will be lowered to immediates, so we will need to insert a MOV.
1751 if (isa<GlobalAddressSDNode>(Ops[i])) {
1752 SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1753 Operand.getValueType(), Operand);
1754 Ops[i] = SDValue(Node, 0);
1758 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1760 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1761 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1763 // Test if it makes sense to swap operands
1764 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1765 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1766 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1768 // Swap commutable operands
1769 std::swap(Ops[0], Ops[1]);
1781 // Test if it makes sense to switch to e64 encoding
1782 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1783 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1786 int32_t TmpImm = -1;
1787 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1788 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1789 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1791 // Switch to e64 encoding
1799 if (!DescE64 && !Promote2e64)
1801 if (!Operand.isMachineOpcode())
1806 std::vector<SDValue> OldOps(Ops);
1808 bool HasModifiers = TII->hasModifiers(Desc->Opcode);
1809 for (unsigned i = 0; i < OldOps.size(); ++i) {
1812 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1813 Ops.push_back(OldOps[i]);
1815 // Add the modifier flags while promoting
1817 for (unsigned i = 0; i < 2; ++i)
1818 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1822 // Add optional chain and glue
1823 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1824 Ops.push_back(Node->getOperand(i));
1826 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1827 // this case a brand new node is always be created, even if the operands
1828 // are the same as before. So, manually check if anything has been changed.
1829 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1833 // Create a complete new instruction
1834 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1837 /// \brief Helper function for adjustWritemask
1838 static unsigned SubIdx2Lane(unsigned Idx) {
1841 case AMDGPU::sub0: return 0;
1842 case AMDGPU::sub1: return 1;
1843 case AMDGPU::sub2: return 2;
1844 case AMDGPU::sub3: return 3;
1848 /// \brief Adjust the writemask of MIMG instructions
1849 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1850 SelectionDAG &DAG) const {
1851 SDNode *Users[4] = { };
1853 unsigned OldDmask = Node->getConstantOperandVal(0);
1854 unsigned NewDmask = 0;
1856 // Try to figure out the used register components
1857 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1860 // Abort if we can't understand the usage
1861 if (!I->isMachineOpcode() ||
1862 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1865 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1866 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1867 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1869 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1871 // Set which texture component corresponds to the lane.
1873 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1875 Comp = countTrailingZeros(Dmask);
1876 Dmask &= ~(1 << Comp);
1879 // Abort if we have more than one user per component
1884 NewDmask |= 1 << Comp;
1887 // Abort if there's no change
1888 if (NewDmask == OldDmask)
1891 // Adjust the writemask in the node
1892 std::vector<SDValue> Ops;
1893 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1894 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1895 Ops.push_back(Node->getOperand(i));
1896 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1898 // If we only got one lane, replace it with a copy
1899 // (if NewDmask has only one bit set...)
1900 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1901 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1902 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1903 SDLoc(), Users[Lane]->getValueType(0),
1904 SDValue(Node, 0), RC);
1905 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1909 // Update the users of the node with the new indices
1910 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1912 SDNode *User = Users[i];
1916 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1917 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1921 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1922 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1923 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1928 /// \brief Fold the instructions after selecting them.
1929 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1930 SelectionDAG &DAG) const {
1931 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1932 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1933 Node = AdjustRegClass(Node, DAG);
1935 if (TII->isMIMG(Node->getMachineOpcode()))
1936 adjustWritemask(Node, DAG);
1938 return foldOperands(Node, DAG);
1941 /// \brief Assign the register class depending on the number of
1942 /// bits set in the writemask
1943 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1944 SDNode *Node) const {
1945 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1946 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1948 if (TII->isMIMG(MI->getOpcode())) {
1949 unsigned VReg = MI->getOperand(0).getReg();
1950 unsigned Writemask = MI->getOperand(1).getImm();
1951 unsigned BitsSet = 0;
1952 for (unsigned i = 0; i < 4; ++i)
1953 BitsSet += Writemask & (1 << i) ? 1 : 0;
1955 const TargetRegisterClass *RC;
1958 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1959 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1960 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1963 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1964 MI->setDesc(TII->get(NewOpcode));
1965 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1966 MRI.setRegClass(VReg, RC);
1970 // Replace unused atomics with the no return version.
1971 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
1972 if (NoRetAtomicOp != -1) {
1973 if (!Node->hasAnyUseOfValue(0)) {
1974 MI->setDesc(TII->get(NoRetAtomicOp));
1975 MI->RemoveOperand(0);
1982 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1983 SelectionDAG &DAG) const {
1986 unsigned NewOpcode = N->getMachineOpcode();
1988 switch (N->getMachineOpcode()) {
1990 case AMDGPU::S_LOAD_DWORD_IMM:
1991 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1993 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1994 if (NewOpcode == N->getMachineOpcode()) {
1995 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1998 case AMDGPU::S_LOAD_DWORDX4_IMM:
1999 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2000 if (NewOpcode == N->getMachineOpcode()) {
2001 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2003 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2006 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2008 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
2009 DAG.getConstant(0, MVT::i64)), 0),
2011 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
2013 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2018 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2019 const TargetRegisterClass *RC,
2020 unsigned Reg, EVT VT) const {
2021 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2023 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2024 cast<RegisterSDNode>(VReg)->getReg(), VT);