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/IR/Function.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"
29 SITargetLowering::SITargetLowering(TargetMachine &TM) :
30 AMDGPUTargetLowering(TM),
31 TII(static_cast<const SIInstrInfo*>(TM.getInstrInfo())),
32 TRI(TM.getRegisterInfo()) {
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);
52 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
53 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
55 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
56 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
58 computeRegisterProperties();
60 setOperationAction(ISD::ADD, MVT::i64, Legal);
61 setOperationAction(ISD::ADD, MVT::i32, Legal);
63 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
65 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
66 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
68 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
69 setTargetDAGCombine(ISD::SELECT_CC);
71 setTargetDAGCombine(ISD::SETCC);
74 SDValue SITargetLowering::LowerFormalArguments(
76 CallingConv::ID CallConv,
78 const SmallVectorImpl<ISD::InputArg> &Ins,
79 DebugLoc DL, SelectionDAG &DAG,
80 SmallVectorImpl<SDValue> &InVals) const {
82 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
84 MachineFunction &MF = DAG.getMachineFunction();
85 FunctionType *FType = MF.getFunction()->getFunctionType();
87 assert(CallConv == CallingConv::C);
89 SmallVector<ISD::InputArg, 16> Splits;
90 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
91 const ISD::InputArg &Arg = Ins[i];
93 // Split vertices into their elements
94 if (Arg.VT.isVector()) {
95 ISD::InputArg NewArg = Arg;
96 NewArg.Flags.setSplit();
97 NewArg.VT = Arg.VT.getVectorElementType();
99 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
100 // three or five element vertex only needs three or five registers,
101 // NOT four or eigth.
102 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
103 unsigned NumElements = ParamType->getVectorNumElements();
105 for (unsigned j = 0; j != NumElements; ++j) {
106 Splits.push_back(NewArg);
107 NewArg.PartOffset += NewArg.VT.getStoreSize();
111 Splits.push_back(Arg);
115 SmallVector<CCValAssign, 16> ArgLocs;
116 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
117 getTargetMachine(), ArgLocs, *DAG.getContext());
119 AnalyzeFormalArguments(CCInfo, Splits);
121 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
123 CCValAssign &VA = ArgLocs[ArgIdx++];
124 assert(VA.isRegLoc() && "Parameter must be in a register!");
126 unsigned Reg = VA.getLocReg();
127 MVT VT = VA.getLocVT();
129 if (VT == MVT::i64) {
130 // For now assume it is a pointer
131 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
132 &AMDGPU::SReg_64RegClass);
133 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
134 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
138 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
140 Reg = MF.addLiveIn(Reg, RC);
141 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
143 const ISD::InputArg &Arg = Ins[i];
144 if (Arg.VT.isVector()) {
146 // Build a vector from the registers
147 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
148 unsigned NumElements = ParamType->getVectorNumElements();
150 SmallVector<SDValue, 4> Regs;
152 for (unsigned j = 1; j != NumElements; ++j) {
153 Reg = ArgLocs[ArgIdx++].getLocReg();
154 Reg = MF.addLiveIn(Reg, RC);
155 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
158 // Fill up the missing vector elements
159 NumElements = Arg.VT.getVectorNumElements() - NumElements;
160 for (unsigned j = 0; j != NumElements; ++j)
161 Regs.push_back(DAG.getUNDEF(VT));
163 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
164 Regs.data(), Regs.size()));
168 InVals.push_back(Val);
173 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
174 MachineInstr * MI, MachineBasicBlock * BB) const {
175 MachineRegisterInfo & MRI = BB->getParent()->getRegInfo();
176 MachineBasicBlock::iterator I = MI;
178 switch (MI->getOpcode()) {
180 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
181 case AMDGPU::BRANCH: return BB;
182 case AMDGPU::SI_INTERP:
183 LowerSI_INTERP(MI, *BB, I, MRI);
186 LowerSI_WQM(MI, *BB, I, MRI);
192 void SITargetLowering::LowerSI_WQM(MachineInstr *MI, MachineBasicBlock &BB,
193 MachineBasicBlock::iterator I, MachineRegisterInfo & MRI) const {
194 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::S_WQM_B64), AMDGPU::EXEC)
195 .addReg(AMDGPU::EXEC);
197 MI->eraseFromParent();
200 void SITargetLowering::LowerSI_INTERP(MachineInstr *MI, MachineBasicBlock &BB,
201 MachineBasicBlock::iterator I, MachineRegisterInfo & MRI) const {
202 unsigned tmp = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
203 unsigned M0 = MRI.createVirtualRegister(&AMDGPU::M0RegRegClass);
204 MachineOperand dst = MI->getOperand(0);
205 MachineOperand iReg = MI->getOperand(1);
206 MachineOperand jReg = MI->getOperand(2);
207 MachineOperand attr_chan = MI->getOperand(3);
208 MachineOperand attr = MI->getOperand(4);
209 MachineOperand params = MI->getOperand(5);
211 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::S_MOV_B32), M0)
214 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::V_INTERP_P1_F32), tmp)
216 .addOperand(attr_chan)
220 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::V_INTERP_P2_F32))
224 .addOperand(attr_chan)
228 MI->eraseFromParent();
231 EVT SITargetLowering::getSetCCResultType(EVT VT) const {
235 //===----------------------------------------------------------------------===//
236 // Custom DAG Lowering Operations
237 //===----------------------------------------------------------------------===//
239 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
240 switch (Op.getOpcode()) {
241 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
242 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
243 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
244 case ISD::INTRINSIC_WO_CHAIN: {
245 unsigned IntrinsicID =
246 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
247 EVT VT = Op.getValueType();
248 switch (IntrinsicID) {
249 case AMDGPUIntrinsic::SI_vs_load_buffer_index:
250 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
252 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
260 /// \brief Helper function for LowerBRCOND
261 static SDNode *findUser(SDValue Value, unsigned Opcode) {
263 SDNode *Parent = Value.getNode();
264 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
267 if (I.getUse().get() != Value)
270 if (I->getOpcode() == Opcode)
276 /// This transforms the control flow intrinsics to get the branch destination as
277 /// last parameter, also switches branch target with BR if the need arise
278 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
279 SelectionDAG &DAG) const {
281 DebugLoc DL = BRCOND.getDebugLoc();
283 SDNode *Intr = BRCOND.getOperand(1).getNode();
284 SDValue Target = BRCOND.getOperand(2);
287 if (Intr->getOpcode() == ISD::SETCC) {
288 // As long as we negate the condition everything is fine
289 SDNode *SetCC = Intr;
290 assert(SetCC->getConstantOperandVal(1) == 1);
291 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
293 Intr = SetCC->getOperand(0).getNode();
296 // Get the target from BR if we don't negate the condition
297 BR = findUser(BRCOND, ISD::BR);
298 Target = BR->getOperand(1);
301 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
303 // Build the result and
304 SmallVector<EVT, 4> Res;
305 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
306 Res.push_back(Intr->getValueType(i));
308 // operands of the new intrinsic call
309 SmallVector<SDValue, 4> Ops;
310 Ops.push_back(BRCOND.getOperand(0));
311 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
312 Ops.push_back(Intr->getOperand(i));
313 Ops.push_back(Target);
315 // build the new intrinsic call
316 SDNode *Result = DAG.getNode(
317 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
318 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
321 // Give the branch instruction our target
326 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
329 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
331 // Copy the intrinsic results to registers
332 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
333 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
337 Chain = DAG.getCopyToReg(
339 CopyToReg->getOperand(1),
340 SDValue(Result, i - 1),
343 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
346 // Remove the old intrinsic from the chain
347 DAG.ReplaceAllUsesOfValueWith(
348 SDValue(Intr, Intr->getNumValues() - 1),
349 Intr->getOperand(0));
354 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
355 SDValue LHS = Op.getOperand(0);
356 SDValue RHS = Op.getOperand(1);
357 SDValue True = Op.getOperand(2);
358 SDValue False = Op.getOperand(3);
359 SDValue CC = Op.getOperand(4);
360 EVT VT = Op.getValueType();
361 DebugLoc DL = Op.getDebugLoc();
363 // Possible Min/Max pattern
364 SDValue MinMax = LowerMinMax(Op, DAG);
365 if (MinMax.getNode()) {
369 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
370 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
373 //===----------------------------------------------------------------------===//
374 // Custom DAG optimizations
375 //===----------------------------------------------------------------------===//
377 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
378 DAGCombinerInfo &DCI) const {
379 SelectionDAG &DAG = DCI.DAG;
380 DebugLoc DL = N->getDebugLoc();
381 EVT VT = N->getValueType(0);
383 switch (N->getOpcode()) {
385 case ISD::SELECT_CC: {
387 ConstantSDNode *True, *False;
388 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
389 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
390 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
391 && True->isAllOnesValue()
392 && False->isNullValue()
394 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
395 N->getOperand(1), N->getOperand(4));
401 SDValue Arg0 = N->getOperand(0);
402 SDValue Arg1 = N->getOperand(1);
403 SDValue CC = N->getOperand(2);
404 ConstantSDNode * C = NULL;
405 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
407 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
409 && Arg0.getOpcode() == ISD::SIGN_EXTEND
410 && Arg0.getOperand(0).getValueType() == MVT::i1
411 && (C = dyn_cast<ConstantSDNode>(Arg1))
413 && CCOp == ISD::SETNE) {
414 return SimplifySetCC(VT, Arg0.getOperand(0),
415 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
423 /// \brief Test if RegClass is one of the VSrc classes
424 static bool isVSrc(unsigned RegClass) {
425 return AMDGPU::VSrc_32RegClassID == RegClass ||
426 AMDGPU::VSrc_64RegClassID == RegClass;
429 /// \brief Test if RegClass is one of the SSrc classes
430 static bool isSSrc(unsigned RegClass) {
431 return AMDGPU::SSrc_32RegClassID == RegClass ||
432 AMDGPU::SSrc_64RegClassID == RegClass;
435 /// \brief Analyze the possible immediate value Op
437 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
438 /// and the immediate value if it's a literal immediate
439 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
446 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N))
447 Imm.I = Node->getSExtValue();
448 else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
449 Imm.F = Node->getValueAPF().convertToFloat();
451 return -1; // It isn't an immediate
453 if ((Imm.I >= -16 && Imm.I <= 64) ||
454 Imm.F == 0.5f || Imm.F == -0.5f ||
455 Imm.F == 1.0f || Imm.F == -1.0f ||
456 Imm.F == 2.0f || Imm.F == -2.0f ||
457 Imm.F == 4.0f || Imm.F == -4.0f)
458 return 0; // It's an inline immediate
460 return Imm.I; // It's a literal immediate
463 /// \brief Try to fold an immediate directly into an instruction
464 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
465 bool &ScalarSlotUsed) const {
467 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
468 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
471 const SDValue &Op = Mov->getOperand(0);
472 int32_t Value = analyzeImmediate(Op.getNode());
474 // Not an immediate at all
477 } else if (Value == 0) {
478 // Inline immediates can always be fold
482 } else if (Value == Immediate) {
483 // Already fold literal immediate
487 } else if (!ScalarSlotUsed && !Immediate) {
488 // Fold this literal immediate
489 ScalarSlotUsed = true;
499 /// \brief Does "Op" fit into register class "RegClass" ?
500 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, SDValue &Op,
501 unsigned RegClass) const {
503 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
504 SDNode *Node = Op.getNode();
507 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
508 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
509 OpClass = Desc.OpInfo[Op.getResNo()].RegClass;
511 } else if (Node->getOpcode() == ISD::CopyFromReg) {
512 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
513 OpClass = MRI.getRegClass(Reg->getReg())->getID();
521 return TRI->getRegClass(RegClass)->hasSubClassEq(TRI->getRegClass(OpClass));
524 /// \brief Make sure that we don't exeed the number of allowed scalars
525 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
527 bool &ScalarSlotUsed) const {
529 // First map the operands register class to a destination class
530 if (RegClass == AMDGPU::VSrc_32RegClassID)
531 RegClass = AMDGPU::VReg_32RegClassID;
532 else if (RegClass == AMDGPU::VSrc_64RegClassID)
533 RegClass = AMDGPU::VReg_64RegClassID;
537 // Nothing todo if they fit naturaly
538 if (fitsRegClass(DAG, Operand, RegClass))
541 // If the scalar slot isn't used yet use it now
542 if (!ScalarSlotUsed) {
543 ScalarSlotUsed = true;
547 // This is a conservative aproach, it is possible that we can't determine
548 // the correct register class and copy too often, but better save than sorry.
549 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
550 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DebugLoc(),
551 Operand.getValueType(), Operand, RC);
552 Operand = SDValue(Node, 0);
555 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
556 SelectionDAG &DAG) const {
558 // Original encoding (either e32 or e64)
559 int Opcode = Node->getMachineOpcode();
560 const MCInstrDesc *Desc = &TII->get(Opcode);
562 unsigned NumDefs = Desc->getNumDefs();
563 unsigned NumOps = Desc->getNumOperands();
565 // e64 version if available, -1 otherwise
566 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
567 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
569 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
570 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
572 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
573 bool HaveVSrc = false, HaveSSrc = false;
575 // First figure out what we alread have in this instruction
576 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
577 i != e && Op < NumOps; ++i, ++Op) {
579 unsigned RegClass = Desc->OpInfo[Op].RegClass;
580 if (isVSrc(RegClass))
582 else if (isSSrc(RegClass))
587 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
588 if (Imm != -1 && Imm != 0) {
594 // If we neither have VSrc nor SSrc it makes no sense to continue
595 if (!HaveVSrc && !HaveSSrc)
598 // No scalar allowed when we have both VSrc and SSrc
599 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
601 // Second go over the operands and try to fold them
602 std::vector<SDValue> Ops;
603 bool Promote2e64 = false;
604 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
605 i != e && Op < NumOps; ++i, ++Op) {
607 const SDValue &Operand = Node->getOperand(i);
608 Ops.push_back(Operand);
610 // Already folded immediate ?
611 if (isa<ConstantSDNode>(Operand.getNode()) ||
612 isa<ConstantFPSDNode>(Operand.getNode()))
615 // Is this a VSrc or SSrc operand ?
616 unsigned RegClass = Desc->OpInfo[Op].RegClass;
617 if (!isVSrc(RegClass) && !isSSrc(RegClass)) {
619 if (i == 1 && Desc->isCommutable() &&
620 fitsRegClass(DAG, Ops[0], RegClass) &&
621 foldImm(Ops[1], Immediate, ScalarSlotUsed)) {
623 assert(isVSrc(Desc->OpInfo[NumDefs].RegClass) ||
624 isSSrc(Desc->OpInfo[NumDefs].RegClass));
626 // Swap commutable operands
627 SDValue Tmp = Ops[1];
631 } else if (DescE64 && !Immediate) {
632 // Test if it makes sense to switch to e64 encoding
634 RegClass = DescE64->OpInfo[Op].RegClass;
636 if ((isVSrc(RegClass) || isSSrc(RegClass)) &&
637 foldImm(Ops[i], TmpImm, ScalarSlotUsed)) {
648 // Try to fold the immediates
649 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
650 // Folding didn't worked, make sure we don't hit the SReg limit
651 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
656 // Add the modifier flags while promoting
657 for (unsigned i = 0; i < 4; ++i)
658 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
661 // Add optional chain and glue
662 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
663 Ops.push_back(Node->getOperand(i));
665 // Either create a complete new or update the current instruction
667 return DAG.getMachineNode(OpcodeE64, Node->getDebugLoc(),
668 Node->getVTList(), Ops.data(), Ops.size());
670 return DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());