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"
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"
28 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
32 SITargetLowering::SITargetLowering(TargetMachine &TM) :
33 AMDGPUTargetLowering(TM),
34 TII(static_cast<const SIInstrInfo*>(TM.getInstrInfo())),
35 TRI(TM.getRegisterInfo()) {
37 addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
38 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
40 addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
41 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
42 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
44 addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
45 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
47 addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
49 addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
50 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
52 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
53 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
54 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
56 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
57 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
59 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
60 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
62 computeRegisterProperties();
64 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
65 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
66 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
67 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
69 setOperationAction(ISD::ADD, MVT::i64, Legal);
70 setOperationAction(ISD::ADD, MVT::i32, Legal);
72 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
73 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
75 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
77 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
79 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
81 setTargetDAGCombine(ISD::SELECT_CC);
83 setTargetDAGCombine(ISD::SETCC);
85 setSchedulingPreference(Sched::RegPressure);
88 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
89 SDLoc DL, SDValue Chain,
90 unsigned Offset) const {
91 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
92 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
93 AMDGPUAS::CONSTANT_ADDRESS);
94 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
95 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
96 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
97 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
98 DAG.getConstant(Offset, MVT::i64));
99 return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
100 MachinePointerInfo(UndefValue::get(PtrTy)),
101 VT, false, false, ArgVT.getSizeInBits() >> 3);
105 SDValue SITargetLowering::LowerFormalArguments(
107 CallingConv::ID CallConv,
109 const SmallVectorImpl<ISD::InputArg> &Ins,
110 SDLoc DL, SelectionDAG &DAG,
111 SmallVectorImpl<SDValue> &InVals) const {
113 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
115 MachineFunction &MF = DAG.getMachineFunction();
116 FunctionType *FType = MF.getFunction()->getFunctionType();
117 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
119 assert(CallConv == CallingConv::C);
121 SmallVector<ISD::InputArg, 16> Splits;
122 uint32_t Skipped = 0;
124 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
125 const ISD::InputArg &Arg = Ins[i];
127 // First check if it's a PS input addr
128 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
130 assert((PSInputNum <= 15) && "Too many PS inputs!");
133 // We can savely skip PS inputs
139 Info->PSInputAddr |= 1 << PSInputNum++;
142 // Second split vertices into their elements
143 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
144 ISD::InputArg NewArg = Arg;
145 NewArg.Flags.setSplit();
146 NewArg.VT = Arg.VT.getVectorElementType();
148 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
149 // three or five element vertex only needs three or five registers,
150 // NOT four or eigth.
151 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
152 unsigned NumElements = ParamType->getVectorNumElements();
154 for (unsigned j = 0; j != NumElements; ++j) {
155 Splits.push_back(NewArg);
156 NewArg.PartOffset += NewArg.VT.getStoreSize();
160 Splits.push_back(Arg);
164 SmallVector<CCValAssign, 16> ArgLocs;
165 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
166 getTargetMachine(), ArgLocs, *DAG.getContext());
168 // At least one interpolation mode must be enabled or else the GPU will hang.
169 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
170 Info->PSInputAddr |= 1;
171 CCInfo.AllocateReg(AMDGPU::VGPR0);
172 CCInfo.AllocateReg(AMDGPU::VGPR1);
175 // The pointer to the list of arguments is stored in SGPR0, SGPR1
176 if (Info->ShaderType == ShaderType::COMPUTE) {
177 CCInfo.AllocateReg(AMDGPU::SGPR0);
178 CCInfo.AllocateReg(AMDGPU::SGPR1);
179 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
182 AnalyzeFormalArguments(CCInfo, Splits);
184 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
186 const ISD::InputArg &Arg = Ins[i];
187 if (Skipped & (1 << i)) {
188 InVals.push_back(DAG.getUNDEF(Arg.VT));
192 CCValAssign &VA = ArgLocs[ArgIdx++];
193 EVT VT = VA.getLocVT();
196 // The first 36 bytes of the input buffer contains information about
197 // thread group and global sizes.
198 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
199 36 + VA.getLocMemOffset());
200 InVals.push_back(Arg);
203 assert(VA.isRegLoc() && "Parameter must be in a register!");
205 unsigned Reg = VA.getLocReg();
207 if (VT == MVT::i64) {
208 // For now assume it is a pointer
209 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
210 &AMDGPU::SReg_64RegClass);
211 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
212 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
216 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
218 Reg = MF.addLiveIn(Reg, RC);
219 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
221 if (Arg.VT.isVector()) {
223 // Build a vector from the registers
224 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
225 unsigned NumElements = ParamType->getVectorNumElements();
227 SmallVector<SDValue, 4> Regs;
229 for (unsigned j = 1; j != NumElements; ++j) {
230 Reg = ArgLocs[ArgIdx++].getLocReg();
231 Reg = MF.addLiveIn(Reg, RC);
232 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
235 // Fill up the missing vector elements
236 NumElements = Arg.VT.getVectorNumElements() - NumElements;
237 for (unsigned j = 0; j != NumElements; ++j)
238 Regs.push_back(DAG.getUNDEF(VT));
240 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
241 Regs.data(), Regs.size()));
245 InVals.push_back(Val);
250 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
251 MachineInstr * MI, MachineBasicBlock * BB) const {
253 MachineBasicBlock::iterator I = *MI;
255 switch (MI->getOpcode()) {
257 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
258 case AMDGPU::BRANCH: return BB;
259 case AMDGPU::SI_ADDR64_RSRC: {
260 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
261 unsigned SuperReg = MI->getOperand(0).getReg();
262 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
263 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
264 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
265 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
266 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
267 .addOperand(MI->getOperand(1));
268 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
270 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
271 .addImm(RSRC_DATA_FORMAT >> 32);
272 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
274 .addImm(AMDGPU::sub0)
276 .addImm(AMDGPU::sub1);
277 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
279 .addImm(AMDGPU::sub0_sub1)
281 .addImm(AMDGPU::sub2_sub3);
282 MI->eraseFromParent();
289 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
293 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
297 //===----------------------------------------------------------------------===//
298 // Custom DAG Lowering Operations
299 //===----------------------------------------------------------------------===//
301 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
302 switch (Op.getOpcode()) {
303 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
304 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
305 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
306 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
307 case ISD::INTRINSIC_WO_CHAIN: {
308 unsigned IntrinsicID =
309 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
310 EVT VT = Op.getValueType();
312 //XXX: Hardcoded we only use two to store the pointer to the parameters.
313 unsigned NumUserSGPRs = 2;
314 switch (IntrinsicID) {
315 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
316 case Intrinsic::r600_read_ngroups_x:
317 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
318 case Intrinsic::r600_read_ngroups_y:
319 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
320 case Intrinsic::r600_read_ngroups_z:
321 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
322 case Intrinsic::r600_read_global_size_x:
323 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
324 case Intrinsic::r600_read_global_size_y:
325 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
326 case Intrinsic::r600_read_global_size_z:
327 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
328 case Intrinsic::r600_read_local_size_x:
329 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
330 case Intrinsic::r600_read_local_size_y:
331 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
332 case Intrinsic::r600_read_local_size_z:
333 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
334 case Intrinsic::r600_read_tgid_x:
335 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
336 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
337 case Intrinsic::r600_read_tgid_y:
338 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
339 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
340 case Intrinsic::r600_read_tgid_z:
341 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
342 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
343 case Intrinsic::r600_read_tidig_x:
344 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
346 case Intrinsic::r600_read_tidig_y:
347 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
349 case Intrinsic::r600_read_tidig_z:
350 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
359 /// \brief Helper function for LowerBRCOND
360 static SDNode *findUser(SDValue Value, unsigned Opcode) {
362 SDNode *Parent = Value.getNode();
363 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
366 if (I.getUse().get() != Value)
369 if (I->getOpcode() == Opcode)
375 /// This transforms the control flow intrinsics to get the branch destination as
376 /// last parameter, also switches branch target with BR if the need arise
377 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
378 SelectionDAG &DAG) const {
382 SDNode *Intr = BRCOND.getOperand(1).getNode();
383 SDValue Target = BRCOND.getOperand(2);
386 if (Intr->getOpcode() == ISD::SETCC) {
387 // As long as we negate the condition everything is fine
388 SDNode *SetCC = Intr;
389 assert(SetCC->getConstantOperandVal(1) == 1);
390 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
392 Intr = SetCC->getOperand(0).getNode();
395 // Get the target from BR if we don't negate the condition
396 BR = findUser(BRCOND, ISD::BR);
397 Target = BR->getOperand(1);
400 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
402 // Build the result and
403 SmallVector<EVT, 4> Res;
404 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
405 Res.push_back(Intr->getValueType(i));
407 // operands of the new intrinsic call
408 SmallVector<SDValue, 4> Ops;
409 Ops.push_back(BRCOND.getOperand(0));
410 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
411 Ops.push_back(Intr->getOperand(i));
412 Ops.push_back(Target);
414 // build the new intrinsic call
415 SDNode *Result = DAG.getNode(
416 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
417 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
420 // Give the branch instruction our target
425 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
428 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
430 // Copy the intrinsic results to registers
431 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
432 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
436 Chain = DAG.getCopyToReg(
438 CopyToReg->getOperand(1),
439 SDValue(Result, i - 1),
442 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
445 // Remove the old intrinsic from the chain
446 DAG.ReplaceAllUsesOfValueWith(
447 SDValue(Intr, Intr->getNumValues() - 1),
448 Intr->getOperand(0));
453 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
454 SDValue LHS = Op.getOperand(0);
455 SDValue RHS = Op.getOperand(1);
456 SDValue True = Op.getOperand(2);
457 SDValue False = Op.getOperand(3);
458 SDValue CC = Op.getOperand(4);
459 EVT VT = Op.getValueType();
462 // Possible Min/Max pattern
463 SDValue MinMax = LowerMinMax(Op, DAG);
464 if (MinMax.getNode()) {
468 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
469 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
472 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
473 SelectionDAG &DAG) const {
474 EVT VT = Op.getValueType();
477 if (VT != MVT::i64) {
481 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
482 DAG.getConstant(31, MVT::i32));
484 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
487 //===----------------------------------------------------------------------===//
488 // Custom DAG optimizations
489 //===----------------------------------------------------------------------===//
491 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
492 DAGCombinerInfo &DCI) const {
493 SelectionDAG &DAG = DCI.DAG;
495 EVT VT = N->getValueType(0);
497 switch (N->getOpcode()) {
499 case ISD::SELECT_CC: {
501 ConstantSDNode *True, *False;
502 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
503 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
504 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
505 && True->isAllOnesValue()
506 && False->isNullValue()
508 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
509 N->getOperand(1), N->getOperand(4));
515 SDValue Arg0 = N->getOperand(0);
516 SDValue Arg1 = N->getOperand(1);
517 SDValue CC = N->getOperand(2);
518 ConstantSDNode * C = NULL;
519 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
521 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
523 && Arg0.getOpcode() == ISD::SIGN_EXTEND
524 && Arg0.getOperand(0).getValueType() == MVT::i1
525 && (C = dyn_cast<ConstantSDNode>(Arg1))
527 && CCOp == ISD::SETNE) {
528 return SimplifySetCC(VT, Arg0.getOperand(0),
529 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
537 /// \brief Test if RegClass is one of the VSrc classes
538 static bool isVSrc(unsigned RegClass) {
539 return AMDGPU::VSrc_32RegClassID == RegClass ||
540 AMDGPU::VSrc_64RegClassID == RegClass;
543 /// \brief Test if RegClass is one of the SSrc classes
544 static bool isSSrc(unsigned RegClass) {
545 return AMDGPU::SSrc_32RegClassID == RegClass ||
546 AMDGPU::SSrc_64RegClassID == RegClass;
549 /// \brief Analyze the possible immediate value Op
551 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
552 /// and the immediate value if it's a literal immediate
553 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
560 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
561 if (Node->getZExtValue() >> 32) {
564 Imm.I = Node->getSExtValue();
565 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
566 Imm.F = Node->getValueAPF().convertToFloat();
568 return -1; // It isn't an immediate
570 if ((Imm.I >= -16 && Imm.I <= 64) ||
571 Imm.F == 0.5f || Imm.F == -0.5f ||
572 Imm.F == 1.0f || Imm.F == -1.0f ||
573 Imm.F == 2.0f || Imm.F == -2.0f ||
574 Imm.F == 4.0f || Imm.F == -4.0f)
575 return 0; // It's an inline immediate
577 return Imm.I; // It's a literal immediate
580 /// \brief Try to fold an immediate directly into an instruction
581 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
582 bool &ScalarSlotUsed) const {
584 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
585 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
588 const SDValue &Op = Mov->getOperand(0);
589 int32_t Value = analyzeImmediate(Op.getNode());
591 // Not an immediate at all
594 } else if (Value == 0) {
595 // Inline immediates can always be fold
599 } else if (Value == Immediate) {
600 // Already fold literal immediate
604 } else if (!ScalarSlotUsed && !Immediate) {
605 // Fold this literal immediate
606 ScalarSlotUsed = true;
616 /// \brief Does "Op" fit into register class "RegClass" ?
617 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
618 unsigned RegClass) const {
620 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
621 SDNode *Node = Op.getNode();
623 const TargetRegisterClass *OpClass;
624 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
625 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
626 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
627 if (OpClassID == -1) {
628 switch (MN->getMachineOpcode()) {
629 case AMDGPU::REG_SEQUENCE:
630 // Operand 0 is the register class id for REG_SEQUENCE instructions.
631 OpClass = TRI->getRegClass(
632 cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
635 OpClass = getRegClassFor(Op.getSimpleValueType());
639 OpClass = TRI->getRegClass(OpClassID);
642 } else if (Node->getOpcode() == ISD::CopyFromReg) {
643 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
644 OpClass = MRI.getRegClass(Reg->getReg());
649 return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
652 /// \brief Make sure that we don't exeed the number of allowed scalars
653 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
655 bool &ScalarSlotUsed) const {
657 // First map the operands register class to a destination class
658 if (RegClass == AMDGPU::VSrc_32RegClassID)
659 RegClass = AMDGPU::VReg_32RegClassID;
660 else if (RegClass == AMDGPU::VSrc_64RegClassID)
661 RegClass = AMDGPU::VReg_64RegClassID;
665 // Nothing todo if they fit naturaly
666 if (fitsRegClass(DAG, Operand, RegClass))
669 // If the scalar slot isn't used yet use it now
670 if (!ScalarSlotUsed) {
671 ScalarSlotUsed = true;
675 // This is a conservative aproach, it is possible that we can't determine
676 // the correct register class and copy too often, but better save than sorry.
677 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
678 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
679 Operand.getValueType(), Operand, RC);
680 Operand = SDValue(Node, 0);
683 /// \returns true if \p Node's operands are different from the SDValue list
685 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
686 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
687 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
694 /// \brief Try to fold the Nodes operands into the Node
695 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
696 SelectionDAG &DAG) const {
698 // Original encoding (either e32 or e64)
699 int Opcode = Node->getMachineOpcode();
700 const MCInstrDesc *Desc = &TII->get(Opcode);
702 unsigned NumDefs = Desc->getNumDefs();
703 unsigned NumOps = Desc->getNumOperands();
705 // Commuted opcode if available
706 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
707 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
709 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
710 assert(!DescRev || DescRev->getNumOperands() == NumOps);
712 // e64 version if available, -1 otherwise
713 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
714 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
716 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
717 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
719 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
720 bool HaveVSrc = false, HaveSSrc = false;
722 // First figure out what we alread have in this instruction
723 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
724 i != e && Op < NumOps; ++i, ++Op) {
726 unsigned RegClass = Desc->OpInfo[Op].RegClass;
727 if (isVSrc(RegClass))
729 else if (isSSrc(RegClass))
734 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
735 if (Imm != -1 && Imm != 0) {
741 // If we neither have VSrc nor SSrc it makes no sense to continue
742 if (!HaveVSrc && !HaveSSrc)
745 // No scalar allowed when we have both VSrc and SSrc
746 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
748 // Second go over the operands and try to fold them
749 std::vector<SDValue> Ops;
750 bool Promote2e64 = false;
751 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
752 i != e && Op < NumOps; ++i, ++Op) {
754 const SDValue &Operand = Node->getOperand(i);
755 Ops.push_back(Operand);
757 // Already folded immediate ?
758 if (isa<ConstantSDNode>(Operand.getNode()) ||
759 isa<ConstantFPSDNode>(Operand.getNode()))
762 // Is this a VSrc or SSrc operand ?
763 unsigned RegClass = Desc->OpInfo[Op].RegClass;
764 if (isVSrc(RegClass) || isSSrc(RegClass)) {
765 // Try to fold the immediates
766 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
767 // Folding didn't worked, make sure we don't hit the SReg limit
768 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
773 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
775 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
776 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
778 // Test if it makes sense to swap operands
779 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
780 (!fitsRegClass(DAG, Ops[1], RegClass) &&
781 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
783 // Swap commutable operands
784 SDValue Tmp = Ops[1];
794 if (DescE64 && !Immediate) {
796 // Test if it makes sense to switch to e64 encoding
797 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
798 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
802 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
803 (!fitsRegClass(DAG, Ops[i], RegClass) &&
804 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
806 // Switch to e64 encoding
816 // Add the modifier flags while promoting
817 for (unsigned i = 0; i < 4; ++i)
818 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
821 // Add optional chain and glue
822 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
823 Ops.push_back(Node->getOperand(i));
825 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
826 // this case a brand new node is always be created, even if the operands
827 // are the same as before. So, manually check if anything has been changed.
828 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
832 // Create a complete new instruction
833 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
836 /// \brief Helper function for adjustWritemask
837 static unsigned SubIdx2Lane(unsigned Idx) {
840 case AMDGPU::sub0: return 0;
841 case AMDGPU::sub1: return 1;
842 case AMDGPU::sub2: return 2;
843 case AMDGPU::sub3: return 3;
847 /// \brief Adjust the writemask of MIMG instructions
848 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
849 SelectionDAG &DAG) const {
850 SDNode *Users[4] = { };
851 unsigned Writemask = 0, Lane = 0;
853 // Try to figure out the used register components
854 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
857 // Abort if we can't understand the usage
858 if (!I->isMachineOpcode() ||
859 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
862 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
864 // Abort if we have more than one user per component
869 Writemask |= 1 << Lane;
872 // Abort if all components are used
873 if (Writemask == 0xf)
876 // Adjust the writemask in the node
877 std::vector<SDValue> Ops;
878 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
879 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
880 Ops.push_back(Node->getOperand(i));
881 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
883 // If we only got one lane, replace it with a copy
884 if (Writemask == (1U << Lane)) {
885 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
886 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
887 SDLoc(), Users[Lane]->getValueType(0),
888 SDValue(Node, 0), RC);
889 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
893 // Update the users of the node with the new indices
894 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
896 SDNode *User = Users[i];
900 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
901 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
905 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
906 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
907 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
912 /// \brief Fold the instructions after slecting them
913 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
914 SelectionDAG &DAG) const {
915 Node = AdjustRegClass(Node, DAG);
917 if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
918 adjustWritemask(Node, DAG);
920 return foldOperands(Node, DAG);
923 /// \brief Assign the register class depending on the number of
924 /// bits set in the writemask
925 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
926 SDNode *Node) const {
927 if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
930 unsigned VReg = MI->getOperand(0).getReg();
931 unsigned Writemask = MI->getOperand(1).getImm();
932 unsigned BitsSet = 0;
933 for (unsigned i = 0; i < 4; ++i)
934 BitsSet += Writemask & (1 << i) ? 1 : 0;
936 const TargetRegisterClass *RC;
939 case 1: RC = &AMDGPU::VReg_32RegClass; break;
940 case 2: RC = &AMDGPU::VReg_64RegClass; break;
941 case 3: RC = &AMDGPU::VReg_96RegClass; break;
944 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
945 MRI.setRegClass(VReg, RC);
948 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
949 SelectionDAG &DAG) const {
952 unsigned NewOpcode = N->getMachineOpcode();
954 switch (N->getMachineOpcode()) {
956 case AMDGPU::REG_SEQUENCE: {
957 // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
959 if (N->getValueType(0) == MVT::i128) {
962 const SDValue Ops[] = {
963 DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
964 N->getOperand(1) , N->getOperand(2),
965 N->getOperand(3), N->getOperand(4)
967 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
970 case AMDGPU::S_LOAD_DWORD_IMM:
971 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
973 case AMDGPU::S_LOAD_DWORDX2_SGPR:
974 if (NewOpcode == N->getMachineOpcode()) {
975 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
978 case AMDGPU::S_LOAD_DWORDX4_IMM:
979 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
980 if (NewOpcode == N->getMachineOpcode()) {
981 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
983 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
986 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
988 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
989 DAG.getConstant(0, MVT::i64)), 0),
991 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
993 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
998 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
999 const TargetRegisterClass *RC,
1000 unsigned Reg, EVT VT) const {
1001 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1003 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1004 cast<RegisterSDNode>(VReg)->getReg(), VT);