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::SELECT_CC, MVT::f32, Custom);
64 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
66 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
67 setTargetDAGCombine(ISD::SELECT_CC);
69 setTargetDAGCombine(ISD::SETCC);
72 SDValue SITargetLowering::LowerFormalArguments(
74 CallingConv::ID CallConv,
76 const SmallVectorImpl<ISD::InputArg> &Ins,
77 DebugLoc DL, SelectionDAG &DAG,
78 SmallVectorImpl<SDValue> &InVals) const {
80 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
82 MachineFunction &MF = DAG.getMachineFunction();
83 FunctionType *FType = MF.getFunction()->getFunctionType();
85 assert(CallConv == CallingConv::C);
87 SmallVector<ISD::InputArg, 16> Splits;
88 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
89 const ISD::InputArg &Arg = Ins[i];
91 // Split vertices into their elements
92 if (Arg.VT.isVector()) {
93 ISD::InputArg NewArg = Arg;
94 NewArg.Flags.setSplit();
95 NewArg.VT = Arg.VT.getVectorElementType();
97 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
98 // three or five element vertex only needs three or five registers,
100 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
101 unsigned NumElements = ParamType->getVectorNumElements();
103 for (unsigned j = 0; j != NumElements; ++j) {
104 Splits.push_back(NewArg);
105 NewArg.PartOffset += NewArg.VT.getStoreSize();
109 Splits.push_back(Arg);
113 SmallVector<CCValAssign, 16> ArgLocs;
114 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
115 getTargetMachine(), ArgLocs, *DAG.getContext());
117 AnalyzeFormalArguments(CCInfo, Splits);
119 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
121 CCValAssign &VA = ArgLocs[ArgIdx++];
122 assert(VA.isRegLoc() && "Parameter must be in a register!");
124 unsigned Reg = VA.getLocReg();
125 MVT VT = VA.getLocVT();
127 if (VT == MVT::i64) {
128 // For now assume it is a pointer
129 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
130 &AMDGPU::SReg_64RegClass);
131 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
132 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
136 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
138 Reg = MF.addLiveIn(Reg, RC);
139 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
141 const ISD::InputArg &Arg = Ins[i];
142 if (Arg.VT.isVector()) {
144 // Build a vector from the registers
145 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
146 unsigned NumElements = ParamType->getVectorNumElements();
148 SmallVector<SDValue, 4> Regs;
150 for (unsigned j = 1; j != NumElements; ++j) {
151 Reg = ArgLocs[ArgIdx++].getLocReg();
152 Reg = MF.addLiveIn(Reg, RC);
153 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
156 // Fill up the missing vector elements
157 NumElements = Arg.VT.getVectorNumElements() - NumElements;
158 for (unsigned j = 0; j != NumElements; ++j)
159 Regs.push_back(DAG.getUNDEF(VT));
161 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
162 Regs.data(), Regs.size()));
166 InVals.push_back(Val);
171 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
172 MachineInstr * MI, MachineBasicBlock * BB) const {
173 MachineRegisterInfo & MRI = BB->getParent()->getRegInfo();
174 MachineBasicBlock::iterator I = MI;
176 switch (MI->getOpcode()) {
178 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
179 case AMDGPU::BRANCH: return BB;
180 case AMDGPU::SI_INTERP:
181 LowerSI_INTERP(MI, *BB, I, MRI);
184 LowerSI_WQM(MI, *BB, I, MRI);
190 void SITargetLowering::LowerSI_WQM(MachineInstr *MI, MachineBasicBlock &BB,
191 MachineBasicBlock::iterator I, MachineRegisterInfo & MRI) const {
192 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::S_WQM_B64), AMDGPU::EXEC)
193 .addReg(AMDGPU::EXEC);
195 MI->eraseFromParent();
198 void SITargetLowering::LowerSI_INTERP(MachineInstr *MI, MachineBasicBlock &BB,
199 MachineBasicBlock::iterator I, MachineRegisterInfo & MRI) const {
200 unsigned tmp = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
201 unsigned M0 = MRI.createVirtualRegister(&AMDGPU::M0RegRegClass);
202 MachineOperand dst = MI->getOperand(0);
203 MachineOperand iReg = MI->getOperand(1);
204 MachineOperand jReg = MI->getOperand(2);
205 MachineOperand attr_chan = MI->getOperand(3);
206 MachineOperand attr = MI->getOperand(4);
207 MachineOperand params = MI->getOperand(5);
209 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::S_MOV_B32), M0)
212 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::V_INTERP_P1_F32), tmp)
214 .addOperand(attr_chan)
218 BuildMI(BB, I, BB.findDebugLoc(I), TII->get(AMDGPU::V_INTERP_P2_F32))
222 .addOperand(attr_chan)
226 MI->eraseFromParent();
229 EVT SITargetLowering::getSetCCResultType(EVT VT) const {
233 //===----------------------------------------------------------------------===//
234 // Custom DAG Lowering Operations
235 //===----------------------------------------------------------------------===//
237 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
238 switch (Op.getOpcode()) {
239 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
240 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
241 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
246 /// \brief Helper function for LowerBRCOND
247 static SDNode *findUser(SDValue Value, unsigned Opcode) {
249 SDNode *Parent = Value.getNode();
250 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
253 if (I.getUse().get() != Value)
256 if (I->getOpcode() == Opcode)
262 /// This transforms the control flow intrinsics to get the branch destination as
263 /// last parameter, also switches branch target with BR if the need arise
264 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
265 SelectionDAG &DAG) const {
267 DebugLoc DL = BRCOND.getDebugLoc();
269 SDNode *Intr = BRCOND.getOperand(1).getNode();
270 SDValue Target = BRCOND.getOperand(2);
273 if (Intr->getOpcode() == ISD::SETCC) {
274 // As long as we negate the condition everything is fine
275 SDNode *SetCC = Intr;
276 assert(SetCC->getConstantOperandVal(1) == 1);
277 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
279 Intr = SetCC->getOperand(0).getNode();
282 // Get the target from BR if we don't negate the condition
283 BR = findUser(BRCOND, ISD::BR);
284 Target = BR->getOperand(1);
287 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
289 // Build the result and
290 SmallVector<EVT, 4> Res;
291 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
292 Res.push_back(Intr->getValueType(i));
294 // operands of the new intrinsic call
295 SmallVector<SDValue, 4> Ops;
296 Ops.push_back(BRCOND.getOperand(0));
297 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
298 Ops.push_back(Intr->getOperand(i));
299 Ops.push_back(Target);
301 // build the new intrinsic call
302 SDNode *Result = DAG.getNode(
303 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
304 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
307 // Give the branch instruction our target
312 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
315 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
317 // Copy the intrinsic results to registers
318 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
319 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
323 Chain = DAG.getCopyToReg(
325 CopyToReg->getOperand(1),
326 SDValue(Result, i - 1),
329 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
332 // Remove the old intrinsic from the chain
333 DAG.ReplaceAllUsesOfValueWith(
334 SDValue(Intr, Intr->getNumValues() - 1),
335 Intr->getOperand(0));
340 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
341 SDValue LHS = Op.getOperand(0);
342 SDValue RHS = Op.getOperand(1);
343 SDValue True = Op.getOperand(2);
344 SDValue False = Op.getOperand(3);
345 SDValue CC = Op.getOperand(4);
346 EVT VT = Op.getValueType();
347 DebugLoc DL = Op.getDebugLoc();
349 // Possible Min/Max pattern
350 SDValue MinMax = LowerMinMax(Op, DAG);
351 if (MinMax.getNode()) {
355 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
356 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
359 //===----------------------------------------------------------------------===//
360 // Custom DAG optimizations
361 //===----------------------------------------------------------------------===//
363 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
364 DAGCombinerInfo &DCI) const {
365 SelectionDAG &DAG = DCI.DAG;
366 DebugLoc DL = N->getDebugLoc();
367 EVT VT = N->getValueType(0);
369 switch (N->getOpcode()) {
371 case ISD::SELECT_CC: {
373 ConstantSDNode *True, *False;
374 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
375 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
376 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
377 && True->isAllOnesValue()
378 && False->isNullValue()
380 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
381 N->getOperand(1), N->getOperand(4));
387 SDValue Arg0 = N->getOperand(0);
388 SDValue Arg1 = N->getOperand(1);
389 SDValue CC = N->getOperand(2);
390 ConstantSDNode * C = NULL;
391 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
393 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
395 && Arg0.getOpcode() == ISD::SIGN_EXTEND
396 && Arg0.getOperand(0).getValueType() == MVT::i1
397 && (C = dyn_cast<ConstantSDNode>(Arg1))
399 && CCOp == ISD::SETNE) {
400 return SimplifySetCC(VT, Arg0.getOperand(0),
401 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
409 /// \brief Test if RegClass is one of the VSrc classes
410 static bool isVSrc(unsigned RegClass) {
411 return AMDGPU::VSrc_32RegClassID == RegClass ||
412 AMDGPU::VSrc_64RegClassID == RegClass;
415 /// \brief Test if RegClass is one of the SSrc classes
416 static bool isSSrc(unsigned RegClass) {
417 return AMDGPU::SSrc_32RegClassID == RegClass ||
418 AMDGPU::SSrc_64RegClassID == RegClass;
421 /// \brief Analyze the possible immediate value Op
423 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
424 /// and the immediate value if it's a literal immediate
425 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
432 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N))
433 Imm.I = Node->getSExtValue();
434 else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
435 Imm.F = Node->getValueAPF().convertToFloat();
437 return -1; // It isn't an immediate
439 if ((Imm.I >= -16 && Imm.I <= 64) ||
440 Imm.F == 0.5f || Imm.F == -0.5f ||
441 Imm.F == 1.0f || Imm.F == -1.0f ||
442 Imm.F == 2.0f || Imm.F == -2.0f ||
443 Imm.F == 4.0f || Imm.F == -4.0f)
444 return 0; // It's an inline immediate
446 return Imm.I; // It's a literal immediate
449 /// \brief Try to fold an immediate directly into an instruction
450 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
451 bool &ScalarSlotUsed) const {
453 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
454 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
457 const SDValue &Op = Mov->getOperand(0);
458 int32_t Value = analyzeImmediate(Op.getNode());
460 // Not an immediate at all
463 } else if (Value == 0) {
464 // Inline immediates can always be fold
468 } else if (Value == Immediate) {
469 // Already fold literal immediate
473 } else if (!ScalarSlotUsed && !Immediate) {
474 // Fold this literal immediate
475 ScalarSlotUsed = true;
485 /// \brief Does "Op" fit into register class "RegClass" ?
486 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, SDValue &Op,
487 unsigned RegClass) const {
489 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
490 SDNode *Node = Op.getNode();
493 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
494 const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
495 OpClass = Desc.OpInfo[Op.getResNo()].RegClass;
497 } else if (Node->getOpcode() == ISD::CopyFromReg) {
498 RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
499 OpClass = MRI.getRegClass(Reg->getReg())->getID();
507 return TRI->getRegClass(RegClass)->hasSubClassEq(TRI->getRegClass(OpClass));
510 /// \brief Make sure that we don't exeed the number of allowed scalars
511 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
513 bool &ScalarSlotUsed) const {
515 // First map the operands register class to a destination class
516 if (RegClass == AMDGPU::VSrc_32RegClassID)
517 RegClass = AMDGPU::VReg_32RegClassID;
518 else if (RegClass == AMDGPU::VSrc_64RegClassID)
519 RegClass = AMDGPU::VReg_64RegClassID;
523 // Nothing todo if they fit naturaly
524 if (fitsRegClass(DAG, Operand, RegClass))
527 // If the scalar slot isn't used yet use it now
528 if (!ScalarSlotUsed) {
529 ScalarSlotUsed = true;
533 // This is a conservative aproach, it is possible that we can't determine
534 // the correct register class and copy too often, but better save than sorry.
535 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
536 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, DebugLoc(),
537 Operand.getValueType(), Operand, RC);
538 Operand = SDValue(Node, 0);
541 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
542 SelectionDAG &DAG) const {
544 // Original encoding (either e32 or e64)
545 int Opcode = Node->getMachineOpcode();
546 const MCInstrDesc *Desc = &TII->get(Opcode);
548 unsigned NumDefs = Desc->getNumDefs();
549 unsigned NumOps = Desc->getNumOperands();
551 // e64 version if available, -1 otherwise
552 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
553 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
555 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
556 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
558 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
559 bool HaveVSrc = false, HaveSSrc = false;
561 // First figure out what we alread have in this instruction
562 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
563 i != e && Op < NumOps; ++i, ++Op) {
565 unsigned RegClass = Desc->OpInfo[Op].RegClass;
566 if (isVSrc(RegClass))
568 else if (isSSrc(RegClass))
573 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
574 if (Imm != -1 && Imm != 0) {
580 // If we neither have VSrc nor SSrc it makes no sense to continue
581 if (!HaveVSrc && !HaveSSrc)
584 // No scalar allowed when we have both VSrc and SSrc
585 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
587 // Second go over the operands and try to fold them
588 std::vector<SDValue> Ops;
589 bool Promote2e64 = false;
590 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
591 i != e && Op < NumOps; ++i, ++Op) {
593 const SDValue &Operand = Node->getOperand(i);
594 Ops.push_back(Operand);
596 // Already folded immediate ?
597 if (isa<ConstantSDNode>(Operand.getNode()) ||
598 isa<ConstantFPSDNode>(Operand.getNode()))
601 // Is this a VSrc or SSrc operand ?
602 unsigned RegClass = Desc->OpInfo[Op].RegClass;
603 if (!isVSrc(RegClass) && !isSSrc(RegClass)) {
605 if (i == 1 && Desc->isCommutable() &&
606 fitsRegClass(DAG, Ops[0], RegClass) &&
607 foldImm(Ops[1], Immediate, ScalarSlotUsed)) {
609 assert(isVSrc(Desc->OpInfo[NumDefs].RegClass) ||
610 isSSrc(Desc->OpInfo[NumDefs].RegClass));
612 // Swap commutable operands
613 SDValue Tmp = Ops[1];
617 } else if (DescE64 && !Immediate) {
618 // Test if it makes sense to switch to e64 encoding
620 RegClass = DescE64->OpInfo[Op].RegClass;
622 if ((isVSrc(RegClass) || isSSrc(RegClass)) &&
623 foldImm(Ops[i], TmpImm, ScalarSlotUsed)) {
634 // Try to fold the immediates
635 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
636 // Folding didn't worked, make sure we don't hit the SReg limit
637 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
642 // Add the modifier flags while promoting
643 for (unsigned i = 0; i < 4; ++i)
644 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
647 // Add optional chain and glue
648 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
649 Ops.push_back(Node->getOperand(i));
651 // Either create a complete new or update the current instruction
653 return DAG.getMachineNode(OpcodeE64, Node->getDebugLoc(),
654 Node->getVTList(), Ops.data(), Ops.size());
656 return DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());