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 "AMDILIntrinsicInfo.h"
18 #include "SIInstrInfo.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/IR/Function.h"
27 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32 AMDGPUTargetLowering(TM) {
34 addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
35 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
37 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
38 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
39 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
41 addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
42 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
44 addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
46 addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
47 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
49 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
50 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
51 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
53 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
54 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
56 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
57 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
59 computeRegisterProperties();
61 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
63 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
66 setOperationAction(ISD::ADD, MVT::i64, Legal);
67 setOperationAction(ISD::ADD, MVT::i32, Legal);
69 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
70 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
72 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
74 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
76 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
78 setTargetDAGCombine(ISD::SELECT_CC);
80 setTargetDAGCombine(ISD::SETCC);
82 setSchedulingPreference(Sched::RegPressure);
85 //===----------------------------------------------------------------------===//
86 // TargetLowering queries
87 //===----------------------------------------------------------------------===//
89 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
91 // XXX: This depends on the address space and also we may want to revist
92 // the alignment values we specify in the DataLayout.
93 return VT.bitsGT(MVT::i32);
97 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
98 SDLoc DL, SDValue Chain,
99 unsigned Offset) const {
100 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
101 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
102 AMDGPUAS::CONSTANT_ADDRESS);
103 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
104 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
105 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
106 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
107 DAG.getConstant(Offset, MVT::i64));
108 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
109 MachinePointerInfo(UndefValue::get(PtrTy)),
110 VT, false, false, ArgVT.getSizeInBits() >> 3);
114 SDValue SITargetLowering::LowerFormalArguments(
116 CallingConv::ID CallConv,
118 const SmallVectorImpl<ISD::InputArg> &Ins,
119 SDLoc DL, SelectionDAG &DAG,
120 SmallVectorImpl<SDValue> &InVals) const {
122 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
124 MachineFunction &MF = DAG.getMachineFunction();
125 FunctionType *FType = MF.getFunction()->getFunctionType();
126 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
128 assert(CallConv == CallingConv::C);
130 SmallVector<ISD::InputArg, 16> Splits;
131 uint32_t Skipped = 0;
133 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
134 const ISD::InputArg &Arg = Ins[i];
136 // First check if it's a PS input addr
137 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
139 assert((PSInputNum <= 15) && "Too many PS inputs!");
142 // We can savely skip PS inputs
148 Info->PSInputAddr |= 1 << PSInputNum++;
151 // Second split vertices into their elements
152 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
153 ISD::InputArg NewArg = Arg;
154 NewArg.Flags.setSplit();
155 NewArg.VT = Arg.VT.getVectorElementType();
157 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
158 // three or five element vertex only needs three or five registers,
159 // NOT four or eigth.
160 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
161 unsigned NumElements = ParamType->getVectorNumElements();
163 for (unsigned j = 0; j != NumElements; ++j) {
164 Splits.push_back(NewArg);
165 NewArg.PartOffset += NewArg.VT.getStoreSize();
169 Splits.push_back(Arg);
173 SmallVector<CCValAssign, 16> ArgLocs;
174 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
175 getTargetMachine(), ArgLocs, *DAG.getContext());
177 // At least one interpolation mode must be enabled or else the GPU will hang.
178 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
179 Info->PSInputAddr |= 1;
180 CCInfo.AllocateReg(AMDGPU::VGPR0);
181 CCInfo.AllocateReg(AMDGPU::VGPR1);
184 // The pointer to the list of arguments is stored in SGPR0, SGPR1
185 if (Info->ShaderType == ShaderType::COMPUTE) {
186 CCInfo.AllocateReg(AMDGPU::SGPR0);
187 CCInfo.AllocateReg(AMDGPU::SGPR1);
188 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
191 AnalyzeFormalArguments(CCInfo, Splits);
193 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
195 const ISD::InputArg &Arg = Ins[i];
196 if (Skipped & (1 << i)) {
197 InVals.push_back(DAG.getUNDEF(Arg.VT));
201 CCValAssign &VA = ArgLocs[ArgIdx++];
202 EVT VT = VA.getLocVT();
205 // The first 36 bytes of the input buffer contains information about
206 // thread group and global sizes.
207 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
208 36 + VA.getLocMemOffset());
209 InVals.push_back(Arg);
212 assert(VA.isRegLoc() && "Parameter must be in a register!");
214 unsigned Reg = VA.getLocReg();
216 if (VT == MVT::i64) {
217 // For now assume it is a pointer
218 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
219 &AMDGPU::SReg_64RegClass);
220 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
221 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
225 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
227 Reg = MF.addLiveIn(Reg, RC);
228 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
230 if (Arg.VT.isVector()) {
232 // Build a vector from the registers
233 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
234 unsigned NumElements = ParamType->getVectorNumElements();
236 SmallVector<SDValue, 4> Regs;
238 for (unsigned j = 1; j != NumElements; ++j) {
239 Reg = ArgLocs[ArgIdx++].getLocReg();
240 Reg = MF.addLiveIn(Reg, RC);
241 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
244 // Fill up the missing vector elements
245 NumElements = Arg.VT.getVectorNumElements() - NumElements;
246 for (unsigned j = 0; j != NumElements; ++j)
247 Regs.push_back(DAG.getUNDEF(VT));
249 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
250 Regs.data(), Regs.size()));
254 InVals.push_back(Val);
259 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
260 MachineInstr * MI, MachineBasicBlock * BB) const {
262 MachineBasicBlock::iterator I = *MI;
264 switch (MI->getOpcode()) {
266 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
267 case AMDGPU::BRANCH: return BB;
268 case AMDGPU::SI_ADDR64_RSRC: {
269 const SIInstrInfo *TII =
270 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
271 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
272 unsigned SuperReg = MI->getOperand(0).getReg();
273 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
274 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
275 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
276 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
277 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
278 .addOperand(MI->getOperand(1));
279 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
281 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
282 .addImm(RSRC_DATA_FORMAT >> 32);
283 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
285 .addImm(AMDGPU::sub0)
287 .addImm(AMDGPU::sub1);
288 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
290 .addImm(AMDGPU::sub0_sub1)
292 .addImm(AMDGPU::sub2_sub3);
293 MI->eraseFromParent();
300 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
304 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
308 //===----------------------------------------------------------------------===//
309 // Custom DAG Lowering Operations
310 //===----------------------------------------------------------------------===//
312 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
313 switch (Op.getOpcode()) {
314 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
315 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
316 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
317 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
318 case ISD::INTRINSIC_WO_CHAIN: {
319 unsigned IntrinsicID =
320 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
321 EVT VT = Op.getValueType();
323 //XXX: Hardcoded we only use two to store the pointer to the parameters.
324 unsigned NumUserSGPRs = 2;
325 switch (IntrinsicID) {
326 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
327 case Intrinsic::r600_read_ngroups_x:
328 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
329 case Intrinsic::r600_read_ngroups_y:
330 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
331 case Intrinsic::r600_read_ngroups_z:
332 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
333 case Intrinsic::r600_read_global_size_x:
334 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
335 case Intrinsic::r600_read_global_size_y:
336 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
337 case Intrinsic::r600_read_global_size_z:
338 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
339 case Intrinsic::r600_read_local_size_x:
340 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
341 case Intrinsic::r600_read_local_size_y:
342 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
343 case Intrinsic::r600_read_local_size_z:
344 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
345 case Intrinsic::r600_read_tgid_x:
346 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
347 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
348 case Intrinsic::r600_read_tgid_y:
349 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
350 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
351 case Intrinsic::r600_read_tgid_z:
352 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
353 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
354 case Intrinsic::r600_read_tidig_x:
355 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
357 case Intrinsic::r600_read_tidig_y:
358 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
360 case Intrinsic::r600_read_tidig_z:
361 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
370 /// \brief Helper function for LowerBRCOND
371 static SDNode *findUser(SDValue Value, unsigned Opcode) {
373 SDNode *Parent = Value.getNode();
374 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
377 if (I.getUse().get() != Value)
380 if (I->getOpcode() == Opcode)
386 /// This transforms the control flow intrinsics to get the branch destination as
387 /// last parameter, also switches branch target with BR if the need arise
388 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
389 SelectionDAG &DAG) const {
393 SDNode *Intr = BRCOND.getOperand(1).getNode();
394 SDValue Target = BRCOND.getOperand(2);
397 if (Intr->getOpcode() == ISD::SETCC) {
398 // As long as we negate the condition everything is fine
399 SDNode *SetCC = Intr;
400 assert(SetCC->getConstantOperandVal(1) == 1);
401 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
403 Intr = SetCC->getOperand(0).getNode();
406 // Get the target from BR if we don't negate the condition
407 BR = findUser(BRCOND, ISD::BR);
408 Target = BR->getOperand(1);
411 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
413 // Build the result and
414 SmallVector<EVT, 4> Res;
415 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
416 Res.push_back(Intr->getValueType(i));
418 // operands of the new intrinsic call
419 SmallVector<SDValue, 4> Ops;
420 Ops.push_back(BRCOND.getOperand(0));
421 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
422 Ops.push_back(Intr->getOperand(i));
423 Ops.push_back(Target);
425 // build the new intrinsic call
426 SDNode *Result = DAG.getNode(
427 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
428 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
431 // Give the branch instruction our target
436 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
439 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
441 // Copy the intrinsic results to registers
442 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
443 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
447 Chain = DAG.getCopyToReg(
449 CopyToReg->getOperand(1),
450 SDValue(Result, i - 1),
453 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
456 // Remove the old intrinsic from the chain
457 DAG.ReplaceAllUsesOfValueWith(
458 SDValue(Intr, Intr->getNumValues() - 1),
459 Intr->getOperand(0));
464 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
465 SDValue LHS = Op.getOperand(0);
466 SDValue RHS = Op.getOperand(1);
467 SDValue True = Op.getOperand(2);
468 SDValue False = Op.getOperand(3);
469 SDValue CC = Op.getOperand(4);
470 EVT VT = Op.getValueType();
473 // Possible Min/Max pattern
474 SDValue MinMax = LowerMinMax(Op, DAG);
475 if (MinMax.getNode()) {
479 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
480 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
483 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
484 SelectionDAG &DAG) const {
485 EVT VT = Op.getValueType();
488 if (VT != MVT::i64) {
492 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
493 DAG.getConstant(31, MVT::i32));
495 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
498 //===----------------------------------------------------------------------===//
499 // Custom DAG optimizations
500 //===----------------------------------------------------------------------===//
502 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
503 DAGCombinerInfo &DCI) const {
504 SelectionDAG &DAG = DCI.DAG;
506 EVT VT = N->getValueType(0);
508 switch (N->getOpcode()) {
510 case ISD::SELECT_CC: {
512 ConstantSDNode *True, *False;
513 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
514 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
515 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
516 && True->isAllOnesValue()
517 && False->isNullValue()
519 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
520 N->getOperand(1), N->getOperand(4));
526 SDValue Arg0 = N->getOperand(0);
527 SDValue Arg1 = N->getOperand(1);
528 SDValue CC = N->getOperand(2);
529 ConstantSDNode * C = NULL;
530 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
532 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
534 && Arg0.getOpcode() == ISD::SIGN_EXTEND
535 && Arg0.getOperand(0).getValueType() == MVT::i1
536 && (C = dyn_cast<ConstantSDNode>(Arg1))
538 && CCOp == ISD::SETNE) {
539 return SimplifySetCC(VT, Arg0.getOperand(0),
540 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
548 /// \brief Test if RegClass is one of the VSrc classes
549 static bool isVSrc(unsigned RegClass) {
550 return AMDGPU::VSrc_32RegClassID == RegClass ||
551 AMDGPU::VSrc_64RegClassID == RegClass;
554 /// \brief Test if RegClass is one of the SSrc classes
555 static bool isSSrc(unsigned RegClass) {
556 return AMDGPU::SSrc_32RegClassID == RegClass ||
557 AMDGPU::SSrc_64RegClassID == RegClass;
560 /// \brief Analyze the possible immediate value Op
562 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
563 /// and the immediate value if it's a literal immediate
564 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
571 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
572 if (Node->getZExtValue() >> 32) {
575 Imm.I = Node->getSExtValue();
576 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
577 Imm.F = Node->getValueAPF().convertToFloat();
579 return -1; // It isn't an immediate
581 if ((Imm.I >= -16 && Imm.I <= 64) ||
582 Imm.F == 0.5f || Imm.F == -0.5f ||
583 Imm.F == 1.0f || Imm.F == -1.0f ||
584 Imm.F == 2.0f || Imm.F == -2.0f ||
585 Imm.F == 4.0f || Imm.F == -4.0f)
586 return 0; // It's an inline immediate
588 return Imm.I; // It's a literal immediate
591 /// \brief Try to fold an immediate directly into an instruction
592 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
593 bool &ScalarSlotUsed) const {
595 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
596 const SIInstrInfo *TII =
597 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
598 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
601 const SDValue &Op = Mov->getOperand(0);
602 int32_t Value = analyzeImmediate(Op.getNode());
604 // Not an immediate at all
607 } else if (Value == 0) {
608 // Inline immediates can always be fold
612 } else if (Value == Immediate) {
613 // Already fold literal immediate
617 } else if (!ScalarSlotUsed && !Immediate) {
618 // Fold this literal immediate
619 ScalarSlotUsed = true;
629 /// \brief Does "Op" fit into register class "RegClass" ?
630 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
631 unsigned RegClass) const {
633 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
634 SDNode *Node = Op.getNode();
636 const TargetRegisterClass *OpClass;
637 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
638 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
639 const SIInstrInfo *TII =
640 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
641 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
642 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
643 if (OpClassID == -1) {
644 switch (MN->getMachineOpcode()) {
645 case AMDGPU::REG_SEQUENCE:
646 // Operand 0 is the register class id for REG_SEQUENCE instructions.
647 OpClass = TRI->getRegClass(
648 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
651 OpClass = getRegClassFor(Op.getSimpleValueType());
655 OpClass = TRI->getRegClass(OpClassID);
658 } else if (Node->getOpcode() == ISD::CopyFromReg) {
659 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
660 OpClass = MRI.getRegClass(Reg->getReg());
665 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
668 /// \brief Make sure that we don't exeed the number of allowed scalars
669 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
671 bool &ScalarSlotUsed) const {
673 // First map the operands register class to a destination class
674 if (RegClass == AMDGPU::VSrc_32RegClassID)
675 RegClass = AMDGPU::VReg_32RegClassID;
676 else if (RegClass == AMDGPU::VSrc_64RegClassID)
677 RegClass = AMDGPU::VReg_64RegClassID;
681 // Nothing todo if they fit naturaly
682 if (fitsRegClass(DAG, Operand, RegClass))
685 // If the scalar slot isn't used yet use it now
686 if (!ScalarSlotUsed) {
687 ScalarSlotUsed = true;
691 // This is a conservative aproach, it is possible that we can't determine
692 // the correct register class and copy too often, but better save than sorry.
693 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
694 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
695 Operand.getValueType(), Operand, RC);
696 Operand = SDValue(Node, 0);
699 /// \returns true if \p Node's operands are different from the SDValue list
701 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
702 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
703 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
710 /// \brief Try to fold the Nodes operands into the Node
711 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
712 SelectionDAG &DAG) const {
714 // Original encoding (either e32 or e64)
715 int Opcode = Node->getMachineOpcode();
716 const SIInstrInfo *TII =
717 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
718 const MCInstrDesc *Desc = &TII->get(Opcode);
720 unsigned NumDefs = Desc->getNumDefs();
721 unsigned NumOps = Desc->getNumOperands();
723 // Commuted opcode if available
724 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
725 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
727 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
728 assert(!DescRev || DescRev->getNumOperands() == NumOps);
730 // e64 version if available, -1 otherwise
731 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
732 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
734 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
735 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
737 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
738 bool HaveVSrc = false, HaveSSrc = false;
740 // First figure out what we alread have in this instruction
741 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
742 i != e && Op < NumOps; ++i, ++Op) {
744 unsigned RegClass = Desc->OpInfo[Op].RegClass;
745 if (isVSrc(RegClass))
747 else if (isSSrc(RegClass))
752 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
753 if (Imm != -1 && Imm != 0) {
759 // If we neither have VSrc nor SSrc it makes no sense to continue
760 if (!HaveVSrc && !HaveSSrc)
763 // No scalar allowed when we have both VSrc and SSrc
764 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
766 // Second go over the operands and try to fold them
767 std::vector<SDValue> Ops;
768 bool Promote2e64 = false;
769 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
770 i != e && Op < NumOps; ++i, ++Op) {
772 const SDValue &Operand = Node->getOperand(i);
773 Ops.push_back(Operand);
775 // Already folded immediate ?
776 if (isa<ConstantSDNode>(Operand.getNode()) ||
777 isa<ConstantFPSDNode>(Operand.getNode()))
780 // Is this a VSrc or SSrc operand ?
781 unsigned RegClass = Desc->OpInfo[Op].RegClass;
782 if (isVSrc(RegClass) || isSSrc(RegClass)) {
783 // Try to fold the immediates
784 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
785 // Folding didn't worked, make sure we don't hit the SReg limit
786 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
791 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
793 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
794 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
796 // Test if it makes sense to swap operands
797 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
798 (!fitsRegClass(DAG, Ops[1], RegClass) &&
799 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
801 // Swap commutable operands
802 SDValue Tmp = Ops[1];
812 if (DescE64 && !Immediate) {
814 // Test if it makes sense to switch to e64 encoding
815 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
816 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
820 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
821 (!fitsRegClass(DAG, Ops[i], RegClass) &&
822 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
824 // Switch to e64 encoding
834 // Add the modifier flags while promoting
835 for (unsigned i = 0; i < 4; ++i)
836 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
839 // Add optional chain and glue
840 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
841 Ops.push_back(Node->getOperand(i));
843 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
844 // this case a brand new node is always be created, even if the operands
845 // are the same as before. So, manually check if anything has been changed.
846 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
850 // Create a complete new instruction
851 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
854 /// \brief Helper function for adjustWritemask
855 static unsigned SubIdx2Lane(unsigned Idx) {
858 case AMDGPU::sub0: return 0;
859 case AMDGPU::sub1: return 1;
860 case AMDGPU::sub2: return 2;
861 case AMDGPU::sub3: return 3;
865 /// \brief Adjust the writemask of MIMG instructions
866 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
867 SelectionDAG &DAG) const {
868 SDNode *Users[4] = { };
869 unsigned Writemask = 0, Lane = 0;
871 // Try to figure out the used register components
872 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
875 // Abort if we can't understand the usage
876 if (!I->isMachineOpcode() ||
877 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
880 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
882 // Abort if we have more than one user per component
887 Writemask |= 1 << Lane;
890 // Abort if all components are used
891 if (Writemask == 0xf)
894 // Adjust the writemask in the node
895 std::vector<SDValue> Ops;
896 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
897 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
898 Ops.push_back(Node->getOperand(i));
899 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
901 // If we only got one lane, replace it with a copy
902 if (Writemask == (1U << Lane)) {
903 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
904 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
905 SDLoc(), Users[Lane]->getValueType(0),
906 SDValue(Node, 0), RC);
907 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
911 // Update the users of the node with the new indices
912 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
914 SDNode *User = Users[i];
918 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
919 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
923 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
924 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
925 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
930 /// \brief Fold the instructions after slecting them
931 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
932 SelectionDAG &DAG) const {
933 Node = AdjustRegClass(Node, DAG);
935 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
936 adjustWritemask(Node, DAG);
938 return foldOperands(Node, DAG);
941 /// \brief Assign the register class depending on the number of
942 /// bits set in the writemask
943 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
944 SDNode *Node) const {
945 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
948 unsigned VReg = MI->getOperand(0).getReg();
949 unsigned Writemask = MI->getOperand(1).getImm();
950 unsigned BitsSet = 0;
951 for (unsigned i = 0; i < 4; ++i)
952 BitsSet += Writemask & (1 << i) ? 1 : 0;
954 const TargetRegisterClass *RC;
957 case 1: RC = &AMDGPU::VReg_32RegClass; break;
958 case 2: RC = &AMDGPU::VReg_64RegClass; break;
959 case 3: RC = &AMDGPU::VReg_96RegClass; break;
962 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
963 MRI.setRegClass(VReg, RC);
966 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
967 SelectionDAG &DAG) const {
970 unsigned NewOpcode = N->getMachineOpcode();
972 switch (N->getMachineOpcode()) {
974 case AMDGPU::REG_SEQUENCE: {
975 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
977 if (N->getValueType(0) == MVT::i128) {
980 const SDValue Ops[] = {
981 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
982 N->getOperand(1) , N->getOperand(2),
983 N->getOperand(3), N->getOperand(4)
985 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
988 case AMDGPU::S_LOAD_DWORD_IMM:
989 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
991 case AMDGPU::S_LOAD_DWORDX2_SGPR:
992 if (NewOpcode == N->getMachineOpcode()) {
993 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
996 case AMDGPU::S_LOAD_DWORDX4_IMM:
997 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
998 if (NewOpcode == N->getMachineOpcode()) {
999 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1001 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1004 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1006 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1007 DAG.getConstant(0, MVT::i64)), 0),
1009 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1011 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1016 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1017 const TargetRegisterClass *RC,
1018 unsigned Reg, EVT VT) const {
1019 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1021 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1022 cast<RegisterSDNode>(VReg)->getReg(), VT);