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/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/ADT/SmallString.h"
37 SITargetLowering::SITargetLowering(TargetMachine &TM) :
38 AMDGPUTargetLowering(TM) {
39 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
40 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
42 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
43 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
45 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
46 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
48 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
49 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
50 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
52 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
53 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
55 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
56 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
58 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
59 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
61 computeRegisterProperties();
64 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
65 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
66 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
67 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
68 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
69 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
71 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
72 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
73 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
74 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
75 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
76 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
78 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
79 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
80 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
81 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
83 setOperationAction(ISD::ADD, MVT::i32, Legal);
84 setOperationAction(ISD::ADDC, MVT::i32, Legal);
85 setOperationAction(ISD::ADDE, MVT::i32, Legal);
86 setOperationAction(ISD::SUBC, MVT::i32, Legal);
87 setOperationAction(ISD::SUBE, MVT::i32, Legal);
89 setOperationAction(ISD::FSIN, MVT::f32, Custom);
90 setOperationAction(ISD::FCOS, MVT::f32, Custom);
92 // We need to custom lower vector stores from local memory
93 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
94 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
95 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
97 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
98 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
100 setOperationAction(ISD::STORE, MVT::i1, Custom);
101 setOperationAction(ISD::STORE, MVT::i32, Custom);
102 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
103 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
105 setOperationAction(ISD::SELECT, MVT::f32, Promote);
106 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
107 setOperationAction(ISD::SELECT, MVT::i64, Custom);
108 setOperationAction(ISD::SELECT, MVT::f64, Promote);
109 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
111 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
112 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
113 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
114 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
116 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
117 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
129 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
131 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
133 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
135 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
136 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
137 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
138 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
140 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
141 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
143 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
144 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
145 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
146 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
147 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
148 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
150 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
151 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
152 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
153 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
155 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
156 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
157 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
158 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
159 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
161 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
162 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
163 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
164 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
168 setOperationAction(ISD::LOAD, MVT::i1, Custom);
170 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Expand);
171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
173 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
174 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
175 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
177 // These should use UDIVREM, so set them to expand
178 setOperationAction(ISD::UDIV, MVT::i64, Expand);
179 setOperationAction(ISD::UREM, MVT::i64, Expand);
181 // We only support LOAD/STORE and vector manipulation ops for vectors
182 // with > 4 elements.
184 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
188 setOperationAction(ISD::SELECT, MVT::i1, Promote);
190 for (MVT VT : VecTypes) {
191 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
195 case ISD::BUILD_VECTOR:
197 case ISD::EXTRACT_VECTOR_ELT:
198 case ISD::INSERT_VECTOR_ELT:
199 case ISD::INSERT_SUBVECTOR:
200 case ISD::EXTRACT_SUBVECTOR:
202 case ISD::CONCAT_VECTORS:
203 setOperationAction(Op, VT, Custom);
206 setOperationAction(Op, VT, Expand);
212 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
213 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
214 setOperationAction(ISD::FTRUNC, VT, Expand);
215 setOperationAction(ISD::FCEIL, VT, Expand);
216 setOperationAction(ISD::FFLOOR, VT, Expand);
219 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
220 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
221 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
222 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
223 setOperationAction(ISD::FRINT, MVT::f64, Legal);
226 // FIXME: These should be removed and handled the same was as f32 fneg. Source
227 // modifiers also work for the double instructions.
228 setOperationAction(ISD::FNEG, MVT::f64, Expand);
230 setOperationAction(ISD::FDIV, MVT::f32, Custom);
232 setTargetDAGCombine(ISD::SELECT_CC);
233 setTargetDAGCombine(ISD::SETCC);
235 setTargetDAGCombine(ISD::UINT_TO_FP);
237 // All memory operations. Some folding on the pointer operand is done to help
238 // matching the constant offsets in the addressing modes.
239 setTargetDAGCombine(ISD::LOAD);
240 setTargetDAGCombine(ISD::STORE);
241 setTargetDAGCombine(ISD::ATOMIC_LOAD);
242 setTargetDAGCombine(ISD::ATOMIC_STORE);
243 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
244 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
245 setTargetDAGCombine(ISD::ATOMIC_SWAP);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
255 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
257 setSchedulingPreference(Sched::RegPressure);
260 //===----------------------------------------------------------------------===//
261 // TargetLowering queries
262 //===----------------------------------------------------------------------===//
264 // FIXME: This really needs an address space argument. The immediate offset
265 // size is different for different sets of memory instruction sets.
267 // The single offset DS instructions have a 16-bit unsigned byte offset.
269 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
270 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
271 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
273 // SMRD instructions have an 8-bit, dword offset.
275 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
277 // No global is ever allowed as a base.
281 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
283 if (!isUInt<16>(AM.BaseOffs))
288 case 0: // "r+i" or just "i", depending on HasBaseReg.
291 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
293 // Otherwise we have r+r or r+i.
296 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
300 default: // Don't allow n * r
307 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
310 bool *IsFast) const {
314 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
315 // which isn't a simple VT.
316 if (!VT.isSimple() || VT == MVT::Other)
319 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
320 // see what for specifically. The wording everywhere else seems to be the
323 // XXX - The only mention I see of this in the ISA manual is for LDS direct
324 // reads the "byte address and must be dword aligned". Is it also true for the
325 // normal loads and stores?
326 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
327 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
328 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
329 // with adjacent offsets.
330 return Align % 4 == 0;
333 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
334 // byte-address are ignored, thus forcing Dword alignment.
335 // This applies to private, global, and constant memory.
338 return VT.bitsGT(MVT::i32);
341 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
342 unsigned SrcAlign, bool IsMemset,
345 MachineFunction &MF) const {
346 // FIXME: Should account for address space here.
348 // The default fallback uses the private pointer size as a guess for a type to
349 // use. Make sure we switch these to 64-bit accesses.
351 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
354 if (Size >= 8 && DstAlign >= 4)
361 TargetLoweringBase::LegalizeTypeAction
362 SITargetLowering::getPreferredVectorAction(EVT VT) const {
363 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
364 return TypeSplitVector;
366 return TargetLoweringBase::getPreferredVectorAction(VT);
369 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
371 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
372 getTargetMachine().getSubtargetImpl()->getInstrInfo());
373 return TII->isInlineConstant(Imm);
376 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
377 SDLoc SL, SDValue Chain,
378 unsigned Offset, bool Signed) const {
379 const DataLayout *DL = getDataLayout();
381 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
383 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
384 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
385 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
386 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
387 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
388 DAG.getConstant(Offset, MVT::i64));
389 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
390 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
392 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
393 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
395 true, // isNonTemporal
397 DL->getABITypeAlignment(Ty)); // Alignment
400 SDValue SITargetLowering::LowerFormalArguments(
402 CallingConv::ID CallConv,
404 const SmallVectorImpl<ISD::InputArg> &Ins,
405 SDLoc DL, SelectionDAG &DAG,
406 SmallVectorImpl<SDValue> &InVals) const {
408 const TargetRegisterInfo *TRI =
409 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
411 MachineFunction &MF = DAG.getMachineFunction();
412 FunctionType *FType = MF.getFunction()->getFunctionType();
413 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
415 assert(CallConv == CallingConv::C);
417 SmallVector<ISD::InputArg, 16> Splits;
418 uint32_t Skipped = 0;
420 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
421 const ISD::InputArg &Arg = Ins[i];
423 // First check if it's a PS input addr
424 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
425 !Arg.Flags.isByVal()) {
427 assert((PSInputNum <= 15) && "Too many PS inputs!");
430 // We can savely skip PS inputs
436 Info->PSInputAddr |= 1 << PSInputNum++;
439 // Second split vertices into their elements
440 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
441 ISD::InputArg NewArg = Arg;
442 NewArg.Flags.setSplit();
443 NewArg.VT = Arg.VT.getVectorElementType();
445 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
446 // three or five element vertex only needs three or five registers,
447 // NOT four or eigth.
448 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
449 unsigned NumElements = ParamType->getVectorNumElements();
451 for (unsigned j = 0; j != NumElements; ++j) {
452 Splits.push_back(NewArg);
453 NewArg.PartOffset += NewArg.VT.getStoreSize();
456 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
457 Splits.push_back(Arg);
461 SmallVector<CCValAssign, 16> ArgLocs;
462 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
465 // At least one interpolation mode must be enabled or else the GPU will hang.
466 if (Info->getShaderType() == ShaderType::PIXEL &&
467 (Info->PSInputAddr & 0x7F) == 0) {
468 Info->PSInputAddr |= 1;
469 CCInfo.AllocateReg(AMDGPU::VGPR0);
470 CCInfo.AllocateReg(AMDGPU::VGPR1);
473 // The pointer to the list of arguments is stored in SGPR0, SGPR1
474 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
475 if (Info->getShaderType() == ShaderType::COMPUTE) {
476 Info->NumUserSGPRs = 4;
477 CCInfo.AllocateReg(AMDGPU::SGPR0);
478 CCInfo.AllocateReg(AMDGPU::SGPR1);
479 CCInfo.AllocateReg(AMDGPU::SGPR2);
480 CCInfo.AllocateReg(AMDGPU::SGPR3);
481 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
482 MF.addLiveIn(AMDGPU::SGPR2_SGPR3, &AMDGPU::SReg_64RegClass);
485 if (Info->getShaderType() == ShaderType::COMPUTE) {
486 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
490 AnalyzeFormalArguments(CCInfo, Splits);
492 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
494 const ISD::InputArg &Arg = Ins[i];
495 if (Skipped & (1 << i)) {
496 InVals.push_back(DAG.getUNDEF(Arg.VT));
500 CCValAssign &VA = ArgLocs[ArgIdx++];
501 EVT VT = VA.getLocVT();
505 EVT MemVT = Splits[i].VT;
506 // The first 36 bytes of the input buffer contains information about
507 // thread group and global sizes.
508 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
509 36 + VA.getLocMemOffset(),
510 Ins[i].Flags.isSExt());
511 InVals.push_back(Arg);
514 assert(VA.isRegLoc() && "Parameter must be in a register!");
516 unsigned Reg = VA.getLocReg();
518 if (VT == MVT::i64) {
519 // For now assume it is a pointer
520 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
521 &AMDGPU::SReg_64RegClass);
522 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
523 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
527 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
529 Reg = MF.addLiveIn(Reg, RC);
530 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
532 if (Arg.VT.isVector()) {
534 // Build a vector from the registers
535 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
536 unsigned NumElements = ParamType->getVectorNumElements();
538 SmallVector<SDValue, 4> Regs;
540 for (unsigned j = 1; j != NumElements; ++j) {
541 Reg = ArgLocs[ArgIdx++].getLocReg();
542 Reg = MF.addLiveIn(Reg, RC);
543 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
546 // Fill up the missing vector elements
547 NumElements = Arg.VT.getVectorNumElements() - NumElements;
548 for (unsigned j = 0; j != NumElements; ++j)
549 Regs.push_back(DAG.getUNDEF(VT));
551 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
555 InVals.push_back(Val);
560 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
561 MachineInstr * MI, MachineBasicBlock * BB) const {
563 MachineBasicBlock::iterator I = *MI;
564 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
565 getTargetMachine().getSubtargetImpl()->getInstrInfo());
566 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
568 switch (MI->getOpcode()) {
570 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
571 case AMDGPU::BRANCH: return BB;
572 case AMDGPU::SI_ADDR64_RSRC: {
573 unsigned SuperReg = MI->getOperand(0).getReg();
574 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
575 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
576 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
577 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
578 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
579 .addOperand(MI->getOperand(1));
580 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
582 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
583 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
584 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
586 .addImm(AMDGPU::sub0)
588 .addImm(AMDGPU::sub1);
589 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
591 .addImm(AMDGPU::sub0_sub1)
593 .addImm(AMDGPU::sub2_sub3);
594 MI->eraseFromParent();
597 case AMDGPU::SI_BUFFER_RSRC: {
598 unsigned SuperReg = MI->getOperand(0).getReg();
600 for (unsigned i = 0, e = 4; i < e; ++i) {
601 MachineOperand &Arg = MI->getOperand(i + 1);
604 Args[i] = Arg.getReg();
609 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
610 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
611 .addImm(Arg.getImm());
614 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
617 .addImm(AMDGPU::sub0)
619 .addImm(AMDGPU::sub1)
621 .addImm(AMDGPU::sub2)
623 .addImm(AMDGPU::sub3);
624 MI->eraseFromParent();
627 case AMDGPU::V_SUB_F64: {
628 unsigned DestReg = MI->getOperand(0).getReg();
629 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
630 .addImm(0) // SRC0 modifiers
631 .addReg(MI->getOperand(1).getReg())
632 .addImm(1) // SRC1 modifiers
633 .addReg(MI->getOperand(2).getReg())
636 MI->eraseFromParent();
639 case AMDGPU::SI_RegisterStorePseudo: {
640 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
641 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
642 MachineInstrBuilder MIB =
643 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
645 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
646 MIB.addOperand(MI->getOperand(i));
648 MI->eraseFromParent();
651 case AMDGPU::FABS_SI: {
652 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
653 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
654 getTargetMachine().getSubtargetImpl()->getInstrInfo());
655 DebugLoc DL = MI->getDebugLoc();
656 unsigned DestReg = MI->getOperand(0).getReg();
657 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
659 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Reg)
661 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_AND_B32_e32), DestReg)
662 .addReg(MI->getOperand(1).getReg())
664 MI->eraseFromParent();
667 case AMDGPU::FABS64_SI: {
668 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
669 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
670 getTargetMachine().getSubtargetImpl()->getInstrInfo());
672 DebugLoc DL = MI->getDebugLoc();
673 unsigned SuperReg = MI->getOperand(0).getReg();
674 unsigned SrcReg = MI->getOperand(1).getReg();
676 unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
678 // Copy the subregister to make sure it is the right register class.
679 unsigned VReg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
680 BuildMI(*BB, I, DL, TII->get(AMDGPU::COPY), VReg)
681 .addReg(SrcReg, 0, AMDGPU::sub1);
683 // We only need to mask the upper half of the register pair.
684 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_AND_B32_e32), TmpReg)
688 BuildMI(*BB, I, DL, TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
689 .addReg(SrcReg, 0, AMDGPU::sub0)
690 .addImm(AMDGPU::sub0)
692 .addImm(AMDGPU::sub1);
693 MI->eraseFromParent();
696 case AMDGPU::FNEG_SI: {
697 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
698 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
699 getTargetMachine().getSubtargetImpl()->getInstrInfo());
700 DebugLoc DL = MI->getDebugLoc();
701 unsigned DestReg = MI->getOperand(0).getReg();
702 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
704 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Reg)
706 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_XOR_B32_e32), DestReg)
707 .addReg(MI->getOperand(1).getReg())
709 MI->eraseFromParent();
712 case AMDGPU::FCLAMP_SI: {
713 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
714 getTargetMachine().getSubtargetImpl()->getInstrInfo());
715 DebugLoc DL = MI->getDebugLoc();
716 unsigned DestReg = MI->getOperand(0).getReg();
717 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
718 .addImm(0) // SRC0 modifiers
719 .addOperand(MI->getOperand(1))
720 .addImm(0) // SRC1 modifiers
724 MI->eraseFromParent();
730 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
731 if (!VT.isVector()) {
734 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
737 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
741 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
742 VT = VT.getScalarType();
747 switch (VT.getSimpleVT().SimpleTy) {
749 return false; /* There is V_MAD_F32 for f32 */
759 //===----------------------------------------------------------------------===//
760 // Custom DAG Lowering Operations
761 //===----------------------------------------------------------------------===//
763 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
764 switch (Op.getOpcode()) {
765 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
766 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
767 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
769 SDValue Result = LowerLOAD(Op, DAG);
770 assert((!Result.getNode() ||
771 Result.getNode()->getNumValues() == 2) &&
772 "Load should return a value and a chain");
778 return LowerTrig(Op, DAG);
779 case ISD::SELECT: return LowerSELECT(Op, DAG);
780 case ISD::FDIV: return LowerFDIV(Op, DAG);
781 case ISD::STORE: return LowerSTORE(Op, DAG);
782 case ISD::GlobalAddress: {
783 MachineFunction &MF = DAG.getMachineFunction();
784 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
785 return LowerGlobalAddress(MFI, Op, DAG);
787 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
788 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
793 /// \brief Helper function for LowerBRCOND
794 static SDNode *findUser(SDValue Value, unsigned Opcode) {
796 SDNode *Parent = Value.getNode();
797 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
800 if (I.getUse().get() != Value)
803 if (I->getOpcode() == Opcode)
809 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
811 MachineFunction &MF = DAG.getMachineFunction();
812 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
813 getTargetMachine().getSubtargetImpl()->getInstrInfo());
814 const SIRegisterInfo &TRI = TII->getRegisterInfo();
815 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
816 unsigned FrameIndex = FINode->getIndex();
818 CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
819 TRI.getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET), MVT::i32);
821 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
824 /// This transforms the control flow intrinsics to get the branch destination as
825 /// last parameter, also switches branch target with BR if the need arise
826 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
827 SelectionDAG &DAG) const {
831 SDNode *Intr = BRCOND.getOperand(1).getNode();
832 SDValue Target = BRCOND.getOperand(2);
833 SDNode *BR = nullptr;
835 if (Intr->getOpcode() == ISD::SETCC) {
836 // As long as we negate the condition everything is fine
837 SDNode *SetCC = Intr;
838 assert(SetCC->getConstantOperandVal(1) == 1);
839 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
841 Intr = SetCC->getOperand(0).getNode();
844 // Get the target from BR if we don't negate the condition
845 BR = findUser(BRCOND, ISD::BR);
846 Target = BR->getOperand(1);
849 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
851 // Build the result and
852 SmallVector<EVT, 4> Res;
853 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
854 Res.push_back(Intr->getValueType(i));
856 // operands of the new intrinsic call
857 SmallVector<SDValue, 4> Ops;
858 Ops.push_back(BRCOND.getOperand(0));
859 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
860 Ops.push_back(Intr->getOperand(i));
861 Ops.push_back(Target);
863 // build the new intrinsic call
864 SDNode *Result = DAG.getNode(
865 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
866 DAG.getVTList(Res), Ops).getNode();
869 // Give the branch instruction our target
874 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
875 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
876 BR = NewBR.getNode();
879 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
881 // Copy the intrinsic results to registers
882 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
883 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
887 Chain = DAG.getCopyToReg(
889 CopyToReg->getOperand(1),
890 SDValue(Result, i - 1),
893 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
896 // Remove the old intrinsic from the chain
897 DAG.ReplaceAllUsesOfValueWith(
898 SDValue(Intr, Intr->getNumValues() - 1),
899 Intr->getOperand(0));
904 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
906 SelectionDAG &DAG) const {
907 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
909 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
910 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
913 const GlobalValue *GV = GSD->getGlobal();
914 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
916 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
917 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
919 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
920 DAG.getConstant(0, MVT::i32));
921 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
922 DAG.getConstant(1, MVT::i32));
924 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
926 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
927 PtrHi, DAG.getConstant(0, MVT::i32),
928 SDValue(Lo.getNode(), 1));
929 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
932 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
933 SelectionDAG &DAG) const {
934 MachineFunction &MF = DAG.getMachineFunction();
935 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
937 EVT VT = Op.getValueType();
939 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
941 switch (IntrinsicID) {
942 case Intrinsic::r600_read_ngroups_x:
943 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
944 case Intrinsic::r600_read_ngroups_y:
945 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
946 case Intrinsic::r600_read_ngroups_z:
947 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
948 case Intrinsic::r600_read_global_size_x:
949 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
950 case Intrinsic::r600_read_global_size_y:
951 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
952 case Intrinsic::r600_read_global_size_z:
953 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
954 case Intrinsic::r600_read_local_size_x:
955 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
956 case Intrinsic::r600_read_local_size_y:
957 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
958 case Intrinsic::r600_read_local_size_z:
959 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
960 case Intrinsic::r600_read_tgid_x:
961 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
962 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
963 case Intrinsic::r600_read_tgid_y:
964 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
965 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
966 case Intrinsic::r600_read_tgid_z:
967 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
968 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
969 case Intrinsic::r600_read_tidig_x:
970 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
972 case Intrinsic::r600_read_tidig_y:
973 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
975 case Intrinsic::r600_read_tidig_z:
976 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
978 case AMDGPUIntrinsic::SI_load_const: {
984 MachineMemOperand *MMO = MF.getMachineMemOperand(
985 MachinePointerInfo(),
986 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
987 VT.getStoreSize(), 4);
988 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
989 Op->getVTList(), Ops, VT, MMO);
991 case AMDGPUIntrinsic::SI_sample:
992 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
993 case AMDGPUIntrinsic::SI_sampleb:
994 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
995 case AMDGPUIntrinsic::SI_sampled:
996 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
997 case AMDGPUIntrinsic::SI_samplel:
998 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
999 case AMDGPUIntrinsic::SI_vs_load_input:
1000 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1005 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1009 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1010 SelectionDAG &DAG) const {
1011 MachineFunction &MF = DAG.getMachineFunction();
1012 SDValue Chain = Op.getOperand(0);
1013 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1015 switch (IntrinsicID) {
1016 case AMDGPUIntrinsic::SI_tbuffer_store: {
1035 EVT VT = Op.getOperand(3).getValueType();
1037 MachineMemOperand *MMO = MF.getMachineMemOperand(
1038 MachinePointerInfo(),
1039 MachineMemOperand::MOStore,
1040 VT.getStoreSize(), 4);
1041 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1042 Op->getVTList(), Ops, VT, MMO);
1049 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1051 LoadSDNode *Load = cast<LoadSDNode>(Op);
1053 if (Op.getValueType().isVector()) {
1054 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1055 "Custom lowering for non-i32 vectors hasn't been implemented.");
1056 unsigned NumElements = Op.getValueType().getVectorNumElements();
1057 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1058 switch (Load->getAddressSpace()) {
1060 case AMDGPUAS::GLOBAL_ADDRESS:
1061 case AMDGPUAS::PRIVATE_ADDRESS:
1062 // v4 loads are supported for private and global memory.
1063 if (NumElements <= 4)
1066 case AMDGPUAS::LOCAL_ADDRESS:
1067 return ScalarizeVectorLoad(Op, DAG);
1071 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1074 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1076 SelectionDAG &DAG) const {
1077 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1083 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1084 if (Op.getValueType() != MVT::i64)
1088 SDValue Cond = Op.getOperand(0);
1090 SDValue Zero = DAG.getConstant(0, MVT::i32);
1091 SDValue One = DAG.getConstant(1, MVT::i32);
1093 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1094 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1096 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1097 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1099 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1101 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1102 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1104 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1106 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1107 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1110 // Catch division cases where we can use shortcuts with rcp and rsq
1112 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1114 SDValue LHS = Op.getOperand(0);
1115 SDValue RHS = Op.getOperand(1);
1116 EVT VT = Op.getValueType();
1117 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1119 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1120 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1121 CLHS->isExactlyValue(1.0)) {
1122 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1123 // the CI documentation has a worst case error of 1 ulp.
1124 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1125 // use it as long as we aren't trying to use denormals.
1127 // 1.0 / sqrt(x) -> rsq(x)
1129 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1130 // error seems really high at 2^29 ULP.
1131 if (RHS.getOpcode() == ISD::FSQRT)
1132 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1134 // 1.0 / x -> rcp(x)
1135 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1140 // Turn into multiply by the reciprocal.
1141 // x / y -> x * (1.0 / y)
1142 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1143 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1149 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1150 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1151 if (FastLowered.getNode())
1154 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1155 // selection error for now rather than do something incorrect.
1156 if (Subtarget->hasFP32Denormals())
1160 SDValue LHS = Op.getOperand(0);
1161 SDValue RHS = Op.getOperand(1);
1163 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1165 const APFloat K0Val(BitsToFloat(0x6f800000));
1166 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1168 const APFloat K1Val(BitsToFloat(0x2f800000));
1169 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1171 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1173 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1175 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1177 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1179 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1181 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1183 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1185 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1188 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1192 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1193 EVT VT = Op.getValueType();
1196 return LowerFDIV32(Op, DAG);
1199 return LowerFDIV64(Op, DAG);
1201 llvm_unreachable("Unexpected type for fdiv");
1204 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1206 StoreSDNode *Store = cast<StoreSDNode>(Op);
1207 EVT VT = Store->getMemoryVT();
1209 // These stores are legal.
1210 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1211 VT.isVector() && VT.getVectorNumElements() == 2 &&
1212 VT.getVectorElementType() == MVT::i32)
1215 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1216 if (VT.isVector() && VT.getVectorNumElements() > 4)
1217 return ScalarizeVectorStore(Op, DAG);
1221 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1225 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1226 return ScalarizeVectorStore(Op, DAG);
1229 return DAG.getTruncStore(Store->getChain(), DL,
1230 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1231 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1236 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1237 EVT VT = Op.getValueType();
1238 SDValue Arg = Op.getOperand(0);
1239 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1240 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1241 DAG.getConstantFP(0.5 / M_PI, VT)));
1243 switch (Op.getOpcode()) {
1245 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1247 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1249 llvm_unreachable("Wrong trig opcode");
1253 //===----------------------------------------------------------------------===//
1254 // Custom DAG optimizations
1255 //===----------------------------------------------------------------------===//
1257 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1258 DAGCombinerInfo &DCI) {
1259 EVT VT = N->getValueType(0);
1260 EVT ScalarVT = VT.getScalarType();
1261 if (ScalarVT != MVT::f32)
1264 SelectionDAG &DAG = DCI.DAG;
1267 SDValue Src = N->getOperand(0);
1268 EVT SrcVT = Src.getValueType();
1270 // TODO: We could try to match extracting the higher bytes, which would be
1271 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1272 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1273 // about in practice.
1274 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1275 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1276 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1277 DCI.AddToWorklist(Cvt.getNode());
1282 // We are primarily trying to catch operations on illegal vector types
1283 // before they are expanded.
1284 // For scalars, we can use the more flexible method of checking masked bits
1285 // after legalization.
1286 if (!DCI.isBeforeLegalize() ||
1287 !SrcVT.isVector() ||
1288 SrcVT.getVectorElementType() != MVT::i8) {
1292 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1294 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1296 unsigned NElts = SrcVT.getVectorNumElements();
1297 if (!SrcVT.isSimple() && NElts != 3)
1300 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1301 // prevent a mess from expanding to v4i32 and repacking.
1302 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1303 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1304 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1305 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1307 LoadSDNode *Load = cast<LoadSDNode>(Src);
1308 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1312 Load->getMemOperand());
1314 // Make sure successors of the original load stay after it by updating
1315 // them to use the new Chain.
1316 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1318 SmallVector<SDValue, 4> Elts;
1319 if (RegVT.isVector())
1320 DAG.ExtractVectorElements(NewLoad, Elts);
1322 Elts.push_back(NewLoad);
1324 SmallVector<SDValue, 4> Ops;
1326 unsigned EltIdx = 0;
1327 for (SDValue Elt : Elts) {
1328 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1329 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1330 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1331 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1332 DCI.AddToWorklist(Cvt.getNode());
1339 assert(Ops.size() == NElts);
1341 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1347 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1349 // This is a variant of
1350 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1352 // The normal DAG combiner will do this, but only if the add has one use since
1353 // that would increase the number of instructions.
1355 // This prevents us from seeing a constant offset that can be folded into a
1356 // memory instruction's addressing mode. If we know the resulting add offset of
1357 // a pointer can be folded into an addressing offset, we can replace the pointer
1358 // operand with the add of new constant offset. This eliminates one of the uses,
1359 // and may allow the remaining use to also be simplified.
1361 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1363 DAGCombinerInfo &DCI) const {
1364 SDValue N0 = N->getOperand(0);
1365 SDValue N1 = N->getOperand(1);
1367 if (N0.getOpcode() != ISD::ADD)
1370 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1374 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1378 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1379 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1381 // If the resulting offset is too large, we can't fold it into the addressing
1383 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1384 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1387 SelectionDAG &DAG = DCI.DAG;
1389 EVT VT = N->getValueType(0);
1391 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1392 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1394 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1397 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1398 DAGCombinerInfo &DCI) const {
1399 SelectionDAG &DAG = DCI.DAG;
1401 EVT VT = N->getValueType(0);
1403 switch (N->getOpcode()) {
1404 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1406 SDValue Arg0 = N->getOperand(0);
1407 SDValue Arg1 = N->getOperand(1);
1408 SDValue CC = N->getOperand(2);
1409 ConstantSDNode * C = nullptr;
1410 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1412 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1414 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1415 && Arg0.getOperand(0).getValueType() == MVT::i1
1416 && (C = dyn_cast<ConstantSDNode>(Arg1))
1418 && CCOp == ISD::SETNE) {
1419 return SimplifySetCC(VT, Arg0.getOperand(0),
1420 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1425 case AMDGPUISD::CVT_F32_UBYTE0:
1426 case AMDGPUISD::CVT_F32_UBYTE1:
1427 case AMDGPUISD::CVT_F32_UBYTE2:
1428 case AMDGPUISD::CVT_F32_UBYTE3: {
1429 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1431 SDValue Src = N->getOperand(0);
1432 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1434 APInt KnownZero, KnownOne;
1435 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1436 !DCI.isBeforeLegalizeOps());
1437 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1438 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1439 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1440 DCI.CommitTargetLoweringOpt(TLO);
1446 case ISD::UINT_TO_FP: {
1447 return performUCharToFloatCombine(N, DCI);
1451 case ISD::ATOMIC_LOAD:
1452 case ISD::ATOMIC_STORE:
1453 case ISD::ATOMIC_CMP_SWAP:
1454 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1455 case ISD::ATOMIC_SWAP:
1456 case ISD::ATOMIC_LOAD_ADD:
1457 case ISD::ATOMIC_LOAD_SUB:
1458 case ISD::ATOMIC_LOAD_AND:
1459 case ISD::ATOMIC_LOAD_OR:
1460 case ISD::ATOMIC_LOAD_XOR:
1461 case ISD::ATOMIC_LOAD_NAND:
1462 case ISD::ATOMIC_LOAD_MIN:
1463 case ISD::ATOMIC_LOAD_MAX:
1464 case ISD::ATOMIC_LOAD_UMIN:
1465 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1466 if (DCI.isBeforeLegalize())
1469 MemSDNode *MemNode = cast<MemSDNode>(N);
1470 SDValue Ptr = MemNode->getBasePtr();
1472 // TODO: We could also do this for multiplies.
1473 unsigned AS = MemNode->getAddressSpace();
1474 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1475 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1477 SmallVector<SDValue, 8> NewOps;
1478 for (unsigned I = 0, N = MemNode->getNumOperands(); I != N; ++I)
1479 NewOps.push_back(MemNode->getOperand(I));
1481 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1482 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1488 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1491 /// \brief Test if RegClass is one of the VSrc classes
1492 static bool isVSrc(unsigned RegClass) {
1493 return AMDGPU::VSrc_32RegClassID == RegClass ||
1494 AMDGPU::VSrc_64RegClassID == RegClass;
1497 /// \brief Test if RegClass is one of the SSrc classes
1498 static bool isSSrc(unsigned RegClass) {
1499 return AMDGPU::SSrc_32RegClassID == RegClass ||
1500 AMDGPU::SSrc_64RegClassID == RegClass;
1503 /// \brief Analyze the possible immediate value Op
1505 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1506 /// and the immediate value if it's a literal immediate
1507 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1514 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1515 if (Node->getZExtValue() >> 32) {
1518 Imm.I = Node->getSExtValue();
1519 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1520 if (N->getValueType(0) != MVT::f32)
1522 Imm.F = Node->getValueAPF().convertToFloat();
1524 return -1; // It isn't an immediate
1526 if ((Imm.I >= -16 && Imm.I <= 64) ||
1527 Imm.F == 0.5f || Imm.F == -0.5f ||
1528 Imm.F == 1.0f || Imm.F == -1.0f ||
1529 Imm.F == 2.0f || Imm.F == -2.0f ||
1530 Imm.F == 4.0f || Imm.F == -4.0f)
1531 return 0; // It's an inline immediate
1533 return Imm.I; // It's a literal immediate
1536 /// \brief Try to fold an immediate directly into an instruction
1537 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1538 bool &ScalarSlotUsed) const {
1540 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1541 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1542 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1543 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1546 const SDValue &Op = Mov->getOperand(0);
1547 int32_t Value = analyzeImmediate(Op.getNode());
1549 // Not an immediate at all
1552 } else if (Value == 0) {
1553 // Inline immediates can always be fold
1557 } else if (Value == Immediate) {
1558 // Already fold literal immediate
1562 } else if (!ScalarSlotUsed && !Immediate) {
1563 // Fold this literal immediate
1564 ScalarSlotUsed = true;
1574 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1575 SelectionDAG &DAG, const SDValue &Op) const {
1576 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1577 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1578 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1580 if (!Op->isMachineOpcode()) {
1581 switch(Op->getOpcode()) {
1582 case ISD::CopyFromReg: {
1583 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1584 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1585 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1586 return MRI.getRegClass(Reg);
1588 return TRI.getPhysRegClass(Reg);
1590 default: return nullptr;
1593 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1594 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1595 if (OpClassID != -1) {
1596 return TRI.getRegClass(OpClassID);
1598 switch(Op.getMachineOpcode()) {
1599 case AMDGPU::COPY_TO_REGCLASS:
1600 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1601 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1603 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1604 // class, then the register class for the value could be either a
1605 // VReg or and SReg. In order to get a more accurate
1606 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1607 OpClassID == AMDGPU::VSrc_64RegClassID) {
1608 return getRegClassForNode(DAG, Op.getOperand(0));
1610 return TRI.getRegClass(OpClassID);
1611 case AMDGPU::EXTRACT_SUBREG: {
1612 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1613 const TargetRegisterClass *SuperClass =
1614 getRegClassForNode(DAG, Op.getOperand(0));
1615 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1617 case AMDGPU::REG_SEQUENCE:
1618 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1619 return TRI.getRegClass(
1620 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1622 return getRegClassFor(Op.getSimpleValueType());
1626 /// \brief Does "Op" fit into register class "RegClass" ?
1627 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1628 unsigned RegClass) const {
1629 const TargetRegisterInfo *TRI =
1630 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1631 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1635 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1638 /// \brief Make sure that we don't exeed the number of allowed scalars
1639 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1641 bool &ScalarSlotUsed) const {
1643 // First map the operands register class to a destination class
1644 if (RegClass == AMDGPU::VSrc_32RegClassID)
1645 RegClass = AMDGPU::VReg_32RegClassID;
1646 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1647 RegClass = AMDGPU::VReg_64RegClassID;
1651 // Nothing to do if they fit naturally
1652 if (fitsRegClass(DAG, Operand, RegClass))
1655 // If the scalar slot isn't used yet use it now
1656 if (!ScalarSlotUsed) {
1657 ScalarSlotUsed = true;
1661 // This is a conservative aproach. It is possible that we can't determine the
1662 // correct register class and copy too often, but better safe than sorry.
1665 // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1666 if (isa<FrameIndexSDNode>(Operand)) {
1667 unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1668 AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1669 Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1672 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1673 Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1674 Operand.getValueType(), Operand, RC);
1676 Operand = SDValue(Node, 0);
1679 /// \returns true if \p Node's operands are different from the SDValue list
1681 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1682 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1683 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1690 /// \brief Try to fold the Nodes operands into the Node
1691 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1692 SelectionDAG &DAG) const {
1694 // Original encoding (either e32 or e64)
1695 int Opcode = Node->getMachineOpcode();
1696 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1697 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1698 const MCInstrDesc *Desc = &TII->get(Opcode);
1700 unsigned NumDefs = Desc->getNumDefs();
1701 unsigned NumOps = Desc->getNumOperands();
1703 // Commuted opcode if available
1704 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1705 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1707 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1708 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1710 // e64 version if available, -1 otherwise
1711 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1712 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1713 int InputModifiers[3] = {0};
1715 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1717 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1718 bool HaveVSrc = false, HaveSSrc = false;
1720 // First figure out what we already have in this instruction.
1721 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1722 i != e && Op < NumOps; ++i, ++Op) {
1724 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1725 if (isVSrc(RegClass))
1727 else if (isSSrc(RegClass))
1732 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1733 if (Imm != -1 && Imm != 0) {
1734 // Literal immediate
1739 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1740 if (!HaveVSrc && !HaveSSrc)
1743 // No scalar allowed when we have both VSrc and SSrc
1744 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1746 // Second go over the operands and try to fold them
1747 std::vector<SDValue> Ops;
1748 bool Promote2e64 = false;
1749 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1750 i != e && Op < NumOps; ++i, ++Op) {
1752 const SDValue &Operand = Node->getOperand(i);
1753 Ops.push_back(Operand);
1755 // Already folded immediate?
1756 if (isa<ConstantSDNode>(Operand.getNode()) ||
1757 isa<ConstantFPSDNode>(Operand.getNode()))
1760 // Is this a VSrc or SSrc operand?
1761 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1762 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1763 // Try to fold the immediates
1764 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1765 // Folding didn't work, make sure we don't hit the SReg limit.
1766 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1770 // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1771 // These will be lowered to immediates, so we will need to insert a MOV.
1772 if (isa<GlobalAddressSDNode>(Ops[i])) {
1773 SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1774 Operand.getValueType(), Operand);
1775 Ops[i] = SDValue(Node, 0);
1779 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1781 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1782 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1784 // Test if it makes sense to swap operands
1785 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1786 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1787 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1789 // Swap commutable operands
1790 std::swap(Ops[0], Ops[1]);
1802 // Test if it makes sense to switch to e64 encoding
1803 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1804 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1807 int32_t TmpImm = -1;
1808 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1809 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1810 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1812 // Switch to e64 encoding
1820 if (!DescE64 && !Promote2e64)
1822 if (!Operand.isMachineOpcode())
1827 std::vector<SDValue> OldOps(Ops);
1829 bool HasModifiers = TII->hasModifiers(Desc->Opcode);
1830 for (unsigned i = 0; i < OldOps.size(); ++i) {
1833 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1834 Ops.push_back(OldOps[i]);
1836 // Add the modifier flags while promoting
1838 for (unsigned i = 0; i < 2; ++i)
1839 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1843 // Add optional chain and glue
1844 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1845 Ops.push_back(Node->getOperand(i));
1847 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1848 // this case a brand new node is always be created, even if the operands
1849 // are the same as before. So, manually check if anything has been changed.
1850 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1854 // Create a complete new instruction
1855 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1858 /// \brief Helper function for adjustWritemask
1859 static unsigned SubIdx2Lane(unsigned Idx) {
1862 case AMDGPU::sub0: return 0;
1863 case AMDGPU::sub1: return 1;
1864 case AMDGPU::sub2: return 2;
1865 case AMDGPU::sub3: return 3;
1869 /// \brief Adjust the writemask of MIMG instructions
1870 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1871 SelectionDAG &DAG) const {
1872 SDNode *Users[4] = { };
1874 unsigned OldDmask = Node->getConstantOperandVal(0);
1875 unsigned NewDmask = 0;
1877 // Try to figure out the used register components
1878 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1881 // Abort if we can't understand the usage
1882 if (!I->isMachineOpcode() ||
1883 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1886 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1887 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1888 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1890 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1892 // Set which texture component corresponds to the lane.
1894 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1896 Comp = countTrailingZeros(Dmask);
1897 Dmask &= ~(1 << Comp);
1900 // Abort if we have more than one user per component
1905 NewDmask |= 1 << Comp;
1908 // Abort if there's no change
1909 if (NewDmask == OldDmask)
1912 // Adjust the writemask in the node
1913 std::vector<SDValue> Ops;
1914 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1915 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1916 Ops.push_back(Node->getOperand(i));
1917 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1919 // If we only got one lane, replace it with a copy
1920 // (if NewDmask has only one bit set...)
1921 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1922 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1923 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1924 SDLoc(), Users[Lane]->getValueType(0),
1925 SDValue(Node, 0), RC);
1926 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1930 // Update the users of the node with the new indices
1931 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1933 SDNode *User = Users[i];
1937 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1938 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1942 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1943 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1944 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1949 /// \brief Fold the instructions after selecting them.
1950 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1951 SelectionDAG &DAG) const {
1952 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1953 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1954 Node = AdjustRegClass(Node, DAG);
1956 if (TII->isMIMG(Node->getMachineOpcode()))
1957 adjustWritemask(Node, DAG);
1959 return foldOperands(Node, DAG);
1962 /// \brief Assign the register class depending on the number of
1963 /// bits set in the writemask
1964 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1965 SDNode *Node) const {
1966 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1967 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1968 if (!TII->isMIMG(MI->getOpcode()))
1971 unsigned VReg = MI->getOperand(0).getReg();
1972 unsigned Writemask = MI->getOperand(1).getImm();
1973 unsigned BitsSet = 0;
1974 for (unsigned i = 0; i < 4; ++i)
1975 BitsSet += Writemask & (1 << i) ? 1 : 0;
1977 const TargetRegisterClass *RC;
1980 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1981 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1982 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1985 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1986 MI->setDesc(TII->get(NewOpcode));
1987 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1988 MRI.setRegClass(VReg, RC);
1991 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1992 SelectionDAG &DAG) const {
1995 unsigned NewOpcode = N->getMachineOpcode();
1997 switch (N->getMachineOpcode()) {
1999 case AMDGPU::S_LOAD_DWORD_IMM:
2000 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
2002 case AMDGPU::S_LOAD_DWORDX2_SGPR:
2003 if (NewOpcode == N->getMachineOpcode()) {
2004 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
2007 case AMDGPU::S_LOAD_DWORDX4_IMM:
2008 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
2009 if (NewOpcode == N->getMachineOpcode()) {
2010 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
2012 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
2015 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
2017 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
2018 DAG.getConstant(0, MVT::i64)), 0),
2020 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
2022 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
2027 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2028 const TargetRegisterClass *RC,
2029 unsigned Reg, EVT VT) const {
2030 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2032 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2033 cast<RegisterSDNode>(VReg)->getReg(), VT);