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::VSrc_64RegClass);
37 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
38 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
40 addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
41 addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
43 addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
44 addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
45 addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
47 addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
48 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
49 addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
51 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
52 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
54 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
55 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
57 computeRegisterProperties();
59 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
60 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
61 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
62 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
64 setOperationAction(ISD::ADD, MVT::i64, Legal);
65 setOperationAction(ISD::ADD, MVT::i32, Legal);
67 setOperationAction(ISD::BITCAST, MVT::i128, 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::SETCC, MVT::v2i1, Expand);
75 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
77 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
78 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
80 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
81 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
82 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
83 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
85 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
87 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
88 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
90 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
92 setTargetDAGCombine(ISD::SELECT_CC);
94 setTargetDAGCombine(ISD::SETCC);
96 setSchedulingPreference(Sched::RegPressure);
99 //===----------------------------------------------------------------------===//
100 // TargetLowering queries
101 //===----------------------------------------------------------------------===//
103 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
104 bool *IsFast) const {
105 // XXX: This depends on the address space and also we may want to revist
106 // the alignment values we specify in the DataLayout.
107 return VT.bitsGT(MVT::i32);
110 bool SITargetLowering::shouldSplitVectorElementType(EVT VT) const {
111 return VT.bitsLE(MVT::i8);
114 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
115 SDLoc DL, SDValue Chain,
116 unsigned Offset) const {
117 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
118 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
119 AMDGPUAS::CONSTANT_ADDRESS);
120 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
121 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
122 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
123 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
124 DAG.getConstant(Offset, MVT::i64));
125 return DAG.getLoad(VT, DL, Chain, Ptr,
126 MachinePointerInfo(UndefValue::get(PtrTy)),
127 false, false, false, ArgVT.getSizeInBits() >> 3);
131 SDValue SITargetLowering::LowerFormalArguments(
133 CallingConv::ID CallConv,
135 const SmallVectorImpl<ISD::InputArg> &Ins,
136 SDLoc DL, SelectionDAG &DAG,
137 SmallVectorImpl<SDValue> &InVals) const {
139 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
141 MachineFunction &MF = DAG.getMachineFunction();
142 FunctionType *FType = MF.getFunction()->getFunctionType();
143 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
145 assert(CallConv == CallingConv::C);
147 SmallVector<ISD::InputArg, 16> Splits;
148 uint32_t Skipped = 0;
150 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
151 const ISD::InputArg &Arg = Ins[i];
153 // First check if it's a PS input addr
154 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
156 assert((PSInputNum <= 15) && "Too many PS inputs!");
159 // We can savely skip PS inputs
165 Info->PSInputAddr |= 1 << PSInputNum++;
168 // Second split vertices into their elements
169 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
170 ISD::InputArg NewArg = Arg;
171 NewArg.Flags.setSplit();
172 NewArg.VT = Arg.VT.getVectorElementType();
174 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
175 // three or five element vertex only needs three or five registers,
176 // NOT four or eigth.
177 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
178 unsigned NumElements = ParamType->getVectorNumElements();
180 for (unsigned j = 0; j != NumElements; ++j) {
181 Splits.push_back(NewArg);
182 NewArg.PartOffset += NewArg.VT.getStoreSize();
186 Splits.push_back(Arg);
190 SmallVector<CCValAssign, 16> ArgLocs;
191 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
192 getTargetMachine(), ArgLocs, *DAG.getContext());
194 // At least one interpolation mode must be enabled or else the GPU will hang.
195 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
196 Info->PSInputAddr |= 1;
197 CCInfo.AllocateReg(AMDGPU::VGPR0);
198 CCInfo.AllocateReg(AMDGPU::VGPR1);
201 // The pointer to the list of arguments is stored in SGPR0, SGPR1
202 if (Info->ShaderType == ShaderType::COMPUTE) {
203 CCInfo.AllocateReg(AMDGPU::SGPR0);
204 CCInfo.AllocateReg(AMDGPU::SGPR1);
205 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
208 AnalyzeFormalArguments(CCInfo, Splits);
210 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
212 const ISD::InputArg &Arg = Ins[i];
213 if (Skipped & (1 << i)) {
214 InVals.push_back(DAG.getUNDEF(Arg.VT));
218 CCValAssign &VA = ArgLocs[ArgIdx++];
219 EVT VT = VA.getLocVT();
222 // The first 36 bytes of the input buffer contains information about
223 // thread group and global sizes.
224 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
225 36 + VA.getLocMemOffset());
226 InVals.push_back(Arg);
229 assert(VA.isRegLoc() && "Parameter must be in a register!");
231 unsigned Reg = VA.getLocReg();
233 if (VT == MVT::i64) {
234 // For now assume it is a pointer
235 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
236 &AMDGPU::SReg_64RegClass);
237 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
238 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
242 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
244 Reg = MF.addLiveIn(Reg, RC);
245 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
247 if (Arg.VT.isVector()) {
249 // Build a vector from the registers
250 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
251 unsigned NumElements = ParamType->getVectorNumElements();
253 SmallVector<SDValue, 4> Regs;
255 for (unsigned j = 1; j != NumElements; ++j) {
256 Reg = ArgLocs[ArgIdx++].getLocReg();
257 Reg = MF.addLiveIn(Reg, RC);
258 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
261 // Fill up the missing vector elements
262 NumElements = Arg.VT.getVectorNumElements() - NumElements;
263 for (unsigned j = 0; j != NumElements; ++j)
264 Regs.push_back(DAG.getUNDEF(VT));
266 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
267 Regs.data(), Regs.size()));
271 InVals.push_back(Val);
276 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
277 MachineInstr * MI, MachineBasicBlock * BB) const {
279 MachineBasicBlock::iterator I = *MI;
281 switch (MI->getOpcode()) {
283 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
284 case AMDGPU::BRANCH: return BB;
285 case AMDGPU::SI_ADDR64_RSRC: {
286 const SIInstrInfo *TII =
287 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
288 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
289 unsigned SuperReg = MI->getOperand(0).getReg();
290 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
291 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
292 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
293 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
294 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
295 .addOperand(MI->getOperand(1));
296 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
298 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
299 .addImm(RSRC_DATA_FORMAT >> 32);
300 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
302 .addImm(AMDGPU::sub0)
304 .addImm(AMDGPU::sub1);
305 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
307 .addImm(AMDGPU::sub0_sub1)
309 .addImm(AMDGPU::sub2_sub3);
310 MI->eraseFromParent();
313 case AMDGPU::V_SUB_F64: {
314 const SIInstrInfo *TII =
315 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
316 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
317 MI->getOperand(0).getReg())
318 .addReg(MI->getOperand(1).getReg())
319 .addReg(MI->getOperand(2).getReg())
320 .addImm(0) /* src2 */
322 .addImm(0) /* CLAMP */
323 .addImm(0) /* OMOD */
324 .addImm(2); /* NEG */
325 MI->eraseFromParent();
332 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
333 if (!VT.isVector()) {
336 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
339 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
343 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
344 VT = VT.getScalarType();
349 switch (VT.getSimpleVT().SimpleTy) {
351 return false; /* There is V_MAD_F32 for f32 */
361 //===----------------------------------------------------------------------===//
362 // Custom DAG Lowering Operations
363 //===----------------------------------------------------------------------===//
365 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
366 MachineFunction &MF = DAG.getMachineFunction();
367 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
368 switch (Op.getOpcode()) {
369 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
370 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
371 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
372 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
373 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
374 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
375 case ISD::INTRINSIC_WO_CHAIN: {
376 unsigned IntrinsicID =
377 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
378 EVT VT = Op.getValueType();
380 //XXX: Hardcoded we only use two to store the pointer to the parameters.
381 unsigned NumUserSGPRs = 2;
382 switch (IntrinsicID) {
383 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
384 case Intrinsic::r600_read_ngroups_x:
385 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
386 case Intrinsic::r600_read_ngroups_y:
387 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
388 case Intrinsic::r600_read_ngroups_z:
389 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
390 case Intrinsic::r600_read_global_size_x:
391 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
392 case Intrinsic::r600_read_global_size_y:
393 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
394 case Intrinsic::r600_read_global_size_z:
395 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
396 case Intrinsic::r600_read_local_size_x:
397 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
398 case Intrinsic::r600_read_local_size_y:
399 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
400 case Intrinsic::r600_read_local_size_z:
401 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
402 case Intrinsic::r600_read_tgid_x:
403 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
404 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
405 case Intrinsic::r600_read_tgid_y:
406 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
407 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
408 case Intrinsic::r600_read_tgid_z:
409 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
410 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
411 case Intrinsic::r600_read_tidig_x:
412 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
414 case Intrinsic::r600_read_tidig_y:
415 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
417 case Intrinsic::r600_read_tidig_z:
418 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
420 case AMDGPUIntrinsic::SI_load_const: {
422 ResourceDescriptorToi128(Op.getOperand(1), DAG),
426 MachineMemOperand *MMO = MF.getMachineMemOperand(
427 MachinePointerInfo(),
428 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
429 VT.getSizeInBits() / 8, 4);
430 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
431 Op->getVTList(), Ops, 2, VT, MMO);
433 case AMDGPUIntrinsic::SI_sample:
434 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
435 case AMDGPUIntrinsic::SI_sampleb:
436 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
437 case AMDGPUIntrinsic::SI_sampled:
438 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
439 case AMDGPUIntrinsic::SI_samplel:
440 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
441 case AMDGPUIntrinsic::SI_vs_load_input:
442 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
443 ResourceDescriptorToi128(Op.getOperand(1), DAG),
452 /// \brief Helper function for LowerBRCOND
453 static SDNode *findUser(SDValue Value, unsigned Opcode) {
455 SDNode *Parent = Value.getNode();
456 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
459 if (I.getUse().get() != Value)
462 if (I->getOpcode() == Opcode)
468 /// This transforms the control flow intrinsics to get the branch destination as
469 /// last parameter, also switches branch target with BR if the need arise
470 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
471 SelectionDAG &DAG) const {
475 SDNode *Intr = BRCOND.getOperand(1).getNode();
476 SDValue Target = BRCOND.getOperand(2);
479 if (Intr->getOpcode() == ISD::SETCC) {
480 // As long as we negate the condition everything is fine
481 SDNode *SetCC = Intr;
482 assert(SetCC->getConstantOperandVal(1) == 1);
483 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
485 Intr = SetCC->getOperand(0).getNode();
488 // Get the target from BR if we don't negate the condition
489 BR = findUser(BRCOND, ISD::BR);
490 Target = BR->getOperand(1);
493 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
495 // Build the result and
496 SmallVector<EVT, 4> Res;
497 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
498 Res.push_back(Intr->getValueType(i));
500 // operands of the new intrinsic call
501 SmallVector<SDValue, 4> Ops;
502 Ops.push_back(BRCOND.getOperand(0));
503 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
504 Ops.push_back(Intr->getOperand(i));
505 Ops.push_back(Target);
507 // build the new intrinsic call
508 SDNode *Result = DAG.getNode(
509 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
510 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
513 // Give the branch instruction our target
518 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
521 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
523 // Copy the intrinsic results to registers
524 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
525 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
529 Chain = DAG.getCopyToReg(
531 CopyToReg->getOperand(1),
532 SDValue(Result, i - 1),
535 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
538 // Remove the old intrinsic from the chain
539 DAG.ReplaceAllUsesOfValueWith(
540 SDValue(Intr, Intr->getNumValues() - 1),
541 Intr->getOperand(0));
546 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
547 SelectionDAG &DAG) const {
549 if (Op.getValueType() == MVT::i128) {
553 assert(Op.getOpcode() == ISD::UNDEF);
555 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
556 DAG.getConstant(0, MVT::i64),
557 DAG.getConstant(0, MVT::i64));
560 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
562 SelectionDAG &DAG) const {
563 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
565 ResourceDescriptorToi128(Op.getOperand(3), DAG),
569 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
570 SDValue LHS = Op.getOperand(0);
571 SDValue RHS = Op.getOperand(1);
572 SDValue True = Op.getOperand(2);
573 SDValue False = Op.getOperand(3);
574 SDValue CC = Op.getOperand(4);
575 EVT VT = Op.getValueType();
578 // Possible Min/Max pattern
579 SDValue MinMax = LowerMinMax(Op, DAG);
580 if (MinMax.getNode()) {
584 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
585 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
588 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
589 SelectionDAG &DAG) const {
590 EVT VT = Op.getValueType();
593 if (VT != MVT::i64) {
597 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
598 DAG.getConstant(31, MVT::i32));
600 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
603 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
604 SelectionDAG &DAG) const {
605 EVT VT = Op.getValueType();
608 if (VT != MVT::i64) {
612 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
613 DAG.getConstant(0, MVT::i32));
616 //===----------------------------------------------------------------------===//
617 // Custom DAG optimizations
618 //===----------------------------------------------------------------------===//
620 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
621 DAGCombinerInfo &DCI) const {
622 SelectionDAG &DAG = DCI.DAG;
624 EVT VT = N->getValueType(0);
626 switch (N->getOpcode()) {
628 case ISD::SELECT_CC: {
630 ConstantSDNode *True, *False;
631 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
632 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
633 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
634 && True->isAllOnesValue()
635 && False->isNullValue()
637 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
638 N->getOperand(1), N->getOperand(4));
644 SDValue Arg0 = N->getOperand(0);
645 SDValue Arg1 = N->getOperand(1);
646 SDValue CC = N->getOperand(2);
647 ConstantSDNode * C = NULL;
648 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
650 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
652 && Arg0.getOpcode() == ISD::SIGN_EXTEND
653 && Arg0.getOperand(0).getValueType() == MVT::i1
654 && (C = dyn_cast<ConstantSDNode>(Arg1))
656 && CCOp == ISD::SETNE) {
657 return SimplifySetCC(VT, Arg0.getOperand(0),
658 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
666 /// \brief Test if RegClass is one of the VSrc classes
667 static bool isVSrc(unsigned RegClass) {
668 return AMDGPU::VSrc_32RegClassID == RegClass ||
669 AMDGPU::VSrc_64RegClassID == RegClass;
672 /// \brief Test if RegClass is one of the SSrc classes
673 static bool isSSrc(unsigned RegClass) {
674 return AMDGPU::SSrc_32RegClassID == RegClass ||
675 AMDGPU::SSrc_64RegClassID == RegClass;
678 /// \brief Analyze the possible immediate value Op
680 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
681 /// and the immediate value if it's a literal immediate
682 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
689 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
690 if (Node->getZExtValue() >> 32) {
693 Imm.I = Node->getSExtValue();
694 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
695 Imm.F = Node->getValueAPF().convertToFloat();
697 return -1; // It isn't an immediate
699 if ((Imm.I >= -16 && Imm.I <= 64) ||
700 Imm.F == 0.5f || Imm.F == -0.5f ||
701 Imm.F == 1.0f || Imm.F == -1.0f ||
702 Imm.F == 2.0f || Imm.F == -2.0f ||
703 Imm.F == 4.0f || Imm.F == -4.0f)
704 return 0; // It's an inline immediate
706 return Imm.I; // It's a literal immediate
709 /// \brief Try to fold an immediate directly into an instruction
710 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
711 bool &ScalarSlotUsed) const {
713 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
714 const SIInstrInfo *TII =
715 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
716 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
719 const SDValue &Op = Mov->getOperand(0);
720 int32_t Value = analyzeImmediate(Op.getNode());
722 // Not an immediate at all
725 } else if (Value == 0) {
726 // Inline immediates can always be fold
730 } else if (Value == Immediate) {
731 // Already fold literal immediate
735 } else if (!ScalarSlotUsed && !Immediate) {
736 // Fold this literal immediate
737 ScalarSlotUsed = true;
747 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
748 SelectionDAG &DAG, const SDValue &Op) const {
749 const SIInstrInfo *TII =
750 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
751 const SIRegisterInfo &TRI = TII->getRegisterInfo();
753 if (!Op->isMachineOpcode()) {
754 switch(Op->getOpcode()) {
755 case ISD::CopyFromReg: {
756 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
757 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
758 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
759 return MRI.getRegClass(Reg);
761 return TRI.getPhysRegClass(Reg);
763 default: return NULL;
766 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
767 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
768 if (OpClassID != -1) {
769 return TRI.getRegClass(OpClassID);
771 switch(Op.getMachineOpcode()) {
772 case AMDGPU::COPY_TO_REGCLASS:
773 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
774 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
776 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
777 // class, then the register class for the value could be either a
778 // VReg or and SReg. In order to get a more accurate
779 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
780 OpClassID == AMDGPU::VSrc_64RegClassID) {
781 return getRegClassForNode(DAG, Op.getOperand(0));
783 return TRI.getRegClass(OpClassID);
784 case AMDGPU::EXTRACT_SUBREG: {
785 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
786 const TargetRegisterClass *SuperClass =
787 getRegClassForNode(DAG, Op.getOperand(0));
788 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
790 case AMDGPU::REG_SEQUENCE:
791 // Operand 0 is the register class id for REG_SEQUENCE instructions.
792 return TRI.getRegClass(
793 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
795 return getRegClassFor(Op.getSimpleValueType());
799 /// \brief Does "Op" fit into register class "RegClass" ?
800 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
801 unsigned RegClass) const {
802 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
803 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
807 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
810 /// \brief Make sure that we don't exeed the number of allowed scalars
811 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
813 bool &ScalarSlotUsed) const {
815 // First map the operands register class to a destination class
816 if (RegClass == AMDGPU::VSrc_32RegClassID)
817 RegClass = AMDGPU::VReg_32RegClassID;
818 else if (RegClass == AMDGPU::VSrc_64RegClassID)
819 RegClass = AMDGPU::VReg_64RegClassID;
823 // Nothing todo if they fit naturaly
824 if (fitsRegClass(DAG, Operand, RegClass))
827 // If the scalar slot isn't used yet use it now
828 if (!ScalarSlotUsed) {
829 ScalarSlotUsed = true;
833 // This is a conservative aproach, it is possible that we can't determine
834 // the correct register class and copy too often, but better save than sorry.
835 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
836 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
837 Operand.getValueType(), Operand, RC);
838 Operand = SDValue(Node, 0);
841 /// \returns true if \p Node's operands are different from the SDValue list
843 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
844 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
845 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
852 /// \brief Try to fold the Nodes operands into the Node
853 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
854 SelectionDAG &DAG) const {
856 // Original encoding (either e32 or e64)
857 int Opcode = Node->getMachineOpcode();
858 const SIInstrInfo *TII =
859 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
860 const MCInstrDesc *Desc = &TII->get(Opcode);
862 unsigned NumDefs = Desc->getNumDefs();
863 unsigned NumOps = Desc->getNumOperands();
865 // Commuted opcode if available
866 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
867 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
869 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
870 assert(!DescRev || DescRev->getNumOperands() == NumOps);
872 // e64 version if available, -1 otherwise
873 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
874 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
876 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
877 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
879 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
880 bool HaveVSrc = false, HaveSSrc = false;
882 // First figure out what we alread have in this instruction
883 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
884 i != e && Op < NumOps; ++i, ++Op) {
886 unsigned RegClass = Desc->OpInfo[Op].RegClass;
887 if (isVSrc(RegClass))
889 else if (isSSrc(RegClass))
894 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
895 if (Imm != -1 && Imm != 0) {
901 // If we neither have VSrc nor SSrc it makes no sense to continue
902 if (!HaveVSrc && !HaveSSrc)
905 // No scalar allowed when we have both VSrc and SSrc
906 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
908 // Second go over the operands and try to fold them
909 std::vector<SDValue> Ops;
910 bool Promote2e64 = false;
911 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
912 i != e && Op < NumOps; ++i, ++Op) {
914 const SDValue &Operand = Node->getOperand(i);
915 Ops.push_back(Operand);
917 // Already folded immediate ?
918 if (isa<ConstantSDNode>(Operand.getNode()) ||
919 isa<ConstantFPSDNode>(Operand.getNode()))
922 // Is this a VSrc or SSrc operand ?
923 unsigned RegClass = Desc->OpInfo[Op].RegClass;
924 if (isVSrc(RegClass) || isSSrc(RegClass)) {
925 // Try to fold the immediates
926 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
927 // Folding didn't worked, make sure we don't hit the SReg limit
928 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
933 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
935 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
936 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
938 // Test if it makes sense to swap operands
939 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
940 (!fitsRegClass(DAG, Ops[1], RegClass) &&
941 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
943 // Swap commutable operands
944 SDValue Tmp = Ops[1];
954 if (DescE64 && !Immediate) {
956 // Test if it makes sense to switch to e64 encoding
957 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
958 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
962 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
963 (!fitsRegClass(DAG, Ops[i], RegClass) &&
964 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
966 // Switch to e64 encoding
976 // Add the modifier flags while promoting
977 for (unsigned i = 0; i < 4; ++i)
978 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
981 // Add optional chain and glue
982 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
983 Ops.push_back(Node->getOperand(i));
985 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
986 // this case a brand new node is always be created, even if the operands
987 // are the same as before. So, manually check if anything has been changed.
988 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
992 // Create a complete new instruction
993 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
996 /// \brief Helper function for adjustWritemask
997 static unsigned SubIdx2Lane(unsigned Idx) {
1000 case AMDGPU::sub0: return 0;
1001 case AMDGPU::sub1: return 1;
1002 case AMDGPU::sub2: return 2;
1003 case AMDGPU::sub3: return 3;
1007 /// \brief Adjust the writemask of MIMG instructions
1008 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1009 SelectionDAG &DAG) const {
1010 SDNode *Users[4] = { };
1011 unsigned Writemask = 0, Lane = 0;
1013 // Try to figure out the used register components
1014 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1017 // Abort if we can't understand the usage
1018 if (!I->isMachineOpcode() ||
1019 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1022 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1024 // Abort if we have more than one user per component
1029 Writemask |= 1 << Lane;
1032 // Abort if all components are used
1033 if (Writemask == 0xf)
1036 // Adjust the writemask in the node
1037 std::vector<SDValue> Ops;
1038 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1039 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1040 Ops.push_back(Node->getOperand(i));
1041 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1043 // If we only got one lane, replace it with a copy
1044 if (Writemask == (1U << Lane)) {
1045 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1046 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1047 SDLoc(), Users[Lane]->getValueType(0),
1048 SDValue(Node, 0), RC);
1049 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1053 // Update the users of the node with the new indices
1054 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1056 SDNode *User = Users[i];
1060 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1061 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1065 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1066 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1067 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1072 /// \brief Fold the instructions after slecting them
1073 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1074 SelectionDAG &DAG) const {
1075 const SIInstrInfo *TII =
1076 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1077 Node = AdjustRegClass(Node, DAG);
1079 if (TII->isMIMG(Node->getMachineOpcode()))
1080 adjustWritemask(Node, DAG);
1082 return foldOperands(Node, DAG);
1085 /// \brief Assign the register class depending on the number of
1086 /// bits set in the writemask
1087 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1088 SDNode *Node) const {
1089 const SIInstrInfo *TII =
1090 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1091 if (!TII->isMIMG(MI->getOpcode()))
1094 unsigned VReg = MI->getOperand(0).getReg();
1095 unsigned Writemask = MI->getOperand(1).getImm();
1096 unsigned BitsSet = 0;
1097 for (unsigned i = 0; i < 4; ++i)
1098 BitsSet += Writemask & (1 << i) ? 1 : 0;
1100 const TargetRegisterClass *RC;
1103 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1104 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1105 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1108 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1109 MRI.setRegClass(VReg, RC);
1112 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1113 SelectionDAG &DAG) const {
1116 unsigned NewOpcode = N->getMachineOpcode();
1118 switch (N->getMachineOpcode()) {
1120 case AMDGPU::S_LOAD_DWORD_IMM:
1121 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1123 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1124 if (NewOpcode == N->getMachineOpcode()) {
1125 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1128 case AMDGPU::S_LOAD_DWORDX4_IMM:
1129 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1130 if (NewOpcode == N->getMachineOpcode()) {
1131 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1133 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1136 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1138 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1139 DAG.getConstant(0, MVT::i64)), 0),
1141 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1143 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1148 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1149 const TargetRegisterClass *RC,
1150 unsigned Reg, EVT VT) const {
1151 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1153 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1154 cast<RegisterSDNode>(VReg)->getReg(), VT);