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 //===----------------------------------------------------------------------===//
15 #include "SIISelLowering.h"
17 #include "AMDGPUSubtarget.h"
18 #include "AMDILIntrinsicInfo.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/Function.h"
30 SITargetLowering::SITargetLowering(TargetMachine &TM) :
31 AMDGPUTargetLowering(TM) {
32 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
33 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
35 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
36 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
38 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
39 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
41 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
42 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
43 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
45 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
46 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
48 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
49 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
51 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
52 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
54 computeRegisterProperties();
57 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
58 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
59 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
60 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
61 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
62 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
64 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
65 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
66 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
67 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
68 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
69 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
71 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
72 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
73 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
74 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
76 setOperationAction(ISD::ADD, MVT::i32, Legal);
77 setOperationAction(ISD::ADDC, MVT::i32, Legal);
78 setOperationAction(ISD::ADDE, MVT::i32, Legal);
80 // We need to custom lower vector stores from local memory
81 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
82 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
83 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
84 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
86 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
87 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
89 // We need to custom lower loads/stores from private memory
90 setOperationAction(ISD::LOAD, MVT::i32, Custom);
91 setOperationAction(ISD::LOAD, MVT::i64, Custom);
92 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
93 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
94 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
96 setOperationAction(ISD::STORE, MVT::i1, Custom);
97 setOperationAction(ISD::STORE, MVT::i32, Custom);
98 setOperationAction(ISD::STORE, MVT::i64, Custom);
99 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
100 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
102 setOperationAction(ISD::SELECT, MVT::f32, Promote);
103 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
104 setOperationAction(ISD::SELECT, MVT::i64, Custom);
105 setOperationAction(ISD::SELECT, MVT::f64, Promote);
106 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
108 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
109 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
110 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
111 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
113 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
114 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
116 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
117 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
125 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
130 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
132 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
133 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
134 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
135 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
137 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
139 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
140 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
141 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
142 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
143 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
144 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
146 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
147 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
148 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
149 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
151 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
152 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
153 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
154 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
155 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
157 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
158 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
159 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
160 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
161 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
162 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
164 setOperationAction(ISD::LOAD, MVT::i1, Custom);
166 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
167 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
168 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
170 // These should use UDIVREM, so set them to expand
171 setOperationAction(ISD::UDIV, MVT::i64, Expand);
172 setOperationAction(ISD::UREM, MVT::i64, Expand);
174 // We only support LOAD/STORE and vector manipulation ops for vectors
175 // with > 4 elements.
177 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
180 for (MVT VT : VecTypes) {
181 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
185 case ISD::BUILD_VECTOR:
187 case ISD::EXTRACT_VECTOR_ELT:
188 case ISD::INSERT_VECTOR_ELT:
189 case ISD::CONCAT_VECTORS:
190 case ISD::INSERT_SUBVECTOR:
191 case ISD::EXTRACT_SUBVECTOR:
194 setOperationAction(Op, VT, Expand);
200 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
201 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
202 setOperationAction(ISD::FTRUNC, VT, Expand);
203 setOperationAction(ISD::FCEIL, VT, Expand);
204 setOperationAction(ISD::FFLOOR, VT, Expand);
207 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
208 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
209 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
210 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
211 setOperationAction(ISD::FRINT, MVT::f64, Legal);
214 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
216 setTargetDAGCombine(ISD::SELECT_CC);
217 setTargetDAGCombine(ISD::SETCC);
219 setSchedulingPreference(Sched::RegPressure);
222 //===----------------------------------------------------------------------===//
223 // TargetLowering queries
224 //===----------------------------------------------------------------------===//
226 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
228 bool *IsFast) const {
232 // XXX: This depends on the address space and also we may want to revist
233 // the alignment values we specify in the DataLayout.
235 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
236 // which isn't a simple VT.
237 if (!VT.isSimple() || VT == MVT::Other)
240 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
241 // see what for specifically. The wording everywhere else seems to be the
244 // 3.6.4 - Operations using pairs of VGPRs (for example: double-floats) have
245 // no alignment restrictions.
246 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
247 // Using any pair of GPRs should be the same as any other pair.
250 return VT.bitsGE(MVT::i64);
253 // XXX - The only mention I see of this in the ISA manual is for LDS direct
254 // reads the "byte address and must be dword aligned". Is it also true for the
255 // normal loads and stores?
256 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS)
259 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
260 // byte-address are ignored, thus forcing Dword alignment.
263 return VT.bitsGT(MVT::i32);
266 bool SITargetLowering::shouldSplitVectorType(EVT VT) const {
267 return VT.getScalarType().bitsLE(MVT::i16);
270 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
272 const SIInstrInfo *TII =
273 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
274 return TII->isInlineConstant(Imm);
277 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
278 SDLoc DL, SDValue Chain,
279 unsigned Offset, bool Signed) const {
280 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
281 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
282 AMDGPUAS::CONSTANT_ADDRESS);
283 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
284 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
285 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
286 DAG.getConstant(Offset, MVT::i64));
287 return DAG.getExtLoad(Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
288 MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
289 false, false, MemVT.getSizeInBits() >> 3);
293 SDValue SITargetLowering::LowerFormalArguments(
295 CallingConv::ID CallConv,
297 const SmallVectorImpl<ISD::InputArg> &Ins,
298 SDLoc DL, SelectionDAG &DAG,
299 SmallVectorImpl<SDValue> &InVals) const {
301 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
303 MachineFunction &MF = DAG.getMachineFunction();
304 FunctionType *FType = MF.getFunction()->getFunctionType();
305 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
307 assert(CallConv == CallingConv::C);
309 SmallVector<ISD::InputArg, 16> Splits;
310 uint32_t Skipped = 0;
312 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
313 const ISD::InputArg &Arg = Ins[i];
315 // First check if it's a PS input addr
316 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
317 !Arg.Flags.isByVal()) {
319 assert((PSInputNum <= 15) && "Too many PS inputs!");
322 // We can savely skip PS inputs
328 Info->PSInputAddr |= 1 << PSInputNum++;
331 // Second split vertices into their elements
332 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
333 ISD::InputArg NewArg = Arg;
334 NewArg.Flags.setSplit();
335 NewArg.VT = Arg.VT.getVectorElementType();
337 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
338 // three or five element vertex only needs three or five registers,
339 // NOT four or eigth.
340 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
341 unsigned NumElements = ParamType->getVectorNumElements();
343 for (unsigned j = 0; j != NumElements; ++j) {
344 Splits.push_back(NewArg);
345 NewArg.PartOffset += NewArg.VT.getStoreSize();
348 } else if (Info->ShaderType != ShaderType::COMPUTE) {
349 Splits.push_back(Arg);
353 SmallVector<CCValAssign, 16> ArgLocs;
354 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
355 getTargetMachine(), ArgLocs, *DAG.getContext());
357 // At least one interpolation mode must be enabled or else the GPU will hang.
358 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
359 Info->PSInputAddr |= 1;
360 CCInfo.AllocateReg(AMDGPU::VGPR0);
361 CCInfo.AllocateReg(AMDGPU::VGPR1);
364 // The pointer to the list of arguments is stored in SGPR0, SGPR1
365 if (Info->ShaderType == ShaderType::COMPUTE) {
366 CCInfo.AllocateReg(AMDGPU::SGPR0);
367 CCInfo.AllocateReg(AMDGPU::SGPR1);
368 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
371 if (Info->ShaderType == ShaderType::COMPUTE) {
372 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
376 AnalyzeFormalArguments(CCInfo, Splits);
378 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
380 const ISD::InputArg &Arg = Ins[i];
381 if (Skipped & (1 << i)) {
382 InVals.push_back(DAG.getUNDEF(Arg.VT));
386 CCValAssign &VA = ArgLocs[ArgIdx++];
387 EVT VT = VA.getLocVT();
391 EVT MemVT = Splits[i].VT;
392 // The first 36 bytes of the input buffer contains information about
393 // thread group and global sizes.
394 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
395 36 + VA.getLocMemOffset(),
396 Ins[i].Flags.isSExt());
397 InVals.push_back(Arg);
400 assert(VA.isRegLoc() && "Parameter must be in a register!");
402 unsigned Reg = VA.getLocReg();
404 if (VT == MVT::i64) {
405 // For now assume it is a pointer
406 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
407 &AMDGPU::SReg_64RegClass);
408 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
409 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
413 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
415 Reg = MF.addLiveIn(Reg, RC);
416 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
418 if (Arg.VT.isVector()) {
420 // Build a vector from the registers
421 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
422 unsigned NumElements = ParamType->getVectorNumElements();
424 SmallVector<SDValue, 4> Regs;
426 for (unsigned j = 1; j != NumElements; ++j) {
427 Reg = ArgLocs[ArgIdx++].getLocReg();
428 Reg = MF.addLiveIn(Reg, RC);
429 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
432 // Fill up the missing vector elements
433 NumElements = Arg.VT.getVectorNumElements() - NumElements;
434 for (unsigned j = 0; j != NumElements; ++j)
435 Regs.push_back(DAG.getUNDEF(VT));
437 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
441 InVals.push_back(Val);
446 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
447 MachineInstr * MI, MachineBasicBlock * BB) const {
449 MachineBasicBlock::iterator I = *MI;
450 const SIInstrInfo *TII =
451 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
452 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
454 switch (MI->getOpcode()) {
456 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
457 case AMDGPU::BRANCH: return BB;
458 case AMDGPU::SI_ADDR64_RSRC: {
459 unsigned SuperReg = MI->getOperand(0).getReg();
460 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
461 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
462 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
463 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
464 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
465 .addOperand(MI->getOperand(1));
466 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
468 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
469 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
470 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
472 .addImm(AMDGPU::sub0)
474 .addImm(AMDGPU::sub1);
475 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
477 .addImm(AMDGPU::sub0_sub1)
479 .addImm(AMDGPU::sub2_sub3);
480 MI->eraseFromParent();
483 case AMDGPU::V_SUB_F64:
484 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
485 MI->getOperand(0).getReg())
486 .addReg(MI->getOperand(1).getReg())
487 .addReg(MI->getOperand(2).getReg())
488 .addImm(0) /* src2 */
490 .addImm(0) /* CLAMP */
491 .addImm(0) /* OMOD */
492 .addImm(2); /* NEG */
493 MI->eraseFromParent();
496 case AMDGPU::SI_RegisterStorePseudo: {
497 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
498 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
499 MachineInstrBuilder MIB =
500 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
502 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
503 MIB.addOperand(MI->getOperand(i));
505 MI->eraseFromParent();
508 case AMDGPU::FABS_SI: {
509 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
510 const SIInstrInfo *TII =
511 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
512 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
513 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
516 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_AND_B32_e32),
517 MI->getOperand(0).getReg())
518 .addReg(MI->getOperand(1).getReg())
520 MI->eraseFromParent();
523 case AMDGPU::FNEG_SI: {
524 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
525 const SIInstrInfo *TII =
526 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
527 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
528 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
531 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_XOR_B32_e32),
532 MI->getOperand(0).getReg())
533 .addReg(MI->getOperand(1).getReg())
535 MI->eraseFromParent();
538 case AMDGPU::FCLAMP_SI: {
539 const SIInstrInfo *TII =
540 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
541 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F32_e64),
542 MI->getOperand(0).getReg())
543 .addImm(0) // SRC0 modifiers
544 .addOperand(MI->getOperand(1))
545 .addImm(0) // SRC1 modifiers
549 MI->eraseFromParent();
555 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
556 if (!VT.isVector()) {
559 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
562 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
566 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
567 VT = VT.getScalarType();
572 switch (VT.getSimpleVT().SimpleTy) {
574 return false; /* There is V_MAD_F32 for f32 */
584 //===----------------------------------------------------------------------===//
585 // Custom DAG Lowering Operations
586 //===----------------------------------------------------------------------===//
588 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
589 MachineFunction &MF = DAG.getMachineFunction();
590 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
591 switch (Op.getOpcode()) {
592 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
593 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
595 LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
596 if (Op.getValueType().isVector() &&
597 (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
598 Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
599 (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
600 Op.getValueType().getVectorNumElements() > 4))) {
601 SDValue MergedValues[2] = {
602 SplitVectorLoad(Op, DAG),
605 return DAG.getMergeValues(MergedValues, SDLoc(Op));
607 return LowerLOAD(Op, DAG);
611 case ISD::SELECT: return LowerSELECT(Op, DAG);
612 case ISD::STORE: return LowerSTORE(Op, DAG);
613 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
614 case ISD::INTRINSIC_WO_CHAIN: {
615 unsigned IntrinsicID =
616 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
617 EVT VT = Op.getValueType();
619 //XXX: Hardcoded we only use two to store the pointer to the parameters.
620 unsigned NumUserSGPRs = 2;
621 switch (IntrinsicID) {
622 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
623 case Intrinsic::r600_read_ngroups_x:
624 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
625 case Intrinsic::r600_read_ngroups_y:
626 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
627 case Intrinsic::r600_read_ngroups_z:
628 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
629 case Intrinsic::r600_read_global_size_x:
630 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
631 case Intrinsic::r600_read_global_size_y:
632 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
633 case Intrinsic::r600_read_global_size_z:
634 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
635 case Intrinsic::r600_read_local_size_x:
636 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
637 case Intrinsic::r600_read_local_size_y:
638 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
639 case Intrinsic::r600_read_local_size_z:
640 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
641 case Intrinsic::r600_read_tgid_x:
642 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
643 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
644 case Intrinsic::r600_read_tgid_y:
645 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
646 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
647 case Intrinsic::r600_read_tgid_z:
648 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
649 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
650 case Intrinsic::r600_read_tidig_x:
651 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
653 case Intrinsic::r600_read_tidig_y:
654 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
656 case Intrinsic::r600_read_tidig_z:
657 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
659 case AMDGPUIntrinsic::SI_load_const: {
665 MachineMemOperand *MMO = MF.getMachineMemOperand(
666 MachinePointerInfo(),
667 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
668 VT.getSizeInBits() / 8, 4);
669 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
670 Op->getVTList(), Ops, VT, MMO);
672 case AMDGPUIntrinsic::SI_sample:
673 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
674 case AMDGPUIntrinsic::SI_sampleb:
675 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
676 case AMDGPUIntrinsic::SI_sampled:
677 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
678 case AMDGPUIntrinsic::SI_samplel:
679 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
680 case AMDGPUIntrinsic::SI_vs_load_input:
681 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
688 case ISD::INTRINSIC_VOID:
689 SDValue Chain = Op.getOperand(0);
690 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
692 switch (IntrinsicID) {
693 case AMDGPUIntrinsic::SI_tbuffer_store: {
711 EVT VT = Op.getOperand(3).getValueType();
713 MachineMemOperand *MMO = MF.getMachineMemOperand(
714 MachinePointerInfo(),
715 MachineMemOperand::MOStore,
716 VT.getSizeInBits() / 8, 4);
717 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
718 Op->getVTList(), Ops, VT, MMO);
727 /// \brief Helper function for LowerBRCOND
728 static SDNode *findUser(SDValue Value, unsigned Opcode) {
730 SDNode *Parent = Value.getNode();
731 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
734 if (I.getUse().get() != Value)
737 if (I->getOpcode() == Opcode)
743 /// This transforms the control flow intrinsics to get the branch destination as
744 /// last parameter, also switches branch target with BR if the need arise
745 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
746 SelectionDAG &DAG) const {
750 SDNode *Intr = BRCOND.getOperand(1).getNode();
751 SDValue Target = BRCOND.getOperand(2);
752 SDNode *BR = nullptr;
754 if (Intr->getOpcode() == ISD::SETCC) {
755 // As long as we negate the condition everything is fine
756 SDNode *SetCC = Intr;
757 assert(SetCC->getConstantOperandVal(1) == 1);
758 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
760 Intr = SetCC->getOperand(0).getNode();
763 // Get the target from BR if we don't negate the condition
764 BR = findUser(BRCOND, ISD::BR);
765 Target = BR->getOperand(1);
768 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
770 // Build the result and
771 SmallVector<EVT, 4> Res;
772 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
773 Res.push_back(Intr->getValueType(i));
775 // operands of the new intrinsic call
776 SmallVector<SDValue, 4> Ops;
777 Ops.push_back(BRCOND.getOperand(0));
778 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
779 Ops.push_back(Intr->getOperand(i));
780 Ops.push_back(Target);
782 // build the new intrinsic call
783 SDNode *Result = DAG.getNode(
784 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
785 DAG.getVTList(Res), Ops).getNode();
788 // Give the branch instruction our target
793 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops);
796 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
798 // Copy the intrinsic results to registers
799 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
800 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
804 Chain = DAG.getCopyToReg(
806 CopyToReg->getOperand(1),
807 SDValue(Result, i - 1),
810 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
813 // Remove the old intrinsic from the chain
814 DAG.ReplaceAllUsesOfValueWith(
815 SDValue(Intr, Intr->getNumValues() - 1),
816 Intr->getOperand(0));
821 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
823 LoadSDNode *Load = cast<LoadSDNode>(Op);
824 SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
825 SDValue MergedValues[2];
826 MergedValues[1] = Load->getChain();
828 MergedValues[0] = Ret;
829 return DAG.getMergeValues(MergedValues, DL);
832 if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
836 EVT MemVT = Load->getMemoryVT();
838 assert(!MemVT.isVector() && "Private loads should be scalarized");
839 assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
841 SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
842 DAG.getConstant(2, MVT::i32));
843 Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
844 Load->getChain(), Ptr,
845 DAG.getTargetConstant(0, MVT::i32),
847 if (MemVT.getSizeInBits() == 64) {
848 SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
849 DAG.getConstant(1, MVT::i32));
851 SDValue LoadUpper = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
852 Load->getChain(), IncPtr,
853 DAG.getTargetConstant(0, MVT::i32),
856 Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ret, LoadUpper);
859 MergedValues[0] = Ret;
860 return DAG.getMergeValues(MergedValues, DL);
864 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
866 SelectionDAG &DAG) const {
867 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
873 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
874 if (Op.getValueType() != MVT::i64)
878 SDValue Cond = Op.getOperand(0);
880 SDValue Zero = DAG.getConstant(0, MVT::i32);
881 SDValue One = DAG.getConstant(1, MVT::i32);
883 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
884 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
886 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
887 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
889 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
891 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
892 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
894 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
896 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
897 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
900 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
902 StoreSDNode *Store = cast<StoreSDNode>(Op);
903 EVT VT = Store->getMemoryVT();
905 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
909 if (VT.isVector() && VT.getVectorNumElements() >= 8)
910 return SplitVectorStore(Op, DAG);
913 return DAG.getTruncStore(Store->getChain(), DL,
914 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
915 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
917 if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
920 SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
921 DAG.getConstant(2, MVT::i32));
922 SDValue Chain = Store->getChain();
923 SmallVector<SDValue, 8> Values;
925 if (Store->isTruncatingStore()) {
927 if (Store->getMemoryVT() == MVT::i8) {
929 } else if (Store->getMemoryVT() == MVT::i16) {
932 SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
933 Chain, Store->getBasePtr(),
934 DAG.getConstant(0, MVT::i32));
935 SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
936 DAG.getConstant(0x3, MVT::i32));
937 SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
938 DAG.getConstant(3, MVT::i32));
939 SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
940 DAG.getConstant(Mask, MVT::i32));
941 SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
942 MaskedValue, ShiftAmt);
943 SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
944 DAG.getConstant(32, MVT::i32), ShiftAmt);
945 SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
946 DAG.getConstant(Mask, MVT::i32),
948 Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
949 Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
951 Values.push_back(Dst);
952 } else if (VT == MVT::i64) {
953 for (unsigned i = 0; i < 2; ++i) {
954 Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
955 Store->getValue(), DAG.getConstant(i, MVT::i32)));
957 } else if (VT == MVT::i128) {
958 for (unsigned i = 0; i < 2; ++i) {
959 for (unsigned j = 0; j < 2; ++j) {
960 Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
961 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
962 Store->getValue(), DAG.getConstant(i, MVT::i32)),
963 DAG.getConstant(j, MVT::i32)));
967 Values.push_back(Store->getValue());
970 for (unsigned i = 0; i < Values.size(); ++i) {
971 SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
972 Ptr, DAG.getConstant(i, MVT::i32));
973 Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
974 Chain, Values[i], PartPtr,
975 DAG.getTargetConstant(0, MVT::i32));
980 //===----------------------------------------------------------------------===//
981 // Custom DAG optimizations
982 //===----------------------------------------------------------------------===//
984 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
985 DAGCombinerInfo &DCI) const {
986 SelectionDAG &DAG = DCI.DAG;
988 EVT VT = N->getValueType(0);
990 switch (N->getOpcode()) {
991 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
992 case ISD::SELECT_CC: {
993 ConstantSDNode *True, *False;
994 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
995 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
996 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
997 && True->isAllOnesValue()
998 && False->isNullValue()
1000 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
1001 N->getOperand(1), N->getOperand(4));
1007 SDValue Arg0 = N->getOperand(0);
1008 SDValue Arg1 = N->getOperand(1);
1009 SDValue CC = N->getOperand(2);
1010 ConstantSDNode * C = nullptr;
1011 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1013 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1015 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1016 && Arg0.getOperand(0).getValueType() == MVT::i1
1017 && (C = dyn_cast<ConstantSDNode>(Arg1))
1019 && CCOp == ISD::SETNE) {
1020 return SimplifySetCC(VT, Arg0.getOperand(0),
1021 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1027 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1030 /// \brief Test if RegClass is one of the VSrc classes
1031 static bool isVSrc(unsigned RegClass) {
1032 return AMDGPU::VSrc_32RegClassID == RegClass ||
1033 AMDGPU::VSrc_64RegClassID == RegClass;
1036 /// \brief Test if RegClass is one of the SSrc classes
1037 static bool isSSrc(unsigned RegClass) {
1038 return AMDGPU::SSrc_32RegClassID == RegClass ||
1039 AMDGPU::SSrc_64RegClassID == RegClass;
1042 /// \brief Analyze the possible immediate value Op
1044 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1045 /// and the immediate value if it's a literal immediate
1046 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1053 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1054 if (Node->getZExtValue() >> 32) {
1057 Imm.I = Node->getSExtValue();
1058 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1059 if (N->getValueType(0) != MVT::f32)
1061 Imm.F = Node->getValueAPF().convertToFloat();
1063 return -1; // It isn't an immediate
1065 if ((Imm.I >= -16 && Imm.I <= 64) ||
1066 Imm.F == 0.5f || Imm.F == -0.5f ||
1067 Imm.F == 1.0f || Imm.F == -1.0f ||
1068 Imm.F == 2.0f || Imm.F == -2.0f ||
1069 Imm.F == 4.0f || Imm.F == -4.0f)
1070 return 0; // It's an inline immediate
1072 return Imm.I; // It's a literal immediate
1075 /// \brief Try to fold an immediate directly into an instruction
1076 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1077 bool &ScalarSlotUsed) const {
1079 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1080 const SIInstrInfo *TII =
1081 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1082 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1085 const SDValue &Op = Mov->getOperand(0);
1086 int32_t Value = analyzeImmediate(Op.getNode());
1088 // Not an immediate at all
1091 } else if (Value == 0) {
1092 // Inline immediates can always be fold
1096 } else if (Value == Immediate) {
1097 // Already fold literal immediate
1101 } else if (!ScalarSlotUsed && !Immediate) {
1102 // Fold this literal immediate
1103 ScalarSlotUsed = true;
1113 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1114 SelectionDAG &DAG, const SDValue &Op) const {
1115 const SIInstrInfo *TII =
1116 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1117 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1119 if (!Op->isMachineOpcode()) {
1120 switch(Op->getOpcode()) {
1121 case ISD::CopyFromReg: {
1122 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1123 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1124 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1125 return MRI.getRegClass(Reg);
1127 return TRI.getPhysRegClass(Reg);
1129 default: return nullptr;
1132 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1133 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1134 if (OpClassID != -1) {
1135 return TRI.getRegClass(OpClassID);
1137 switch(Op.getMachineOpcode()) {
1138 case AMDGPU::COPY_TO_REGCLASS:
1139 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1140 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1142 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1143 // class, then the register class for the value could be either a
1144 // VReg or and SReg. In order to get a more accurate
1145 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1146 OpClassID == AMDGPU::VSrc_64RegClassID) {
1147 return getRegClassForNode(DAG, Op.getOperand(0));
1149 return TRI.getRegClass(OpClassID);
1150 case AMDGPU::EXTRACT_SUBREG: {
1151 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1152 const TargetRegisterClass *SuperClass =
1153 getRegClassForNode(DAG, Op.getOperand(0));
1154 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1156 case AMDGPU::REG_SEQUENCE:
1157 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1158 return TRI.getRegClass(
1159 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1161 return getRegClassFor(Op.getSimpleValueType());
1165 /// \brief Does "Op" fit into register class "RegClass" ?
1166 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1167 unsigned RegClass) const {
1168 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1169 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1173 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1176 /// \brief Make sure that we don't exeed the number of allowed scalars
1177 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1179 bool &ScalarSlotUsed) const {
1181 // First map the operands register class to a destination class
1182 if (RegClass == AMDGPU::VSrc_32RegClassID)
1183 RegClass = AMDGPU::VReg_32RegClassID;
1184 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1185 RegClass = AMDGPU::VReg_64RegClassID;
1189 // Nothing to do if they fit naturally
1190 if (fitsRegClass(DAG, Operand, RegClass))
1193 // If the scalar slot isn't used yet use it now
1194 if (!ScalarSlotUsed) {
1195 ScalarSlotUsed = true;
1199 // This is a conservative aproach. It is possible that we can't determine the
1200 // correct register class and copy too often, but better safe than sorry.
1201 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1202 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1203 Operand.getValueType(), Operand, RC);
1204 Operand = SDValue(Node, 0);
1207 /// \returns true if \p Node's operands are different from the SDValue list
1209 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1210 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1211 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1218 /// \brief Try to fold the Nodes operands into the Node
1219 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1220 SelectionDAG &DAG) const {
1222 // Original encoding (either e32 or e64)
1223 int Opcode = Node->getMachineOpcode();
1224 const SIInstrInfo *TII =
1225 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1226 const MCInstrDesc *Desc = &TII->get(Opcode);
1228 unsigned NumDefs = Desc->getNumDefs();
1229 unsigned NumOps = Desc->getNumOperands();
1231 // Commuted opcode if available
1232 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1233 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1235 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1236 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1238 // e64 version if available, -1 otherwise
1239 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1240 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1241 int InputModifiers[3] = {0};
1243 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1245 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1246 bool HaveVSrc = false, HaveSSrc = false;
1248 // First figure out what we already have in this instruction.
1249 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1250 i != e && Op < NumOps; ++i, ++Op) {
1252 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1253 if (isVSrc(RegClass))
1255 else if (isSSrc(RegClass))
1260 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1261 if (Imm != -1 && Imm != 0) {
1262 // Literal immediate
1267 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1268 if (!HaveVSrc && !HaveSSrc)
1271 // No scalar allowed when we have both VSrc and SSrc
1272 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1274 // Second go over the operands and try to fold them
1275 std::vector<SDValue> Ops;
1276 bool Promote2e64 = false;
1277 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1278 i != e && Op < NumOps; ++i, ++Op) {
1280 const SDValue &Operand = Node->getOperand(i);
1281 Ops.push_back(Operand);
1283 // Already folded immediate?
1284 if (isa<ConstantSDNode>(Operand.getNode()) ||
1285 isa<ConstantFPSDNode>(Operand.getNode()))
1288 // Is this a VSrc or SSrc operand?
1289 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1290 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1291 // Try to fold the immediates
1292 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1293 // Folding didn't work, make sure we don't hit the SReg limit.
1294 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1299 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1301 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1302 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1304 // Test if it makes sense to swap operands
1305 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1306 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1307 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1309 // Swap commutable operands
1310 std::swap(Ops[0], Ops[1]);
1322 // Test if it makes sense to switch to e64 encoding
1323 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1324 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1327 int32_t TmpImm = -1;
1328 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1329 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1330 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1332 // Switch to e64 encoding
1340 if (!DescE64 && !Promote2e64)
1342 if (!Operand.isMachineOpcode())
1344 if (Operand.getMachineOpcode() == AMDGPU::FNEG_SI) {
1346 Ops.push_back(Operand.getOperand(0));
1347 InputModifiers[i] = 1;
1354 else if (Operand.getMachineOpcode() == AMDGPU::FABS_SI) {
1356 Ops.push_back(Operand.getOperand(0));
1357 InputModifiers[i] = 2;
1367 std::vector<SDValue> OldOps(Ops);
1369 for (unsigned i = 0; i < OldOps.size(); ++i) {
1371 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1372 Ops.push_back(OldOps[i]);
1374 // Add the modifier flags while promoting
1375 for (unsigned i = 0; i < 2; ++i)
1376 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1379 // Add optional chain and glue
1380 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1381 Ops.push_back(Node->getOperand(i));
1383 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1384 // this case a brand new node is always be created, even if the operands
1385 // are the same as before. So, manually check if anything has been changed.
1386 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1390 // Create a complete new instruction
1391 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1394 /// \brief Helper function for adjustWritemask
1395 static unsigned SubIdx2Lane(unsigned Idx) {
1398 case AMDGPU::sub0: return 0;
1399 case AMDGPU::sub1: return 1;
1400 case AMDGPU::sub2: return 2;
1401 case AMDGPU::sub3: return 3;
1405 /// \brief Adjust the writemask of MIMG instructions
1406 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1407 SelectionDAG &DAG) const {
1408 SDNode *Users[4] = { };
1410 unsigned OldDmask = Node->getConstantOperandVal(0);
1411 unsigned NewDmask = 0;
1413 // Try to figure out the used register components
1414 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1417 // Abort if we can't understand the usage
1418 if (!I->isMachineOpcode() ||
1419 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1422 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1423 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1424 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1426 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1428 // Set which texture component corresponds to the lane.
1430 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1432 Comp = countTrailingZeros(Dmask);
1433 Dmask &= ~(1 << Comp);
1436 // Abort if we have more than one user per component
1441 NewDmask |= 1 << Comp;
1444 // Abort if there's no change
1445 if (NewDmask == OldDmask)
1448 // Adjust the writemask in the node
1449 std::vector<SDValue> Ops;
1450 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1451 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1452 Ops.push_back(Node->getOperand(i));
1453 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1455 // If we only got one lane, replace it with a copy
1456 // (if NewDmask has only one bit set...)
1457 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1458 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1459 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1460 SDLoc(), Users[Lane]->getValueType(0),
1461 SDValue(Node, 0), RC);
1462 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1466 // Update the users of the node with the new indices
1467 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1469 SDNode *User = Users[i];
1473 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1474 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1478 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1479 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1480 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1485 /// \brief Fold the instructions after selecting them.
1486 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1487 SelectionDAG &DAG) const {
1488 const SIInstrInfo *TII =
1489 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1490 Node = AdjustRegClass(Node, DAG);
1492 if (TII->isMIMG(Node->getMachineOpcode()))
1493 adjustWritemask(Node, DAG);
1495 return foldOperands(Node, DAG);
1498 /// \brief Assign the register class depending on the number of
1499 /// bits set in the writemask
1500 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1501 SDNode *Node) const {
1502 const SIInstrInfo *TII =
1503 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1504 if (!TII->isMIMG(MI->getOpcode()))
1507 unsigned VReg = MI->getOperand(0).getReg();
1508 unsigned Writemask = MI->getOperand(1).getImm();
1509 unsigned BitsSet = 0;
1510 for (unsigned i = 0; i < 4; ++i)
1511 BitsSet += Writemask & (1 << i) ? 1 : 0;
1513 const TargetRegisterClass *RC;
1516 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1517 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1518 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1521 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1522 MI->setDesc(TII->get(NewOpcode));
1523 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1524 MRI.setRegClass(VReg, RC);
1527 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1528 SelectionDAG &DAG) const {
1531 unsigned NewOpcode = N->getMachineOpcode();
1533 switch (N->getMachineOpcode()) {
1535 case AMDGPU::S_LOAD_DWORD_IMM:
1536 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1538 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1539 if (NewOpcode == N->getMachineOpcode()) {
1540 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1543 case AMDGPU::S_LOAD_DWORDX4_IMM:
1544 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1545 if (NewOpcode == N->getMachineOpcode()) {
1546 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1548 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1551 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1553 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1554 DAG.getConstant(0, MVT::i64)), 0),
1556 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1558 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1563 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1564 const TargetRegisterClass *RC,
1565 unsigned Reg, EVT VT) const {
1566 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1568 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1569 cast<RegisterSDNode>(VReg)->getReg(), VT);