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 setOperationAction(ISD::FDIV, MVT::f32, Custom);
228 setTargetDAGCombine(ISD::SELECT_CC);
229 setTargetDAGCombine(ISD::SETCC);
231 setTargetDAGCombine(ISD::UINT_TO_FP);
233 // All memory operations. Some folding on the pointer operand is done to help
234 // matching the constant offsets in the addressing modes.
235 setTargetDAGCombine(ISD::LOAD);
236 setTargetDAGCombine(ISD::STORE);
237 setTargetDAGCombine(ISD::ATOMIC_LOAD);
238 setTargetDAGCombine(ISD::ATOMIC_STORE);
239 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
240 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
241 setTargetDAGCombine(ISD::ATOMIC_SWAP);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
243 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
244 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
245 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
246 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
253 setSchedulingPreference(Sched::RegPressure);
256 //===----------------------------------------------------------------------===//
257 // TargetLowering queries
258 //===----------------------------------------------------------------------===//
260 // FIXME: This really needs an address space argument. The immediate offset
261 // size is different for different sets of memory instruction sets.
263 // The single offset DS instructions have a 16-bit unsigned byte offset.
265 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
266 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
267 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
269 // SMRD instructions have an 8-bit, dword offset.
271 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
273 // No global is ever allowed as a base.
277 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
279 if (!isUInt<16>(AM.BaseOffs))
284 case 0: // "r+i" or just "i", depending on HasBaseReg.
287 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
289 // Otherwise we have r+r or r+i.
292 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
296 default: // Don't allow n * r
303 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
306 bool *IsFast) const {
310 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
311 // which isn't a simple VT.
312 if (!VT.isSimple() || VT == MVT::Other)
315 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
316 // see what for specifically. The wording everywhere else seems to be the
319 // XXX - The only mention I see of this in the ISA manual is for LDS direct
320 // reads the "byte address and must be dword aligned". Is it also true for the
321 // normal loads and stores?
322 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
323 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
324 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
325 // with adjacent offsets.
326 return Align % 4 == 0;
329 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
330 // byte-address are ignored, thus forcing Dword alignment.
331 // This applies to private, global, and constant memory.
334 return VT.bitsGT(MVT::i32);
337 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
338 unsigned SrcAlign, bool IsMemset,
341 MachineFunction &MF) const {
342 // FIXME: Should account for address space here.
344 // The default fallback uses the private pointer size as a guess for a type to
345 // use. Make sure we switch these to 64-bit accesses.
347 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
350 if (Size >= 8 && DstAlign >= 4)
357 TargetLoweringBase::LegalizeTypeAction
358 SITargetLowering::getPreferredVectorAction(EVT VT) const {
359 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
360 return TypeSplitVector;
362 return TargetLoweringBase::getPreferredVectorAction(VT);
365 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
367 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
368 getTargetMachine().getSubtargetImpl()->getInstrInfo());
369 return TII->isInlineConstant(Imm);
372 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
373 SDLoc SL, SDValue Chain,
374 unsigned Offset, bool Signed) const {
375 const DataLayout *DL = getDataLayout();
377 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
379 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
380 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
381 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
382 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
383 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
384 DAG.getConstant(Offset, MVT::i64));
385 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
386 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
388 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
389 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
391 true, // isNonTemporal
393 DL->getABITypeAlignment(Ty)); // Alignment
396 SDValue SITargetLowering::LowerFormalArguments(
398 CallingConv::ID CallConv,
400 const SmallVectorImpl<ISD::InputArg> &Ins,
401 SDLoc DL, SelectionDAG &DAG,
402 SmallVectorImpl<SDValue> &InVals) const {
404 const TargetRegisterInfo *TRI =
405 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
407 MachineFunction &MF = DAG.getMachineFunction();
408 FunctionType *FType = MF.getFunction()->getFunctionType();
409 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
411 assert(CallConv == CallingConv::C);
413 SmallVector<ISD::InputArg, 16> Splits;
414 uint32_t Skipped = 0;
416 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
417 const ISD::InputArg &Arg = Ins[i];
419 // First check if it's a PS input addr
420 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
421 !Arg.Flags.isByVal()) {
423 assert((PSInputNum <= 15) && "Too many PS inputs!");
426 // We can savely skip PS inputs
432 Info->PSInputAddr |= 1 << PSInputNum++;
435 // Second split vertices into their elements
436 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
437 ISD::InputArg NewArg = Arg;
438 NewArg.Flags.setSplit();
439 NewArg.VT = Arg.VT.getVectorElementType();
441 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
442 // three or five element vertex only needs three or five registers,
443 // NOT four or eigth.
444 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
445 unsigned NumElements = ParamType->getVectorNumElements();
447 for (unsigned j = 0; j != NumElements; ++j) {
448 Splits.push_back(NewArg);
449 NewArg.PartOffset += NewArg.VT.getStoreSize();
452 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
453 Splits.push_back(Arg);
457 SmallVector<CCValAssign, 16> ArgLocs;
458 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
461 // At least one interpolation mode must be enabled or else the GPU will hang.
462 if (Info->getShaderType() == ShaderType::PIXEL &&
463 (Info->PSInputAddr & 0x7F) == 0) {
464 Info->PSInputAddr |= 1;
465 CCInfo.AllocateReg(AMDGPU::VGPR0);
466 CCInfo.AllocateReg(AMDGPU::VGPR1);
469 // The pointer to the list of arguments is stored in SGPR0, SGPR1
470 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
471 if (Info->getShaderType() == ShaderType::COMPUTE) {
472 Info->NumUserSGPRs = 4;
473 CCInfo.AllocateReg(AMDGPU::SGPR0);
474 CCInfo.AllocateReg(AMDGPU::SGPR1);
475 CCInfo.AllocateReg(AMDGPU::SGPR2);
476 CCInfo.AllocateReg(AMDGPU::SGPR3);
477 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
478 MF.addLiveIn(AMDGPU::SGPR2_SGPR3, &AMDGPU::SReg_64RegClass);
481 if (Info->getShaderType() == ShaderType::COMPUTE) {
482 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
486 AnalyzeFormalArguments(CCInfo, Splits);
488 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
490 const ISD::InputArg &Arg = Ins[i];
491 if (Skipped & (1 << i)) {
492 InVals.push_back(DAG.getUNDEF(Arg.VT));
496 CCValAssign &VA = ArgLocs[ArgIdx++];
497 EVT VT = VA.getLocVT();
501 EVT MemVT = Splits[i].VT;
502 // The first 36 bytes of the input buffer contains information about
503 // thread group and global sizes.
504 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
505 36 + VA.getLocMemOffset(),
506 Ins[i].Flags.isSExt());
507 InVals.push_back(Arg);
510 assert(VA.isRegLoc() && "Parameter must be in a register!");
512 unsigned Reg = VA.getLocReg();
514 if (VT == MVT::i64) {
515 // For now assume it is a pointer
516 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
517 &AMDGPU::SReg_64RegClass);
518 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
519 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
523 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
525 Reg = MF.addLiveIn(Reg, RC);
526 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
528 if (Arg.VT.isVector()) {
530 // Build a vector from the registers
531 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
532 unsigned NumElements = ParamType->getVectorNumElements();
534 SmallVector<SDValue, 4> Regs;
536 for (unsigned j = 1; j != NumElements; ++j) {
537 Reg = ArgLocs[ArgIdx++].getLocReg();
538 Reg = MF.addLiveIn(Reg, RC);
539 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
542 // Fill up the missing vector elements
543 NumElements = Arg.VT.getVectorNumElements() - NumElements;
544 for (unsigned j = 0; j != NumElements; ++j)
545 Regs.push_back(DAG.getUNDEF(VT));
547 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
551 InVals.push_back(Val);
556 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
557 MachineInstr * MI, MachineBasicBlock * BB) const {
559 MachineBasicBlock::iterator I = *MI;
560 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
561 getTargetMachine().getSubtargetImpl()->getInstrInfo());
562 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
564 switch (MI->getOpcode()) {
566 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
567 case AMDGPU::BRANCH: return BB;
568 case AMDGPU::SI_ADDR64_RSRC: {
569 unsigned SuperReg = MI->getOperand(0).getReg();
570 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
571 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
572 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
573 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
574 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
575 .addOperand(MI->getOperand(1));
576 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
578 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
579 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
580 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
582 .addImm(AMDGPU::sub0)
584 .addImm(AMDGPU::sub1);
585 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
587 .addImm(AMDGPU::sub0_sub1)
589 .addImm(AMDGPU::sub2_sub3);
590 MI->eraseFromParent();
593 case AMDGPU::SI_BUFFER_RSRC: {
594 unsigned SuperReg = MI->getOperand(0).getReg();
596 for (unsigned i = 0, e = 4; i < e; ++i) {
597 MachineOperand &Arg = MI->getOperand(i + 1);
600 Args[i] = Arg.getReg();
605 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
606 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
607 .addImm(Arg.getImm());
610 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
613 .addImm(AMDGPU::sub0)
615 .addImm(AMDGPU::sub1)
617 .addImm(AMDGPU::sub2)
619 .addImm(AMDGPU::sub3);
620 MI->eraseFromParent();
623 case AMDGPU::V_SUB_F64: {
624 unsigned DestReg = MI->getOperand(0).getReg();
625 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
626 .addImm(0) // SRC0 modifiers
627 .addReg(MI->getOperand(1).getReg())
628 .addImm(1) // SRC1 modifiers
629 .addReg(MI->getOperand(2).getReg())
632 MI->eraseFromParent();
635 case AMDGPU::SI_RegisterStorePseudo: {
636 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
637 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
638 MachineInstrBuilder MIB =
639 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
641 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
642 MIB.addOperand(MI->getOperand(i));
644 MI->eraseFromParent();
647 case AMDGPU::FCLAMP_SI: {
648 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
649 getTargetMachine().getSubtargetImpl()->getInstrInfo());
650 DebugLoc DL = MI->getDebugLoc();
651 unsigned DestReg = MI->getOperand(0).getReg();
652 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
653 .addImm(0) // SRC0 modifiers
654 .addOperand(MI->getOperand(1))
655 .addImm(0) // SRC1 modifiers
659 MI->eraseFromParent();
665 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
666 if (!VT.isVector()) {
669 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
672 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
676 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
677 VT = VT.getScalarType();
682 switch (VT.getSimpleVT().SimpleTy) {
684 return false; /* There is V_MAD_F32 for f32 */
694 //===----------------------------------------------------------------------===//
695 // Custom DAG Lowering Operations
696 //===----------------------------------------------------------------------===//
698 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
699 switch (Op.getOpcode()) {
700 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
701 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
702 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
704 SDValue Result = LowerLOAD(Op, DAG);
705 assert((!Result.getNode() ||
706 Result.getNode()->getNumValues() == 2) &&
707 "Load should return a value and a chain");
713 return LowerTrig(Op, DAG);
714 case ISD::SELECT: return LowerSELECT(Op, DAG);
715 case ISD::FDIV: return LowerFDIV(Op, DAG);
716 case ISD::STORE: return LowerSTORE(Op, DAG);
717 case ISD::GlobalAddress: {
718 MachineFunction &MF = DAG.getMachineFunction();
719 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
720 return LowerGlobalAddress(MFI, Op, DAG);
722 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
723 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
728 /// \brief Helper function for LowerBRCOND
729 static SDNode *findUser(SDValue Value, unsigned Opcode) {
731 SDNode *Parent = Value.getNode();
732 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
735 if (I.getUse().get() != Value)
738 if (I->getOpcode() == Opcode)
744 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
746 MachineFunction &MF = DAG.getMachineFunction();
747 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
748 getTargetMachine().getSubtargetImpl()->getInstrInfo());
749 const SIRegisterInfo &TRI = TII->getRegisterInfo();
750 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
751 unsigned FrameIndex = FINode->getIndex();
753 CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
754 TRI.getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET), MVT::i32);
756 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
759 /// This transforms the control flow intrinsics to get the branch destination as
760 /// last parameter, also switches branch target with BR if the need arise
761 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
762 SelectionDAG &DAG) const {
766 SDNode *Intr = BRCOND.getOperand(1).getNode();
767 SDValue Target = BRCOND.getOperand(2);
768 SDNode *BR = nullptr;
770 if (Intr->getOpcode() == ISD::SETCC) {
771 // As long as we negate the condition everything is fine
772 SDNode *SetCC = Intr;
773 assert(SetCC->getConstantOperandVal(1) == 1);
774 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
776 Intr = SetCC->getOperand(0).getNode();
779 // Get the target from BR if we don't negate the condition
780 BR = findUser(BRCOND, ISD::BR);
781 Target = BR->getOperand(1);
784 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
786 // Build the result and
787 SmallVector<EVT, 4> Res;
788 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
789 Res.push_back(Intr->getValueType(i));
791 // operands of the new intrinsic call
792 SmallVector<SDValue, 4> Ops;
793 Ops.push_back(BRCOND.getOperand(0));
794 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
795 Ops.push_back(Intr->getOperand(i));
796 Ops.push_back(Target);
798 // build the new intrinsic call
799 SDNode *Result = DAG.getNode(
800 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
801 DAG.getVTList(Res), Ops).getNode();
804 // Give the branch instruction our target
809 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
810 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
811 BR = NewBR.getNode();
814 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
816 // Copy the intrinsic results to registers
817 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
818 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
822 Chain = DAG.getCopyToReg(
824 CopyToReg->getOperand(1),
825 SDValue(Result, i - 1),
828 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
831 // Remove the old intrinsic from the chain
832 DAG.ReplaceAllUsesOfValueWith(
833 SDValue(Intr, Intr->getNumValues() - 1),
834 Intr->getOperand(0));
839 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
841 SelectionDAG &DAG) const {
842 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
844 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
845 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
848 const GlobalValue *GV = GSD->getGlobal();
849 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
851 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
852 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
854 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
855 DAG.getConstant(0, MVT::i32));
856 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
857 DAG.getConstant(1, MVT::i32));
859 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
861 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
862 PtrHi, DAG.getConstant(0, MVT::i32),
863 SDValue(Lo.getNode(), 1));
864 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
867 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
868 SelectionDAG &DAG) const {
869 MachineFunction &MF = DAG.getMachineFunction();
870 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
872 EVT VT = Op.getValueType();
874 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
876 switch (IntrinsicID) {
877 case Intrinsic::r600_read_ngroups_x:
878 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
879 case Intrinsic::r600_read_ngroups_y:
880 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
881 case Intrinsic::r600_read_ngroups_z:
882 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
883 case Intrinsic::r600_read_global_size_x:
884 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
885 case Intrinsic::r600_read_global_size_y:
886 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
887 case Intrinsic::r600_read_global_size_z:
888 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
889 case Intrinsic::r600_read_local_size_x:
890 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
891 case Intrinsic::r600_read_local_size_y:
892 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
893 case Intrinsic::r600_read_local_size_z:
894 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
895 case Intrinsic::r600_read_tgid_x:
896 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
897 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
898 case Intrinsic::r600_read_tgid_y:
899 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
900 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
901 case Intrinsic::r600_read_tgid_z:
902 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
903 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
904 case Intrinsic::r600_read_tidig_x:
905 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
907 case Intrinsic::r600_read_tidig_y:
908 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
910 case Intrinsic::r600_read_tidig_z:
911 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
913 case AMDGPUIntrinsic::SI_load_const: {
919 MachineMemOperand *MMO = MF.getMachineMemOperand(
920 MachinePointerInfo(),
921 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
922 VT.getStoreSize(), 4);
923 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
924 Op->getVTList(), Ops, VT, MMO);
926 case AMDGPUIntrinsic::SI_sample:
927 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
928 case AMDGPUIntrinsic::SI_sampleb:
929 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
930 case AMDGPUIntrinsic::SI_sampled:
931 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
932 case AMDGPUIntrinsic::SI_samplel:
933 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
934 case AMDGPUIntrinsic::SI_vs_load_input:
935 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
940 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
944 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
945 SelectionDAG &DAG) const {
946 MachineFunction &MF = DAG.getMachineFunction();
947 SDValue Chain = Op.getOperand(0);
948 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
950 switch (IntrinsicID) {
951 case AMDGPUIntrinsic::SI_tbuffer_store: {
970 EVT VT = Op.getOperand(3).getValueType();
972 MachineMemOperand *MMO = MF.getMachineMemOperand(
973 MachinePointerInfo(),
974 MachineMemOperand::MOStore,
975 VT.getStoreSize(), 4);
976 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
977 Op->getVTList(), Ops, VT, MMO);
984 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
986 LoadSDNode *Load = cast<LoadSDNode>(Op);
988 if (Op.getValueType().isVector()) {
989 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
990 "Custom lowering for non-i32 vectors hasn't been implemented.");
991 unsigned NumElements = Op.getValueType().getVectorNumElements();
992 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
993 switch (Load->getAddressSpace()) {
995 case AMDGPUAS::GLOBAL_ADDRESS:
996 case AMDGPUAS::PRIVATE_ADDRESS:
997 // v4 loads are supported for private and global memory.
998 if (NumElements <= 4)
1001 case AMDGPUAS::LOCAL_ADDRESS:
1002 return ScalarizeVectorLoad(Op, DAG);
1006 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1009 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1011 SelectionDAG &DAG) const {
1012 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1018 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1019 if (Op.getValueType() != MVT::i64)
1023 SDValue Cond = Op.getOperand(0);
1025 SDValue Zero = DAG.getConstant(0, MVT::i32);
1026 SDValue One = DAG.getConstant(1, MVT::i32);
1028 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1029 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1031 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1032 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1034 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1036 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1037 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1039 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1041 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1042 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1045 // Catch division cases where we can use shortcuts with rcp and rsq
1047 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1049 SDValue LHS = Op.getOperand(0);
1050 SDValue RHS = Op.getOperand(1);
1051 EVT VT = Op.getValueType();
1052 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1054 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1055 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1056 CLHS->isExactlyValue(1.0)) {
1057 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1058 // the CI documentation has a worst case error of 1 ulp.
1059 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1060 // use it as long as we aren't trying to use denormals.
1062 // 1.0 / sqrt(x) -> rsq(x)
1064 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1065 // error seems really high at 2^29 ULP.
1066 if (RHS.getOpcode() == ISD::FSQRT)
1067 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1069 // 1.0 / x -> rcp(x)
1070 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1075 // Turn into multiply by the reciprocal.
1076 // x / y -> x * (1.0 / y)
1077 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1078 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1084 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1085 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1086 if (FastLowered.getNode())
1089 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1090 // selection error for now rather than do something incorrect.
1091 if (Subtarget->hasFP32Denormals())
1095 SDValue LHS = Op.getOperand(0);
1096 SDValue RHS = Op.getOperand(1);
1098 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1100 const APFloat K0Val(BitsToFloat(0x6f800000));
1101 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1103 const APFloat K1Val(BitsToFloat(0x2f800000));
1104 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1106 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1108 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1110 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1112 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1114 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1116 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1118 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1120 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1123 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1127 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1128 EVT VT = Op.getValueType();
1131 return LowerFDIV32(Op, DAG);
1134 return LowerFDIV64(Op, DAG);
1136 llvm_unreachable("Unexpected type for fdiv");
1139 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1141 StoreSDNode *Store = cast<StoreSDNode>(Op);
1142 EVT VT = Store->getMemoryVT();
1144 // These stores are legal.
1145 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1146 VT.isVector() && VT.getVectorNumElements() == 2 &&
1147 VT.getVectorElementType() == MVT::i32)
1150 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1151 if (VT.isVector() && VT.getVectorNumElements() > 4)
1152 return ScalarizeVectorStore(Op, DAG);
1156 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1160 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1161 return ScalarizeVectorStore(Op, DAG);
1164 return DAG.getTruncStore(Store->getChain(), DL,
1165 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1166 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1171 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1172 EVT VT = Op.getValueType();
1173 SDValue Arg = Op.getOperand(0);
1174 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1175 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1176 DAG.getConstantFP(0.5 / M_PI, VT)));
1178 switch (Op.getOpcode()) {
1180 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1182 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1184 llvm_unreachable("Wrong trig opcode");
1188 //===----------------------------------------------------------------------===//
1189 // Custom DAG optimizations
1190 //===----------------------------------------------------------------------===//
1192 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1193 DAGCombinerInfo &DCI) {
1194 EVT VT = N->getValueType(0);
1195 EVT ScalarVT = VT.getScalarType();
1196 if (ScalarVT != MVT::f32)
1199 SelectionDAG &DAG = DCI.DAG;
1202 SDValue Src = N->getOperand(0);
1203 EVT SrcVT = Src.getValueType();
1205 // TODO: We could try to match extracting the higher bytes, which would be
1206 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1207 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1208 // about in practice.
1209 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1210 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1211 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1212 DCI.AddToWorklist(Cvt.getNode());
1217 // We are primarily trying to catch operations on illegal vector types
1218 // before they are expanded.
1219 // For scalars, we can use the more flexible method of checking masked bits
1220 // after legalization.
1221 if (!DCI.isBeforeLegalize() ||
1222 !SrcVT.isVector() ||
1223 SrcVT.getVectorElementType() != MVT::i8) {
1227 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1229 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1231 unsigned NElts = SrcVT.getVectorNumElements();
1232 if (!SrcVT.isSimple() && NElts != 3)
1235 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1236 // prevent a mess from expanding to v4i32 and repacking.
1237 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1238 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1239 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1240 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1242 LoadSDNode *Load = cast<LoadSDNode>(Src);
1243 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1247 Load->getMemOperand());
1249 // Make sure successors of the original load stay after it by updating
1250 // them to use the new Chain.
1251 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1253 SmallVector<SDValue, 4> Elts;
1254 if (RegVT.isVector())
1255 DAG.ExtractVectorElements(NewLoad, Elts);
1257 Elts.push_back(NewLoad);
1259 SmallVector<SDValue, 4> Ops;
1261 unsigned EltIdx = 0;
1262 for (SDValue Elt : Elts) {
1263 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1264 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1265 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1266 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1267 DCI.AddToWorklist(Cvt.getNode());
1274 assert(Ops.size() == NElts);
1276 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1282 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1284 // This is a variant of
1285 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1287 // The normal DAG combiner will do this, but only if the add has one use since
1288 // that would increase the number of instructions.
1290 // This prevents us from seeing a constant offset that can be folded into a
1291 // memory instruction's addressing mode. If we know the resulting add offset of
1292 // a pointer can be folded into an addressing offset, we can replace the pointer
1293 // operand with the add of new constant offset. This eliminates one of the uses,
1294 // and may allow the remaining use to also be simplified.
1296 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1298 DAGCombinerInfo &DCI) const {
1299 SDValue N0 = N->getOperand(0);
1300 SDValue N1 = N->getOperand(1);
1302 if (N0.getOpcode() != ISD::ADD)
1305 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1309 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1313 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1314 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1316 // If the resulting offset is too large, we can't fold it into the addressing
1318 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1319 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1322 SelectionDAG &DAG = DCI.DAG;
1324 EVT VT = N->getValueType(0);
1326 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1327 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1329 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1332 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1333 DAGCombinerInfo &DCI) const {
1334 SelectionDAG &DAG = DCI.DAG;
1336 EVT VT = N->getValueType(0);
1338 switch (N->getOpcode()) {
1339 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1341 SDValue Arg0 = N->getOperand(0);
1342 SDValue Arg1 = N->getOperand(1);
1343 SDValue CC = N->getOperand(2);
1344 ConstantSDNode * C = nullptr;
1345 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1347 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1349 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1350 && Arg0.getOperand(0).getValueType() == MVT::i1
1351 && (C = dyn_cast<ConstantSDNode>(Arg1))
1353 && CCOp == ISD::SETNE) {
1354 return SimplifySetCC(VT, Arg0.getOperand(0),
1355 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1360 case AMDGPUISD::CVT_F32_UBYTE0:
1361 case AMDGPUISD::CVT_F32_UBYTE1:
1362 case AMDGPUISD::CVT_F32_UBYTE2:
1363 case AMDGPUISD::CVT_F32_UBYTE3: {
1364 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1366 SDValue Src = N->getOperand(0);
1367 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1369 APInt KnownZero, KnownOne;
1370 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1371 !DCI.isBeforeLegalizeOps());
1372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1373 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1374 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1375 DCI.CommitTargetLoweringOpt(TLO);
1381 case ISD::UINT_TO_FP: {
1382 return performUCharToFloatCombine(N, DCI);
1386 case ISD::ATOMIC_LOAD:
1387 case ISD::ATOMIC_STORE:
1388 case ISD::ATOMIC_CMP_SWAP:
1389 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1390 case ISD::ATOMIC_SWAP:
1391 case ISD::ATOMIC_LOAD_ADD:
1392 case ISD::ATOMIC_LOAD_SUB:
1393 case ISD::ATOMIC_LOAD_AND:
1394 case ISD::ATOMIC_LOAD_OR:
1395 case ISD::ATOMIC_LOAD_XOR:
1396 case ISD::ATOMIC_LOAD_NAND:
1397 case ISD::ATOMIC_LOAD_MIN:
1398 case ISD::ATOMIC_LOAD_MAX:
1399 case ISD::ATOMIC_LOAD_UMIN:
1400 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1401 if (DCI.isBeforeLegalize())
1404 MemSDNode *MemNode = cast<MemSDNode>(N);
1405 SDValue Ptr = MemNode->getBasePtr();
1407 // TODO: We could also do this for multiplies.
1408 unsigned AS = MemNode->getAddressSpace();
1409 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1410 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1412 SmallVector<SDValue, 8> NewOps;
1413 for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1414 NewOps.push_back(MemNode->getOperand(I));
1416 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1417 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1423 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1426 /// \brief Test if RegClass is one of the VSrc classes
1427 static bool isVSrc(unsigned RegClass) {
1428 return AMDGPU::VSrc_32RegClassID == RegClass ||
1429 AMDGPU::VSrc_64RegClassID == RegClass;
1432 /// \brief Test if RegClass is one of the SSrc classes
1433 static bool isSSrc(unsigned RegClass) {
1434 return AMDGPU::SSrc_32RegClassID == RegClass ||
1435 AMDGPU::SSrc_64RegClassID == RegClass;
1438 /// \brief Analyze the possible immediate value Op
1440 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1441 /// and the immediate value if it's a literal immediate
1442 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1449 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1450 if (Node->getZExtValue() >> 32) {
1453 Imm.I = Node->getSExtValue();
1454 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1455 if (N->getValueType(0) != MVT::f32)
1457 Imm.F = Node->getValueAPF().convertToFloat();
1459 return -1; // It isn't an immediate
1461 if ((Imm.I >= -16 && Imm.I <= 64) ||
1462 Imm.F == 0.5f || Imm.F == -0.5f ||
1463 Imm.F == 1.0f || Imm.F == -1.0f ||
1464 Imm.F == 2.0f || Imm.F == -2.0f ||
1465 Imm.F == 4.0f || Imm.F == -4.0f)
1466 return 0; // It's an inline immediate
1468 return Imm.I; // It's a literal immediate
1471 /// \brief Try to fold an immediate directly into an instruction
1472 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1473 bool &ScalarSlotUsed) const {
1475 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1476 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1477 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1478 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1481 const SDValue &Op = Mov->getOperand(0);
1482 int32_t Value = analyzeImmediate(Op.getNode());
1484 // Not an immediate at all
1487 } else if (Value == 0) {
1488 // Inline immediates can always be fold
1492 } else if (Value == Immediate) {
1493 // Already fold literal immediate
1497 } else if (!ScalarSlotUsed && !Immediate) {
1498 // Fold this literal immediate
1499 ScalarSlotUsed = true;
1509 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1510 SelectionDAG &DAG, const SDValue &Op) const {
1511 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1512 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1513 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1515 if (!Op->isMachineOpcode()) {
1516 switch(Op->getOpcode()) {
1517 case ISD::CopyFromReg: {
1518 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1519 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1520 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1521 return MRI.getRegClass(Reg);
1523 return TRI.getPhysRegClass(Reg);
1525 default: return nullptr;
1528 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1529 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1530 if (OpClassID != -1) {
1531 return TRI.getRegClass(OpClassID);
1533 switch(Op.getMachineOpcode()) {
1534 case AMDGPU::COPY_TO_REGCLASS:
1535 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1536 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1538 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1539 // class, then the register class for the value could be either a
1540 // VReg or and SReg. In order to get a more accurate
1541 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1542 OpClassID == AMDGPU::VSrc_64RegClassID) {
1543 return getRegClassForNode(DAG, Op.getOperand(0));
1545 return TRI.getRegClass(OpClassID);
1546 case AMDGPU::EXTRACT_SUBREG: {
1547 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1548 const TargetRegisterClass *SuperClass =
1549 getRegClassForNode(DAG, Op.getOperand(0));
1550 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1552 case AMDGPU::REG_SEQUENCE:
1553 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1554 return TRI.getRegClass(
1555 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1557 return getRegClassFor(Op.getSimpleValueType());
1561 /// \brief Does "Op" fit into register class "RegClass" ?
1562 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1563 unsigned RegClass) const {
1564 const TargetRegisterInfo *TRI =
1565 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1566 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1570 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1573 /// \brief Make sure that we don't exeed the number of allowed scalars
1574 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1576 bool &ScalarSlotUsed) const {
1578 // First map the operands register class to a destination class
1579 if (RegClass == AMDGPU::VSrc_32RegClassID)
1580 RegClass = AMDGPU::VReg_32RegClassID;
1581 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1582 RegClass = AMDGPU::VReg_64RegClassID;
1586 // Nothing to do if they fit naturally
1587 if (fitsRegClass(DAG, Operand, RegClass))
1590 // If the scalar slot isn't used yet use it now
1591 if (!ScalarSlotUsed) {
1592 ScalarSlotUsed = true;
1596 // This is a conservative aproach. It is possible that we can't determine the
1597 // correct register class and copy too often, but better safe than sorry.
1600 // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1601 if (isa<FrameIndexSDNode>(Operand)) {
1602 unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1603 AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1604 Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1607 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1608 Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1609 Operand.getValueType(), Operand, RC);
1611 Operand = SDValue(Node, 0);
1614 /// \returns true if \p Node's operands are different from the SDValue list
1616 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1617 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1618 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1625 /// \brief Try to fold the Nodes operands into the Node
1626 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1627 SelectionDAG &DAG) const {
1629 // Original encoding (either e32 or e64)
1630 int Opcode = Node->getMachineOpcode();
1631 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1632 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1633 const MCInstrDesc *Desc = &TII->get(Opcode);
1635 unsigned NumDefs = Desc->getNumDefs();
1636 unsigned NumOps = Desc->getNumOperands();
1638 // Commuted opcode if available
1639 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1640 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1642 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1643 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1645 // e64 version if available, -1 otherwise
1646 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1647 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1648 int InputModifiers[3] = {0};
1650 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1652 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1653 bool HaveVSrc = false, HaveSSrc = false;
1655 // First figure out what we already have in this instruction.
1656 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1657 i != e && Op < NumOps; ++i, ++Op) {
1659 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1660 if (isVSrc(RegClass))
1662 else if (isSSrc(RegClass))
1667 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1668 if (Imm != -1 && Imm != 0) {
1669 // Literal immediate
1674 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1675 if (!HaveVSrc && !HaveSSrc)
1678 // No scalar allowed when we have both VSrc and SSrc
1679 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1681 // Second go over the operands and try to fold them
1682 std::vector<SDValue> Ops;
1683 bool Promote2e64 = false;
1684 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1685 i != e && Op < NumOps; ++i, ++Op) {
1687 const SDValue &Operand = Node->getOperand(i);
1688 Ops.push_back(Operand);
1690 // Already folded immediate?
1691 if (isa<ConstantSDNode>(Operand.getNode()) ||
1692 isa<ConstantFPSDNode>(Operand.getNode()))
1695 // Is this a VSrc or SSrc operand?
1696 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1697 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1698 // Try to fold the immediates
1699 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1700 // Folding didn't work, make sure we don't hit the SReg limit.
1701 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1705 // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1706 // These will be lowered to immediates, so we will need to insert a MOV.
1707 if (isa<GlobalAddressSDNode>(Ops[i])) {
1708 SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1709 Operand.getValueType(), Operand);
1710 Ops[i] = SDValue(Node, 0);
1714 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1716 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1717 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1719 // Test if it makes sense to swap operands
1720 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1721 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1722 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1724 // Swap commutable operands
1725 std::swap(Ops[0], Ops[1]);
1737 // Test if it makes sense to switch to e64 encoding
1738 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1739 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1742 int32_t TmpImm = -1;
1743 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1744 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1745 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1747 // Switch to e64 encoding
1755 if (!DescE64 && !Promote2e64)
1757 if (!Operand.isMachineOpcode())
1762 std::vector<SDValue> OldOps(Ops);
1764 bool HasModifiers = TII->hasModifiers(Desc->Opcode);
1765 for (unsigned i = 0; i < OldOps.size(); ++i) {
1768 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1769 Ops.push_back(OldOps[i]);
1771 // Add the modifier flags while promoting
1773 for (unsigned i = 0; i < 2; ++i)
1774 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1778 // Add optional chain and glue
1779 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1780 Ops.push_back(Node->getOperand(i));
1782 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1783 // this case a brand new node is always be created, even if the operands
1784 // are the same as before. So, manually check if anything has been changed.
1785 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1789 // Create a complete new instruction
1790 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1793 /// \brief Helper function for adjustWritemask
1794 static unsigned SubIdx2Lane(unsigned Idx) {
1797 case AMDGPU::sub0: return 0;
1798 case AMDGPU::sub1: return 1;
1799 case AMDGPU::sub2: return 2;
1800 case AMDGPU::sub3: return 3;
1804 /// \brief Adjust the writemask of MIMG instructions
1805 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1806 SelectionDAG &DAG) const {
1807 SDNode *Users[4] = { };
1809 unsigned OldDmask = Node->getConstantOperandVal(0);
1810 unsigned NewDmask = 0;
1812 // Try to figure out the used register components
1813 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1816 // Abort if we can't understand the usage
1817 if (!I->isMachineOpcode() ||
1818 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1821 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1822 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1823 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1825 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1827 // Set which texture component corresponds to the lane.
1829 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1831 Comp = countTrailingZeros(Dmask);
1832 Dmask &= ~(1 << Comp);
1835 // Abort if we have more than one user per component
1840 NewDmask |= 1 << Comp;
1843 // Abort if there's no change
1844 if (NewDmask == OldDmask)
1847 // Adjust the writemask in the node
1848 std::vector<SDValue> Ops;
1849 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1850 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1851 Ops.push_back(Node->getOperand(i));
1852 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1854 // If we only got one lane, replace it with a copy
1855 // (if NewDmask has only one bit set...)
1856 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1857 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1858 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1859 SDLoc(), Users[Lane]->getValueType(0),
1860 SDValue(Node, 0), RC);
1861 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1865 // Update the users of the node with the new indices
1866 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1868 SDNode *User = Users[i];
1872 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1873 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1877 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1878 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1879 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1884 /// \brief Fold the instructions after selecting them.
1885 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1886 SelectionDAG &DAG) const {
1887 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1888 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1889 Node = AdjustRegClass(Node, DAG);
1891 if (TII->isMIMG(Node->getMachineOpcode()))
1892 adjustWritemask(Node, DAG);
1894 return foldOperands(Node, DAG);
1897 /// \brief Assign the register class depending on the number of
1898 /// bits set in the writemask
1899 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1900 SDNode *Node) const {
1901 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1902 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1903 if (!TII->isMIMG(MI->getOpcode()))
1906 unsigned VReg = MI->getOperand(0).getReg();
1907 unsigned Writemask = MI->getOperand(1).getImm();
1908 unsigned BitsSet = 0;
1909 for (unsigned i = 0; i < 4; ++i)
1910 BitsSet += Writemask & (1 << i) ? 1 : 0;
1912 const TargetRegisterClass *RC;
1915 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1916 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1917 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1920 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1921 MI->setDesc(TII->get(NewOpcode));
1922 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1923 MRI.setRegClass(VReg, RC);
1926 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1927 SelectionDAG &DAG) const {
1930 unsigned NewOpcode = N->getMachineOpcode();
1932 switch (N->getMachineOpcode()) {
1934 case AMDGPU::S_LOAD_DWORD_IMM:
1935 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1937 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1938 if (NewOpcode == N->getMachineOpcode()) {
1939 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1942 case AMDGPU::S_LOAD_DWORDX4_IMM:
1943 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1944 if (NewOpcode == N->getMachineOpcode()) {
1945 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1947 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1950 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1952 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1953 DAG.getConstant(0, MVT::i64)), 0),
1955 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1957 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1962 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1963 const TargetRegisterClass *RC,
1964 unsigned Reg, EVT VT) const {
1965 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1967 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1968 cast<RegisterSDNode>(VReg)->getReg(), VT);