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);
229 setOperationAction(ISD::FABS, MVT::f64, Expand);
231 setOperationAction(ISD::FDIV, MVT::f32, Custom);
233 setTargetDAGCombine(ISD::SELECT_CC);
234 setTargetDAGCombine(ISD::SETCC);
236 setTargetDAGCombine(ISD::UINT_TO_FP);
238 // All memory operations. Some folding on the pointer operand is done to help
239 // matching the constant offsets in the addressing modes.
240 setTargetDAGCombine(ISD::LOAD);
241 setTargetDAGCombine(ISD::STORE);
242 setTargetDAGCombine(ISD::ATOMIC_LOAD);
243 setTargetDAGCombine(ISD::ATOMIC_STORE);
244 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
245 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
246 setTargetDAGCombine(ISD::ATOMIC_SWAP);
247 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
248 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
249 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
250 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
251 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
252 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
253 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
254 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
255 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
256 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
258 setSchedulingPreference(Sched::RegPressure);
261 //===----------------------------------------------------------------------===//
262 // TargetLowering queries
263 //===----------------------------------------------------------------------===//
265 // FIXME: This really needs an address space argument. The immediate offset
266 // size is different for different sets of memory instruction sets.
268 // The single offset DS instructions have a 16-bit unsigned byte offset.
270 // MUBUF / MTBUF have a 12-bit unsigned byte offset, and additionally can do r +
271 // r + i with addr64. 32-bit has more addressing mode options. Depending on the
272 // resource constant, it can also do (i64 r0) + (i32 r1) * (i14 i).
274 // SMRD instructions have an 8-bit, dword offset.
276 bool SITargetLowering::isLegalAddressingMode(const AddrMode &AM,
278 // No global is ever allowed as a base.
282 // Allow a 16-bit unsigned immediate field, since this is what DS instructions
284 if (!isUInt<16>(AM.BaseOffs))
289 case 0: // "r+i" or just "i", depending on HasBaseReg.
292 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
294 // Otherwise we have r+r or r+i.
297 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
301 default: // Don't allow n * r
308 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
311 bool *IsFast) const {
315 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
316 // which isn't a simple VT.
317 if (!VT.isSimple() || VT == MVT::Other)
320 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
321 // see what for specifically. The wording everywhere else seems to be the
324 // XXX - The only mention I see of this in the ISA manual is for LDS direct
325 // reads the "byte address and must be dword aligned". Is it also true for the
326 // normal loads and stores?
327 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
328 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
329 // aligned, 8 byte access in a single operation using ds_read2/write2_b32
330 // with adjacent offsets.
331 return Align % 4 == 0;
334 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
335 // byte-address are ignored, thus forcing Dword alignment.
336 // This applies to private, global, and constant memory.
339 return VT.bitsGT(MVT::i32);
342 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
343 unsigned SrcAlign, bool IsMemset,
346 MachineFunction &MF) const {
347 // FIXME: Should account for address space here.
349 // The default fallback uses the private pointer size as a guess for a type to
350 // use. Make sure we switch these to 64-bit accesses.
352 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
355 if (Size >= 8 && DstAlign >= 4)
362 TargetLoweringBase::LegalizeTypeAction
363 SITargetLowering::getPreferredVectorAction(EVT VT) const {
364 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
365 return TypeSplitVector;
367 return TargetLoweringBase::getPreferredVectorAction(VT);
370 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
372 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
373 getTargetMachine().getSubtargetImpl()->getInstrInfo());
374 return TII->isInlineConstant(Imm);
377 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
378 SDLoc SL, SDValue Chain,
379 unsigned Offset, bool Signed) const {
380 const DataLayout *DL = getDataLayout();
382 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
384 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
385 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
386 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
387 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
388 SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, BasePtr,
389 DAG.getConstant(Offset, MVT::i64));
390 SDValue PtrOffset = DAG.getUNDEF(getPointerTy(AMDGPUAS::CONSTANT_ADDRESS));
391 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
393 return DAG.getLoad(ISD::UNINDEXED, Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD,
394 VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
396 true, // isNonTemporal
398 DL->getABITypeAlignment(Ty)); // Alignment
401 SDValue SITargetLowering::LowerFormalArguments(
403 CallingConv::ID CallConv,
405 const SmallVectorImpl<ISD::InputArg> &Ins,
406 SDLoc DL, SelectionDAG &DAG,
407 SmallVectorImpl<SDValue> &InVals) const {
409 const TargetRegisterInfo *TRI =
410 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
412 MachineFunction &MF = DAG.getMachineFunction();
413 FunctionType *FType = MF.getFunction()->getFunctionType();
414 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
416 assert(CallConv == CallingConv::C);
418 SmallVector<ISD::InputArg, 16> Splits;
419 uint32_t Skipped = 0;
421 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
422 const ISD::InputArg &Arg = Ins[i];
424 // First check if it's a PS input addr
425 if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
426 !Arg.Flags.isByVal()) {
428 assert((PSInputNum <= 15) && "Too many PS inputs!");
431 // We can savely skip PS inputs
437 Info->PSInputAddr |= 1 << PSInputNum++;
440 // Second split vertices into their elements
441 if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
442 ISD::InputArg NewArg = Arg;
443 NewArg.Flags.setSplit();
444 NewArg.VT = Arg.VT.getVectorElementType();
446 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
447 // three or five element vertex only needs three or five registers,
448 // NOT four or eigth.
449 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
450 unsigned NumElements = ParamType->getVectorNumElements();
452 for (unsigned j = 0; j != NumElements; ++j) {
453 Splits.push_back(NewArg);
454 NewArg.PartOffset += NewArg.VT.getStoreSize();
457 } else if (Info->getShaderType() != ShaderType::COMPUTE) {
458 Splits.push_back(Arg);
462 SmallVector<CCValAssign, 16> ArgLocs;
463 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
466 // At least one interpolation mode must be enabled or else the GPU will hang.
467 if (Info->getShaderType() == ShaderType::PIXEL &&
468 (Info->PSInputAddr & 0x7F) == 0) {
469 Info->PSInputAddr |= 1;
470 CCInfo.AllocateReg(AMDGPU::VGPR0);
471 CCInfo.AllocateReg(AMDGPU::VGPR1);
474 // The pointer to the list of arguments is stored in SGPR0, SGPR1
475 // The pointer to the scratch buffer is stored in SGPR2, SGPR3
476 if (Info->getShaderType() == ShaderType::COMPUTE) {
477 Info->NumUserSGPRs = 4;
478 CCInfo.AllocateReg(AMDGPU::SGPR0);
479 CCInfo.AllocateReg(AMDGPU::SGPR1);
480 CCInfo.AllocateReg(AMDGPU::SGPR2);
481 CCInfo.AllocateReg(AMDGPU::SGPR3);
482 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
483 MF.addLiveIn(AMDGPU::SGPR2_SGPR3, &AMDGPU::SReg_64RegClass);
486 if (Info->getShaderType() == ShaderType::COMPUTE) {
487 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
491 AnalyzeFormalArguments(CCInfo, Splits);
493 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
495 const ISD::InputArg &Arg = Ins[i];
496 if (Skipped & (1 << i)) {
497 InVals.push_back(DAG.getUNDEF(Arg.VT));
501 CCValAssign &VA = ArgLocs[ArgIdx++];
502 EVT VT = VA.getLocVT();
506 EVT MemVT = Splits[i].VT;
507 // The first 36 bytes of the input buffer contains information about
508 // thread group and global sizes.
509 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
510 36 + VA.getLocMemOffset(),
511 Ins[i].Flags.isSExt());
512 InVals.push_back(Arg);
515 assert(VA.isRegLoc() && "Parameter must be in a register!");
517 unsigned Reg = VA.getLocReg();
519 if (VT == MVT::i64) {
520 // For now assume it is a pointer
521 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
522 &AMDGPU::SReg_64RegClass);
523 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
524 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
528 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
530 Reg = MF.addLiveIn(Reg, RC);
531 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
533 if (Arg.VT.isVector()) {
535 // Build a vector from the registers
536 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
537 unsigned NumElements = ParamType->getVectorNumElements();
539 SmallVector<SDValue, 4> Regs;
541 for (unsigned j = 1; j != NumElements; ++j) {
542 Reg = ArgLocs[ArgIdx++].getLocReg();
543 Reg = MF.addLiveIn(Reg, RC);
544 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
547 // Fill up the missing vector elements
548 NumElements = Arg.VT.getVectorNumElements() - NumElements;
549 for (unsigned j = 0; j != NumElements; ++j)
550 Regs.push_back(DAG.getUNDEF(VT));
552 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
556 InVals.push_back(Val);
561 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
562 MachineInstr * MI, MachineBasicBlock * BB) const {
564 MachineBasicBlock::iterator I = *MI;
565 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
566 getTargetMachine().getSubtargetImpl()->getInstrInfo());
567 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
569 switch (MI->getOpcode()) {
571 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
572 case AMDGPU::BRANCH: return BB;
573 case AMDGPU::SI_ADDR64_RSRC: {
574 unsigned SuperReg = MI->getOperand(0).getReg();
575 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
576 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
577 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
578 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
579 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
580 .addOperand(MI->getOperand(1));
581 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
583 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
584 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
585 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
587 .addImm(AMDGPU::sub0)
589 .addImm(AMDGPU::sub1);
590 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
592 .addImm(AMDGPU::sub0_sub1)
594 .addImm(AMDGPU::sub2_sub3);
595 MI->eraseFromParent();
598 case AMDGPU::SI_BUFFER_RSRC: {
599 unsigned SuperReg = MI->getOperand(0).getReg();
601 for (unsigned i = 0, e = 4; i < e; ++i) {
602 MachineOperand &Arg = MI->getOperand(i + 1);
605 Args[i] = Arg.getReg();
610 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
611 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
612 .addImm(Arg.getImm());
615 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
618 .addImm(AMDGPU::sub0)
620 .addImm(AMDGPU::sub1)
622 .addImm(AMDGPU::sub2)
624 .addImm(AMDGPU::sub3);
625 MI->eraseFromParent();
628 case AMDGPU::V_SUB_F64: {
629 unsigned DestReg = MI->getOperand(0).getReg();
630 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
631 .addImm(0) // SRC0 modifiers
632 .addReg(MI->getOperand(1).getReg())
633 .addImm(1) // SRC1 modifiers
634 .addReg(MI->getOperand(2).getReg())
637 MI->eraseFromParent();
640 case AMDGPU::SI_RegisterStorePseudo: {
641 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
642 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
643 MachineInstrBuilder MIB =
644 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
646 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
647 MIB.addOperand(MI->getOperand(i));
649 MI->eraseFromParent();
652 case AMDGPU::FABS_SI: {
653 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
654 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
655 getTargetMachine().getSubtargetImpl()->getInstrInfo());
656 DebugLoc DL = MI->getDebugLoc();
657 unsigned DestReg = MI->getOperand(0).getReg();
658 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
660 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Reg)
662 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_AND_B32_e32), DestReg)
663 .addReg(MI->getOperand(1).getReg())
665 MI->eraseFromParent();
668 case AMDGPU::FNEG_SI: {
669 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
670 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
671 getTargetMachine().getSubtargetImpl()->getInstrInfo());
672 DebugLoc DL = MI->getDebugLoc();
673 unsigned DestReg = MI->getOperand(0).getReg();
674 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
676 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Reg)
678 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_XOR_B32_e32), DestReg)
679 .addReg(MI->getOperand(1).getReg())
681 MI->eraseFromParent();
684 case AMDGPU::FCLAMP_SI: {
685 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
686 getTargetMachine().getSubtargetImpl()->getInstrInfo());
687 DebugLoc DL = MI->getDebugLoc();
688 unsigned DestReg = MI->getOperand(0).getReg();
689 BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
690 .addImm(0) // SRC0 modifiers
691 .addOperand(MI->getOperand(1))
692 .addImm(0) // SRC1 modifiers
696 MI->eraseFromParent();
702 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
703 if (!VT.isVector()) {
706 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
709 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
713 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
714 VT = VT.getScalarType();
719 switch (VT.getSimpleVT().SimpleTy) {
721 return false; /* There is V_MAD_F32 for f32 */
731 //===----------------------------------------------------------------------===//
732 // Custom DAG Lowering Operations
733 //===----------------------------------------------------------------------===//
735 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
736 switch (Op.getOpcode()) {
737 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
738 case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
739 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
741 SDValue Result = LowerLOAD(Op, DAG);
742 assert((!Result.getNode() ||
743 Result.getNode()->getNumValues() == 2) &&
744 "Load should return a value and a chain");
750 return LowerTrig(Op, DAG);
751 case ISD::SELECT: return LowerSELECT(Op, DAG);
752 case ISD::FDIV: return LowerFDIV(Op, DAG);
753 case ISD::STORE: return LowerSTORE(Op, DAG);
754 case ISD::GlobalAddress: {
755 MachineFunction &MF = DAG.getMachineFunction();
756 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
757 return LowerGlobalAddress(MFI, Op, DAG);
759 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
760 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
765 /// \brief Helper function for LowerBRCOND
766 static SDNode *findUser(SDValue Value, unsigned Opcode) {
768 SDNode *Parent = Value.getNode();
769 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
772 if (I.getUse().get() != Value)
775 if (I->getOpcode() == Opcode)
781 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
783 MachineFunction &MF = DAG.getMachineFunction();
784 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
785 getTargetMachine().getSubtargetImpl()->getInstrInfo());
786 const SIRegisterInfo &TRI = TII->getRegisterInfo();
787 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
788 unsigned FrameIndex = FINode->getIndex();
790 CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
791 TRI.getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET), MVT::i32);
793 return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
796 /// This transforms the control flow intrinsics to get the branch destination as
797 /// last parameter, also switches branch target with BR if the need arise
798 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
799 SelectionDAG &DAG) const {
803 SDNode *Intr = BRCOND.getOperand(1).getNode();
804 SDValue Target = BRCOND.getOperand(2);
805 SDNode *BR = nullptr;
807 if (Intr->getOpcode() == ISD::SETCC) {
808 // As long as we negate the condition everything is fine
809 SDNode *SetCC = Intr;
810 assert(SetCC->getConstantOperandVal(1) == 1);
811 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
813 Intr = SetCC->getOperand(0).getNode();
816 // Get the target from BR if we don't negate the condition
817 BR = findUser(BRCOND, ISD::BR);
818 Target = BR->getOperand(1);
821 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
823 // Build the result and
824 SmallVector<EVT, 4> Res;
825 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
826 Res.push_back(Intr->getValueType(i));
828 // operands of the new intrinsic call
829 SmallVector<SDValue, 4> Ops;
830 Ops.push_back(BRCOND.getOperand(0));
831 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
832 Ops.push_back(Intr->getOperand(i));
833 Ops.push_back(Target);
835 // build the new intrinsic call
836 SDNode *Result = DAG.getNode(
837 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
838 DAG.getVTList(Res), Ops).getNode();
841 // Give the branch instruction our target
846 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
847 DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
848 BR = NewBR.getNode();
851 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
853 // Copy the intrinsic results to registers
854 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
855 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
859 Chain = DAG.getCopyToReg(
861 CopyToReg->getOperand(1),
862 SDValue(Result, i - 1),
865 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
868 // Remove the old intrinsic from the chain
869 DAG.ReplaceAllUsesOfValueWith(
870 SDValue(Intr, Intr->getNumValues() - 1),
871 Intr->getOperand(0));
876 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
878 SelectionDAG &DAG) const {
879 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
881 if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
882 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
885 const GlobalValue *GV = GSD->getGlobal();
886 MVT PtrVT = getPointerTy(GSD->getAddressSpace());
888 SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
889 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
891 SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
892 DAG.getConstant(0, MVT::i32));
893 SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
894 DAG.getConstant(1, MVT::i32));
896 SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
898 SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
899 PtrHi, DAG.getConstant(0, MVT::i32),
900 SDValue(Lo.getNode(), 1));
901 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
904 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
905 SelectionDAG &DAG) const {
906 MachineFunction &MF = DAG.getMachineFunction();
907 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
909 EVT VT = Op.getValueType();
911 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
913 switch (IntrinsicID) {
914 case Intrinsic::r600_read_ngroups_x:
915 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
916 case Intrinsic::r600_read_ngroups_y:
917 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
918 case Intrinsic::r600_read_ngroups_z:
919 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
920 case Intrinsic::r600_read_global_size_x:
921 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
922 case Intrinsic::r600_read_global_size_y:
923 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
924 case Intrinsic::r600_read_global_size_z:
925 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
926 case Intrinsic::r600_read_local_size_x:
927 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
928 case Intrinsic::r600_read_local_size_y:
929 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
930 case Intrinsic::r600_read_local_size_z:
931 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
932 case Intrinsic::r600_read_tgid_x:
933 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
934 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
935 case Intrinsic::r600_read_tgid_y:
936 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
937 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
938 case Intrinsic::r600_read_tgid_z:
939 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
940 AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
941 case Intrinsic::r600_read_tidig_x:
942 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
944 case Intrinsic::r600_read_tidig_y:
945 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
947 case Intrinsic::r600_read_tidig_z:
948 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
950 case AMDGPUIntrinsic::SI_load_const: {
956 MachineMemOperand *MMO = MF.getMachineMemOperand(
957 MachinePointerInfo(),
958 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
959 VT.getStoreSize(), 4);
960 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
961 Op->getVTList(), Ops, VT, MMO);
963 case AMDGPUIntrinsic::SI_sample:
964 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
965 case AMDGPUIntrinsic::SI_sampleb:
966 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
967 case AMDGPUIntrinsic::SI_sampled:
968 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
969 case AMDGPUIntrinsic::SI_samplel:
970 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
971 case AMDGPUIntrinsic::SI_vs_load_input:
972 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
977 return AMDGPUTargetLowering::LowerOperation(Op, DAG);
981 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
982 SelectionDAG &DAG) const {
983 MachineFunction &MF = DAG.getMachineFunction();
984 SDValue Chain = Op.getOperand(0);
985 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
987 switch (IntrinsicID) {
988 case AMDGPUIntrinsic::SI_tbuffer_store: {
1007 EVT VT = Op.getOperand(3).getValueType();
1009 MachineMemOperand *MMO = MF.getMachineMemOperand(
1010 MachinePointerInfo(),
1011 MachineMemOperand::MOStore,
1012 VT.getStoreSize(), 4);
1013 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1014 Op->getVTList(), Ops, VT, MMO);
1021 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1023 LoadSDNode *Load = cast<LoadSDNode>(Op);
1025 if (Op.getValueType().isVector()) {
1026 assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1027 "Custom lowering for non-i32 vectors hasn't been implemented.");
1028 unsigned NumElements = Op.getValueType().getVectorNumElements();
1029 assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1030 switch (Load->getAddressSpace()) {
1032 case AMDGPUAS::GLOBAL_ADDRESS:
1033 case AMDGPUAS::PRIVATE_ADDRESS:
1034 // v4 loads are supported for private and global memory.
1035 if (NumElements <= 4)
1038 case AMDGPUAS::LOCAL_ADDRESS:
1039 return ScalarizeVectorLoad(Op, DAG);
1043 return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1046 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1048 SelectionDAG &DAG) const {
1049 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1055 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1056 if (Op.getValueType() != MVT::i64)
1060 SDValue Cond = Op.getOperand(0);
1062 SDValue Zero = DAG.getConstant(0, MVT::i32);
1063 SDValue One = DAG.getConstant(1, MVT::i32);
1065 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1066 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1068 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1069 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1071 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1073 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1074 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1076 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1078 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1079 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1082 // Catch division cases where we can use shortcuts with rcp and rsq
1084 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1086 SDValue LHS = Op.getOperand(0);
1087 SDValue RHS = Op.getOperand(1);
1088 EVT VT = Op.getValueType();
1089 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1091 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1092 if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1093 CLHS->isExactlyValue(1.0)) {
1094 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1095 // the CI documentation has a worst case error of 1 ulp.
1096 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1097 // use it as long as we aren't trying to use denormals.
1099 // 1.0 / sqrt(x) -> rsq(x)
1101 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1102 // error seems really high at 2^29 ULP.
1103 if (RHS.getOpcode() == ISD::FSQRT)
1104 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1106 // 1.0 / x -> rcp(x)
1107 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1112 // Turn into multiply by the reciprocal.
1113 // x / y -> x * (1.0 / y)
1114 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1115 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1121 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1122 SDValue FastLowered = LowerFastFDIV(Op, DAG);
1123 if (FastLowered.getNode())
1126 // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1127 // selection error for now rather than do something incorrect.
1128 if (Subtarget->hasFP32Denormals())
1132 SDValue LHS = Op.getOperand(0);
1133 SDValue RHS = Op.getOperand(1);
1135 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1137 const APFloat K0Val(BitsToFloat(0x6f800000));
1138 const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1140 const APFloat K1Val(BitsToFloat(0x2f800000));
1141 const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1143 const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1145 EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1147 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1149 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1151 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1153 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1155 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1157 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1160 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1164 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1165 EVT VT = Op.getValueType();
1168 return LowerFDIV32(Op, DAG);
1171 return LowerFDIV64(Op, DAG);
1173 llvm_unreachable("Unexpected type for fdiv");
1176 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1178 StoreSDNode *Store = cast<StoreSDNode>(Op);
1179 EVT VT = Store->getMemoryVT();
1181 // These stores are legal.
1182 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1183 VT.isVector() && VT.getVectorNumElements() == 2 &&
1184 VT.getVectorElementType() == MVT::i32)
1187 if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1188 if (VT.isVector() && VT.getVectorNumElements() > 4)
1189 return ScalarizeVectorStore(Op, DAG);
1193 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1197 if (VT.isVector() && VT.getVectorNumElements() >= 8)
1198 return ScalarizeVectorStore(Op, DAG);
1201 return DAG.getTruncStore(Store->getChain(), DL,
1202 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1203 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1208 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1209 EVT VT = Op.getValueType();
1210 SDValue Arg = Op.getOperand(0);
1211 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1212 DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1213 DAG.getConstantFP(0.5 / M_PI, VT)));
1215 switch (Op.getOpcode()) {
1217 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1219 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1221 llvm_unreachable("Wrong trig opcode");
1225 //===----------------------------------------------------------------------===//
1226 // Custom DAG optimizations
1227 //===----------------------------------------------------------------------===//
1229 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1230 DAGCombinerInfo &DCI) {
1231 EVT VT = N->getValueType(0);
1232 EVT ScalarVT = VT.getScalarType();
1233 if (ScalarVT != MVT::f32)
1236 SelectionDAG &DAG = DCI.DAG;
1239 SDValue Src = N->getOperand(0);
1240 EVT SrcVT = Src.getValueType();
1242 // TODO: We could try to match extracting the higher bytes, which would be
1243 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1244 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1245 // about in practice.
1246 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1247 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1248 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1249 DCI.AddToWorklist(Cvt.getNode());
1254 // We are primarily trying to catch operations on illegal vector types
1255 // before they are expanded.
1256 // For scalars, we can use the more flexible method of checking masked bits
1257 // after legalization.
1258 if (!DCI.isBeforeLegalize() ||
1259 !SrcVT.isVector() ||
1260 SrcVT.getVectorElementType() != MVT::i8) {
1264 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1266 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1268 unsigned NElts = SrcVT.getVectorNumElements();
1269 if (!SrcVT.isSimple() && NElts != 3)
1272 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1273 // prevent a mess from expanding to v4i32 and repacking.
1274 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1275 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1276 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1277 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1279 LoadSDNode *Load = cast<LoadSDNode>(Src);
1280 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1284 Load->getMemOperand());
1286 // Make sure successors of the original load stay after it by updating
1287 // them to use the new Chain.
1288 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1290 SmallVector<SDValue, 4> Elts;
1291 if (RegVT.isVector())
1292 DAG.ExtractVectorElements(NewLoad, Elts);
1294 Elts.push_back(NewLoad);
1296 SmallVector<SDValue, 4> Ops;
1298 unsigned EltIdx = 0;
1299 for (SDValue Elt : Elts) {
1300 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1301 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1302 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1303 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1304 DCI.AddToWorklist(Cvt.getNode());
1311 assert(Ops.size() == NElts);
1313 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1319 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1321 // This is a variant of
1322 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1324 // The normal DAG combiner will do this, but only if the add has one use since
1325 // that would increase the number of instructions.
1327 // This prevents us from seeing a constant offset that can be folded into a
1328 // memory instruction's addressing mode. If we know the resulting add offset of
1329 // a pointer can be folded into an addressing offset, we can replace the pointer
1330 // operand with the add of new constant offset. This eliminates one of the uses,
1331 // and may allow the remaining use to also be simplified.
1333 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1335 DAGCombinerInfo &DCI) const {
1336 SDValue N0 = N->getOperand(0);
1337 SDValue N1 = N->getOperand(1);
1339 if (N0.getOpcode() != ISD::ADD)
1342 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1346 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1350 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1351 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1353 // If the resulting offset is too large, we can't fold it into the addressing
1355 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1356 if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1359 SelectionDAG &DAG = DCI.DAG;
1361 EVT VT = N->getValueType(0);
1363 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1364 SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1366 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1369 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1370 DAGCombinerInfo &DCI) const {
1371 SelectionDAG &DAG = DCI.DAG;
1373 EVT VT = N->getValueType(0);
1375 switch (N->getOpcode()) {
1376 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1378 SDValue Arg0 = N->getOperand(0);
1379 SDValue Arg1 = N->getOperand(1);
1380 SDValue CC = N->getOperand(2);
1381 ConstantSDNode * C = nullptr;
1382 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1384 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1386 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1387 && Arg0.getOperand(0).getValueType() == MVT::i1
1388 && (C = dyn_cast<ConstantSDNode>(Arg1))
1390 && CCOp == ISD::SETNE) {
1391 return SimplifySetCC(VT, Arg0.getOperand(0),
1392 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1397 case AMDGPUISD::CVT_F32_UBYTE0:
1398 case AMDGPUISD::CVT_F32_UBYTE1:
1399 case AMDGPUISD::CVT_F32_UBYTE2:
1400 case AMDGPUISD::CVT_F32_UBYTE3: {
1401 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1403 SDValue Src = N->getOperand(0);
1404 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1406 APInt KnownZero, KnownOne;
1407 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1408 !DCI.isBeforeLegalizeOps());
1409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1410 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1411 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1412 DCI.CommitTargetLoweringOpt(TLO);
1418 case ISD::UINT_TO_FP: {
1419 return performUCharToFloatCombine(N, DCI);
1423 case ISD::ATOMIC_LOAD:
1424 case ISD::ATOMIC_STORE:
1425 case ISD::ATOMIC_CMP_SWAP:
1426 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1427 case ISD::ATOMIC_SWAP:
1428 case ISD::ATOMIC_LOAD_ADD:
1429 case ISD::ATOMIC_LOAD_SUB:
1430 case ISD::ATOMIC_LOAD_AND:
1431 case ISD::ATOMIC_LOAD_OR:
1432 case ISD::ATOMIC_LOAD_XOR:
1433 case ISD::ATOMIC_LOAD_NAND:
1434 case ISD::ATOMIC_LOAD_MIN:
1435 case ISD::ATOMIC_LOAD_MAX:
1436 case ISD::ATOMIC_LOAD_UMIN:
1437 case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1438 if (DCI.isBeforeLegalize())
1441 MemSDNode *MemNode = cast<MemSDNode>(N);
1442 SDValue Ptr = MemNode->getBasePtr();
1444 // TODO: We could also do this for multiplies.
1445 unsigned AS = MemNode->getAddressSpace();
1446 if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1447 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1449 SmallVector<SDValue, 8> NewOps;
1450 for (unsigned I = 0, N = MemNode->getNumOperands(); I != N; ++I)
1451 NewOps.push_back(MemNode->getOperand(I));
1453 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1454 return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1460 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1463 /// \brief Test if RegClass is one of the VSrc classes
1464 static bool isVSrc(unsigned RegClass) {
1465 return AMDGPU::VSrc_32RegClassID == RegClass ||
1466 AMDGPU::VSrc_64RegClassID == RegClass;
1469 /// \brief Test if RegClass is one of the SSrc classes
1470 static bool isSSrc(unsigned RegClass) {
1471 return AMDGPU::SSrc_32RegClassID == RegClass ||
1472 AMDGPU::SSrc_64RegClassID == RegClass;
1475 /// \brief Analyze the possible immediate value Op
1477 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1478 /// and the immediate value if it's a literal immediate
1479 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1486 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1487 if (Node->getZExtValue() >> 32) {
1490 Imm.I = Node->getSExtValue();
1491 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1492 if (N->getValueType(0) != MVT::f32)
1494 Imm.F = Node->getValueAPF().convertToFloat();
1496 return -1; // It isn't an immediate
1498 if ((Imm.I >= -16 && Imm.I <= 64) ||
1499 Imm.F == 0.5f || Imm.F == -0.5f ||
1500 Imm.F == 1.0f || Imm.F == -1.0f ||
1501 Imm.F == 2.0f || Imm.F == -2.0f ||
1502 Imm.F == 4.0f || Imm.F == -4.0f)
1503 return 0; // It's an inline immediate
1505 return Imm.I; // It's a literal immediate
1508 /// \brief Try to fold an immediate directly into an instruction
1509 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1510 bool &ScalarSlotUsed) const {
1512 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1513 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1514 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1515 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1518 const SDValue &Op = Mov->getOperand(0);
1519 int32_t Value = analyzeImmediate(Op.getNode());
1521 // Not an immediate at all
1524 } else if (Value == 0) {
1525 // Inline immediates can always be fold
1529 } else if (Value == Immediate) {
1530 // Already fold literal immediate
1534 } else if (!ScalarSlotUsed && !Immediate) {
1535 // Fold this literal immediate
1536 ScalarSlotUsed = true;
1546 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1547 SelectionDAG &DAG, const SDValue &Op) const {
1548 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1549 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1550 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1552 if (!Op->isMachineOpcode()) {
1553 switch(Op->getOpcode()) {
1554 case ISD::CopyFromReg: {
1555 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1556 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1557 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1558 return MRI.getRegClass(Reg);
1560 return TRI.getPhysRegClass(Reg);
1562 default: return nullptr;
1565 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1566 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1567 if (OpClassID != -1) {
1568 return TRI.getRegClass(OpClassID);
1570 switch(Op.getMachineOpcode()) {
1571 case AMDGPU::COPY_TO_REGCLASS:
1572 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1573 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1575 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1576 // class, then the register class for the value could be either a
1577 // VReg or and SReg. In order to get a more accurate
1578 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1579 OpClassID == AMDGPU::VSrc_64RegClassID) {
1580 return getRegClassForNode(DAG, Op.getOperand(0));
1582 return TRI.getRegClass(OpClassID);
1583 case AMDGPU::EXTRACT_SUBREG: {
1584 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1585 const TargetRegisterClass *SuperClass =
1586 getRegClassForNode(DAG, Op.getOperand(0));
1587 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1589 case AMDGPU::REG_SEQUENCE:
1590 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1591 return TRI.getRegClass(
1592 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1594 return getRegClassFor(Op.getSimpleValueType());
1598 /// \brief Does "Op" fit into register class "RegClass" ?
1599 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1600 unsigned RegClass) const {
1601 const TargetRegisterInfo *TRI =
1602 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1603 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1607 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1610 /// \brief Make sure that we don't exeed the number of allowed scalars
1611 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1613 bool &ScalarSlotUsed) const {
1615 // First map the operands register class to a destination class
1616 if (RegClass == AMDGPU::VSrc_32RegClassID)
1617 RegClass = AMDGPU::VReg_32RegClassID;
1618 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1619 RegClass = AMDGPU::VReg_64RegClassID;
1623 // Nothing to do if they fit naturally
1624 if (fitsRegClass(DAG, Operand, RegClass))
1627 // If the scalar slot isn't used yet use it now
1628 if (!ScalarSlotUsed) {
1629 ScalarSlotUsed = true;
1633 // This is a conservative aproach. It is possible that we can't determine the
1634 // correct register class and copy too often, but better safe than sorry.
1637 // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1638 if (isa<FrameIndexSDNode>(Operand)) {
1639 unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1640 AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1641 Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1644 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1645 Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1646 Operand.getValueType(), Operand, RC);
1648 Operand = SDValue(Node, 0);
1651 /// \returns true if \p Node's operands are different from the SDValue list
1653 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1654 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1655 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1662 /// \brief Try to fold the Nodes operands into the Node
1663 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1664 SelectionDAG &DAG) const {
1666 // Original encoding (either e32 or e64)
1667 int Opcode = Node->getMachineOpcode();
1668 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1669 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1670 const MCInstrDesc *Desc = &TII->get(Opcode);
1672 unsigned NumDefs = Desc->getNumDefs();
1673 unsigned NumOps = Desc->getNumOperands();
1675 // Commuted opcode if available
1676 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1677 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1679 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1680 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1682 // e64 version if available, -1 otherwise
1683 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1684 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1685 int InputModifiers[3] = {0};
1687 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1689 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1690 bool HaveVSrc = false, HaveSSrc = false;
1692 // First figure out what we already have in this instruction.
1693 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1694 i != e && Op < NumOps; ++i, ++Op) {
1696 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1697 if (isVSrc(RegClass))
1699 else if (isSSrc(RegClass))
1704 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1705 if (Imm != -1 && Imm != 0) {
1706 // Literal immediate
1711 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1712 if (!HaveVSrc && !HaveSSrc)
1715 // No scalar allowed when we have both VSrc and SSrc
1716 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1718 // Second go over the operands and try to fold them
1719 std::vector<SDValue> Ops;
1720 bool Promote2e64 = false;
1721 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1722 i != e && Op < NumOps; ++i, ++Op) {
1724 const SDValue &Operand = Node->getOperand(i);
1725 Ops.push_back(Operand);
1727 // Already folded immediate?
1728 if (isa<ConstantSDNode>(Operand.getNode()) ||
1729 isa<ConstantFPSDNode>(Operand.getNode()))
1732 // Is this a VSrc or SSrc operand?
1733 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1734 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1735 // Try to fold the immediates
1736 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1737 // Folding didn't work, make sure we don't hit the SReg limit.
1738 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1742 // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1743 // These will be lowered to immediates, so we will need to insert a MOV.
1744 if (isa<GlobalAddressSDNode>(Ops[i])) {
1745 SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1746 Operand.getValueType(), Operand);
1747 Ops[i] = SDValue(Node, 0);
1751 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1753 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1754 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1756 // Test if it makes sense to swap operands
1757 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1758 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1759 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1761 // Swap commutable operands
1762 std::swap(Ops[0], Ops[1]);
1774 // Test if it makes sense to switch to e64 encoding
1775 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1776 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1779 int32_t TmpImm = -1;
1780 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1781 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1782 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1784 // Switch to e64 encoding
1792 if (!DescE64 && !Promote2e64)
1794 if (!Operand.isMachineOpcode())
1799 std::vector<SDValue> OldOps(Ops);
1801 bool HasModifiers = TII->hasModifiers(Desc->Opcode);
1802 for (unsigned i = 0; i < OldOps.size(); ++i) {
1805 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1806 Ops.push_back(OldOps[i]);
1808 // Add the modifier flags while promoting
1810 for (unsigned i = 0; i < 2; ++i)
1811 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1815 // Add optional chain and glue
1816 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1817 Ops.push_back(Node->getOperand(i));
1819 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1820 // this case a brand new node is always be created, even if the operands
1821 // are the same as before. So, manually check if anything has been changed.
1822 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1826 // Create a complete new instruction
1827 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1830 /// \brief Helper function for adjustWritemask
1831 static unsigned SubIdx2Lane(unsigned Idx) {
1834 case AMDGPU::sub0: return 0;
1835 case AMDGPU::sub1: return 1;
1836 case AMDGPU::sub2: return 2;
1837 case AMDGPU::sub3: return 3;
1841 /// \brief Adjust the writemask of MIMG instructions
1842 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1843 SelectionDAG &DAG) const {
1844 SDNode *Users[4] = { };
1846 unsigned OldDmask = Node->getConstantOperandVal(0);
1847 unsigned NewDmask = 0;
1849 // Try to figure out the used register components
1850 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1853 // Abort if we can't understand the usage
1854 if (!I->isMachineOpcode() ||
1855 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1858 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1859 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1860 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1862 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1864 // Set which texture component corresponds to the lane.
1866 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1868 Comp = countTrailingZeros(Dmask);
1869 Dmask &= ~(1 << Comp);
1872 // Abort if we have more than one user per component
1877 NewDmask |= 1 << Comp;
1880 // Abort if there's no change
1881 if (NewDmask == OldDmask)
1884 // Adjust the writemask in the node
1885 std::vector<SDValue> Ops;
1886 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1887 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1888 Ops.push_back(Node->getOperand(i));
1889 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1891 // If we only got one lane, replace it with a copy
1892 // (if NewDmask has only one bit set...)
1893 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1894 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1895 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1896 SDLoc(), Users[Lane]->getValueType(0),
1897 SDValue(Node, 0), RC);
1898 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1902 // Update the users of the node with the new indices
1903 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1905 SDNode *User = Users[i];
1909 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1910 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1914 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1915 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1916 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1921 /// \brief Fold the instructions after selecting them.
1922 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1923 SelectionDAG &DAG) const {
1924 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1925 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1926 Node = AdjustRegClass(Node, DAG);
1928 if (TII->isMIMG(Node->getMachineOpcode()))
1929 adjustWritemask(Node, DAG);
1931 return foldOperands(Node, DAG);
1934 /// \brief Assign the register class depending on the number of
1935 /// bits set in the writemask
1936 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1937 SDNode *Node) const {
1938 const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1939 getTargetMachine().getSubtargetImpl()->getInstrInfo());
1940 if (!TII->isMIMG(MI->getOpcode()))
1943 unsigned VReg = MI->getOperand(0).getReg();
1944 unsigned Writemask = MI->getOperand(1).getImm();
1945 unsigned BitsSet = 0;
1946 for (unsigned i = 0; i < 4; ++i)
1947 BitsSet += Writemask & (1 << i) ? 1 : 0;
1949 const TargetRegisterClass *RC;
1952 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1953 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1954 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1957 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1958 MI->setDesc(TII->get(NewOpcode));
1959 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1960 MRI.setRegClass(VReg, RC);
1963 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1964 SelectionDAG &DAG) const {
1967 unsigned NewOpcode = N->getMachineOpcode();
1969 switch (N->getMachineOpcode()) {
1971 case AMDGPU::S_LOAD_DWORD_IMM:
1972 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1974 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1975 if (NewOpcode == N->getMachineOpcode()) {
1976 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1979 case AMDGPU::S_LOAD_DWORDX4_IMM:
1980 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1981 if (NewOpcode == N->getMachineOpcode()) {
1982 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1984 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1987 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1989 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1990 DAG.getConstant(0, MVT::i64)), 0),
1992 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1994 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1999 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2000 const TargetRegisterClass *RC,
2001 unsigned Reg, EVT VT) const {
2002 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2004 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2005 cast<RegisterSDNode>(VReg)->getReg(), VT);