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 // We need to custom lower vector stores from local memory
70 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
71 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
73 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
74 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
76 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
78 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
79 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
81 setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
82 setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
84 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
85 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
86 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
87 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
89 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
91 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
92 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
93 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
97 setTargetDAGCombine(ISD::SELECT_CC);
99 setTargetDAGCombine(ISD::SETCC);
101 setSchedulingPreference(Sched::RegPressure);
104 //===----------------------------------------------------------------------===//
105 // TargetLowering queries
106 //===----------------------------------------------------------------------===//
108 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
109 bool *IsFast) const {
110 // XXX: This depends on the address space and also we may want to revist
111 // the alignment values we specify in the DataLayout.
112 return VT.bitsGT(MVT::i32);
115 bool SITargetLowering::shouldSplitVectorElementType(EVT VT) const {
116 return VT.bitsLE(MVT::i8);
119 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
120 SDLoc DL, SDValue Chain,
121 unsigned Offset) const {
122 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
123 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
124 AMDGPUAS::CONSTANT_ADDRESS);
125 EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
126 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
127 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
128 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
129 DAG.getConstant(Offset, MVT::i64));
130 return DAG.getLoad(VT, DL, Chain, Ptr,
131 MachinePointerInfo(UndefValue::get(PtrTy)),
132 false, false, false, ArgVT.getSizeInBits() >> 3);
136 SDValue SITargetLowering::LowerFormalArguments(
138 CallingConv::ID CallConv,
140 const SmallVectorImpl<ISD::InputArg> &Ins,
141 SDLoc DL, SelectionDAG &DAG,
142 SmallVectorImpl<SDValue> &InVals) const {
144 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
146 MachineFunction &MF = DAG.getMachineFunction();
147 FunctionType *FType = MF.getFunction()->getFunctionType();
148 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
150 assert(CallConv == CallingConv::C);
152 SmallVector<ISD::InputArg, 16> Splits;
153 uint32_t Skipped = 0;
155 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
156 const ISD::InputArg &Arg = Ins[i];
158 // First check if it's a PS input addr
159 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
161 assert((PSInputNum <= 15) && "Too many PS inputs!");
164 // We can savely skip PS inputs
170 Info->PSInputAddr |= 1 << PSInputNum++;
173 // Second split vertices into their elements
174 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
175 ISD::InputArg NewArg = Arg;
176 NewArg.Flags.setSplit();
177 NewArg.VT = Arg.VT.getVectorElementType();
179 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
180 // three or five element vertex only needs three or five registers,
181 // NOT four or eigth.
182 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
183 unsigned NumElements = ParamType->getVectorNumElements();
185 for (unsigned j = 0; j != NumElements; ++j) {
186 Splits.push_back(NewArg);
187 NewArg.PartOffset += NewArg.VT.getStoreSize();
191 Splits.push_back(Arg);
195 SmallVector<CCValAssign, 16> ArgLocs;
196 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
197 getTargetMachine(), ArgLocs, *DAG.getContext());
199 // At least one interpolation mode must be enabled or else the GPU will hang.
200 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
201 Info->PSInputAddr |= 1;
202 CCInfo.AllocateReg(AMDGPU::VGPR0);
203 CCInfo.AllocateReg(AMDGPU::VGPR1);
206 // The pointer to the list of arguments is stored in SGPR0, SGPR1
207 if (Info->ShaderType == ShaderType::COMPUTE) {
208 CCInfo.AllocateReg(AMDGPU::SGPR0);
209 CCInfo.AllocateReg(AMDGPU::SGPR1);
210 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
213 AnalyzeFormalArguments(CCInfo, Splits);
215 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
217 const ISD::InputArg &Arg = Ins[i];
218 if (Skipped & (1 << i)) {
219 InVals.push_back(DAG.getUNDEF(Arg.VT));
223 CCValAssign &VA = ArgLocs[ArgIdx++];
224 EVT VT = VA.getLocVT();
227 // The first 36 bytes of the input buffer contains information about
228 // thread group and global sizes.
229 SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
230 36 + VA.getLocMemOffset());
231 InVals.push_back(Arg);
234 assert(VA.isRegLoc() && "Parameter must be in a register!");
236 unsigned Reg = VA.getLocReg();
238 if (VT == MVT::i64) {
239 // For now assume it is a pointer
240 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
241 &AMDGPU::SReg_64RegClass);
242 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
243 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
247 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
249 Reg = MF.addLiveIn(Reg, RC);
250 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
252 if (Arg.VT.isVector()) {
254 // Build a vector from the registers
255 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
256 unsigned NumElements = ParamType->getVectorNumElements();
258 SmallVector<SDValue, 4> Regs;
260 for (unsigned j = 1; j != NumElements; ++j) {
261 Reg = ArgLocs[ArgIdx++].getLocReg();
262 Reg = MF.addLiveIn(Reg, RC);
263 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
266 // Fill up the missing vector elements
267 NumElements = Arg.VT.getVectorNumElements() - NumElements;
268 for (unsigned j = 0; j != NumElements; ++j)
269 Regs.push_back(DAG.getUNDEF(VT));
271 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
272 Regs.data(), Regs.size()));
276 InVals.push_back(Val);
281 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
282 MachineInstr * MI, MachineBasicBlock * BB) const {
284 MachineBasicBlock::iterator I = *MI;
286 switch (MI->getOpcode()) {
288 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
289 case AMDGPU::BRANCH: return BB;
290 case AMDGPU::SI_ADDR64_RSRC: {
291 const SIInstrInfo *TII =
292 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
293 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
294 unsigned SuperReg = MI->getOperand(0).getReg();
295 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
296 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
297 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
298 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
299 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
300 .addOperand(MI->getOperand(1));
301 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
303 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
304 .addImm(RSRC_DATA_FORMAT >> 32);
305 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
307 .addImm(AMDGPU::sub0)
309 .addImm(AMDGPU::sub1);
310 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
312 .addImm(AMDGPU::sub0_sub1)
314 .addImm(AMDGPU::sub2_sub3);
315 MI->eraseFromParent();
318 case AMDGPU::V_SUB_F64: {
319 const SIInstrInfo *TII =
320 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
321 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
322 MI->getOperand(0).getReg())
323 .addReg(MI->getOperand(1).getReg())
324 .addReg(MI->getOperand(2).getReg())
325 .addImm(0) /* src2 */
327 .addImm(0) /* CLAMP */
328 .addImm(0) /* OMOD */
329 .addImm(2); /* NEG */
330 MI->eraseFromParent();
337 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
338 if (!VT.isVector()) {
341 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
344 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
348 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
349 VT = VT.getScalarType();
354 switch (VT.getSimpleVT().SimpleTy) {
356 return false; /* There is V_MAD_F32 for f32 */
366 //===----------------------------------------------------------------------===//
367 // Custom DAG Lowering Operations
368 //===----------------------------------------------------------------------===//
370 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
371 MachineFunction &MF = DAG.getMachineFunction();
372 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
373 switch (Op.getOpcode()) {
374 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
375 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
377 LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
378 if (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
379 Op.getValueType().isVector()) {
380 SDValue MergedValues[2] = {
381 SplitVectorLoad(Op, DAG),
384 return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
389 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
390 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
391 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
392 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
393 case ISD::INTRINSIC_WO_CHAIN: {
394 unsigned IntrinsicID =
395 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
396 EVT VT = Op.getValueType();
398 //XXX: Hardcoded we only use two to store the pointer to the parameters.
399 unsigned NumUserSGPRs = 2;
400 switch (IntrinsicID) {
401 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
402 case Intrinsic::r600_read_ngroups_x:
403 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
404 case Intrinsic::r600_read_ngroups_y:
405 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
406 case Intrinsic::r600_read_ngroups_z:
407 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
408 case Intrinsic::r600_read_global_size_x:
409 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
410 case Intrinsic::r600_read_global_size_y:
411 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
412 case Intrinsic::r600_read_global_size_z:
413 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
414 case Intrinsic::r600_read_local_size_x:
415 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
416 case Intrinsic::r600_read_local_size_y:
417 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
418 case Intrinsic::r600_read_local_size_z:
419 return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
420 case Intrinsic::r600_read_tgid_x:
421 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
422 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
423 case Intrinsic::r600_read_tgid_y:
424 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
425 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
426 case Intrinsic::r600_read_tgid_z:
427 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
428 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
429 case Intrinsic::r600_read_tidig_x:
430 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
432 case Intrinsic::r600_read_tidig_y:
433 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
435 case Intrinsic::r600_read_tidig_z:
436 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
438 case AMDGPUIntrinsic::SI_load_const: {
440 ResourceDescriptorToi128(Op.getOperand(1), DAG),
444 MachineMemOperand *MMO = MF.getMachineMemOperand(
445 MachinePointerInfo(),
446 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
447 VT.getSizeInBits() / 8, 4);
448 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
449 Op->getVTList(), Ops, 2, VT, MMO);
451 case AMDGPUIntrinsic::SI_sample:
452 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
453 case AMDGPUIntrinsic::SI_sampleb:
454 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
455 case AMDGPUIntrinsic::SI_sampled:
456 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
457 case AMDGPUIntrinsic::SI_samplel:
458 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
459 case AMDGPUIntrinsic::SI_vs_load_input:
460 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
461 ResourceDescriptorToi128(Op.getOperand(1), DAG),
470 /// \brief Helper function for LowerBRCOND
471 static SDNode *findUser(SDValue Value, unsigned Opcode) {
473 SDNode *Parent = Value.getNode();
474 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
477 if (I.getUse().get() != Value)
480 if (I->getOpcode() == Opcode)
486 /// This transforms the control flow intrinsics to get the branch destination as
487 /// last parameter, also switches branch target with BR if the need arise
488 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
489 SelectionDAG &DAG) const {
493 SDNode *Intr = BRCOND.getOperand(1).getNode();
494 SDValue Target = BRCOND.getOperand(2);
497 if (Intr->getOpcode() == ISD::SETCC) {
498 // As long as we negate the condition everything is fine
499 SDNode *SetCC = Intr;
500 assert(SetCC->getConstantOperandVal(1) == 1);
501 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
503 Intr = SetCC->getOperand(0).getNode();
506 // Get the target from BR if we don't negate the condition
507 BR = findUser(BRCOND, ISD::BR);
508 Target = BR->getOperand(1);
511 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
513 // Build the result and
514 SmallVector<EVT, 4> Res;
515 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
516 Res.push_back(Intr->getValueType(i));
518 // operands of the new intrinsic call
519 SmallVector<SDValue, 4> Ops;
520 Ops.push_back(BRCOND.getOperand(0));
521 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
522 Ops.push_back(Intr->getOperand(i));
523 Ops.push_back(Target);
525 // build the new intrinsic call
526 SDNode *Result = DAG.getNode(
527 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
528 DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
531 // Give the branch instruction our target
536 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
539 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
541 // Copy the intrinsic results to registers
542 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
543 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
547 Chain = DAG.getCopyToReg(
549 CopyToReg->getOperand(1),
550 SDValue(Result, i - 1),
553 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
556 // Remove the old intrinsic from the chain
557 DAG.ReplaceAllUsesOfValueWith(
558 SDValue(Intr, Intr->getNumValues() - 1),
559 Intr->getOperand(0));
564 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
565 SelectionDAG &DAG) const {
567 if (Op.getValueType() == MVT::i128) {
571 assert(Op.getOpcode() == ISD::UNDEF);
573 return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
574 DAG.getConstant(0, MVT::i64),
575 DAG.getConstant(0, MVT::i64));
578 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
580 SelectionDAG &DAG) const {
581 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
583 ResourceDescriptorToi128(Op.getOperand(3), DAG),
587 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
588 SDValue LHS = Op.getOperand(0);
589 SDValue RHS = Op.getOperand(1);
590 SDValue True = Op.getOperand(2);
591 SDValue False = Op.getOperand(3);
592 SDValue CC = Op.getOperand(4);
593 EVT VT = Op.getValueType();
596 // Possible Min/Max pattern
597 SDValue MinMax = LowerMinMax(Op, DAG);
598 if (MinMax.getNode()) {
602 SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
603 return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
606 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
607 SelectionDAG &DAG) const {
608 EVT VT = Op.getValueType();
611 if (VT != MVT::i64) {
615 SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
616 DAG.getConstant(31, MVT::i32));
618 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
621 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
622 SelectionDAG &DAG) const {
623 EVT VT = Op.getValueType();
626 if (VT != MVT::i64) {
630 return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
631 DAG.getConstant(0, MVT::i32));
634 //===----------------------------------------------------------------------===//
635 // Custom DAG optimizations
636 //===----------------------------------------------------------------------===//
638 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
639 DAGCombinerInfo &DCI) const {
640 SelectionDAG &DAG = DCI.DAG;
642 EVT VT = N->getValueType(0);
644 switch (N->getOpcode()) {
646 case ISD::SELECT_CC: {
648 ConstantSDNode *True, *False;
649 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
650 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
651 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
652 && True->isAllOnesValue()
653 && False->isNullValue()
655 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
656 N->getOperand(1), N->getOperand(4));
662 SDValue Arg0 = N->getOperand(0);
663 SDValue Arg1 = N->getOperand(1);
664 SDValue CC = N->getOperand(2);
665 ConstantSDNode * C = NULL;
666 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
668 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
670 && Arg0.getOpcode() == ISD::SIGN_EXTEND
671 && Arg0.getOperand(0).getValueType() == MVT::i1
672 && (C = dyn_cast<ConstantSDNode>(Arg1))
674 && CCOp == ISD::SETNE) {
675 return SimplifySetCC(VT, Arg0.getOperand(0),
676 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
684 /// \brief Test if RegClass is one of the VSrc classes
685 static bool isVSrc(unsigned RegClass) {
686 return AMDGPU::VSrc_32RegClassID == RegClass ||
687 AMDGPU::VSrc_64RegClassID == RegClass;
690 /// \brief Test if RegClass is one of the SSrc classes
691 static bool isSSrc(unsigned RegClass) {
692 return AMDGPU::SSrc_32RegClassID == RegClass ||
693 AMDGPU::SSrc_64RegClassID == RegClass;
696 /// \brief Analyze the possible immediate value Op
698 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
699 /// and the immediate value if it's a literal immediate
700 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
707 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
708 if (Node->getZExtValue() >> 32) {
711 Imm.I = Node->getSExtValue();
712 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
713 Imm.F = Node->getValueAPF().convertToFloat();
715 return -1; // It isn't an immediate
717 if ((Imm.I >= -16 && Imm.I <= 64) ||
718 Imm.F == 0.5f || Imm.F == -0.5f ||
719 Imm.F == 1.0f || Imm.F == -1.0f ||
720 Imm.F == 2.0f || Imm.F == -2.0f ||
721 Imm.F == 4.0f || Imm.F == -4.0f)
722 return 0; // It's an inline immediate
724 return Imm.I; // It's a literal immediate
727 /// \brief Try to fold an immediate directly into an instruction
728 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
729 bool &ScalarSlotUsed) const {
731 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
732 const SIInstrInfo *TII =
733 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
734 if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
737 const SDValue &Op = Mov->getOperand(0);
738 int32_t Value = analyzeImmediate(Op.getNode());
740 // Not an immediate at all
743 } else if (Value == 0) {
744 // Inline immediates can always be fold
748 } else if (Value == Immediate) {
749 // Already fold literal immediate
753 } else if (!ScalarSlotUsed && !Immediate) {
754 // Fold this literal immediate
755 ScalarSlotUsed = true;
765 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
766 SelectionDAG &DAG, const SDValue &Op) const {
767 const SIInstrInfo *TII =
768 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
769 const SIRegisterInfo &TRI = TII->getRegisterInfo();
771 if (!Op->isMachineOpcode()) {
772 switch(Op->getOpcode()) {
773 case ISD::CopyFromReg: {
774 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
775 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
776 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
777 return MRI.getRegClass(Reg);
779 return TRI.getPhysRegClass(Reg);
781 default: return NULL;
784 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
785 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
786 if (OpClassID != -1) {
787 return TRI.getRegClass(OpClassID);
789 switch(Op.getMachineOpcode()) {
790 case AMDGPU::COPY_TO_REGCLASS:
791 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
792 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
794 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
795 // class, then the register class for the value could be either a
796 // VReg or and SReg. In order to get a more accurate
797 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
798 OpClassID == AMDGPU::VSrc_64RegClassID) {
799 return getRegClassForNode(DAG, Op.getOperand(0));
801 return TRI.getRegClass(OpClassID);
802 case AMDGPU::EXTRACT_SUBREG: {
803 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
804 const TargetRegisterClass *SuperClass =
805 getRegClassForNode(DAG, Op.getOperand(0));
806 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
808 case AMDGPU::REG_SEQUENCE:
809 // Operand 0 is the register class id for REG_SEQUENCE instructions.
810 return TRI.getRegClass(
811 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
813 return getRegClassFor(Op.getSimpleValueType());
817 /// \brief Does "Op" fit into register class "RegClass" ?
818 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
819 unsigned RegClass) const {
820 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
821 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
825 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
828 /// \brief Make sure that we don't exeed the number of allowed scalars
829 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
831 bool &ScalarSlotUsed) const {
833 // First map the operands register class to a destination class
834 if (RegClass == AMDGPU::VSrc_32RegClassID)
835 RegClass = AMDGPU::VReg_32RegClassID;
836 else if (RegClass == AMDGPU::VSrc_64RegClassID)
837 RegClass = AMDGPU::VReg_64RegClassID;
841 // Nothing todo if they fit naturaly
842 if (fitsRegClass(DAG, Operand, RegClass))
845 // If the scalar slot isn't used yet use it now
846 if (!ScalarSlotUsed) {
847 ScalarSlotUsed = true;
851 // This is a conservative aproach, it is possible that we can't determine
852 // the correct register class and copy too often, but better save than sorry.
853 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
854 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
855 Operand.getValueType(), Operand, RC);
856 Operand = SDValue(Node, 0);
859 /// \returns true if \p Node's operands are different from the SDValue list
861 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
862 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
863 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
870 /// \brief Try to fold the Nodes operands into the Node
871 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
872 SelectionDAG &DAG) const {
874 // Original encoding (either e32 or e64)
875 int Opcode = Node->getMachineOpcode();
876 const SIInstrInfo *TII =
877 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
878 const MCInstrDesc *Desc = &TII->get(Opcode);
880 unsigned NumDefs = Desc->getNumDefs();
881 unsigned NumOps = Desc->getNumOperands();
883 // Commuted opcode if available
884 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
885 const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
887 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
888 assert(!DescRev || DescRev->getNumOperands() == NumOps);
890 // e64 version if available, -1 otherwise
891 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
892 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
894 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
895 assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
897 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
898 bool HaveVSrc = false, HaveSSrc = false;
900 // First figure out what we alread have in this instruction
901 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
902 i != e && Op < NumOps; ++i, ++Op) {
904 unsigned RegClass = Desc->OpInfo[Op].RegClass;
905 if (isVSrc(RegClass))
907 else if (isSSrc(RegClass))
912 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
913 if (Imm != -1 && Imm != 0) {
919 // If we neither have VSrc nor SSrc it makes no sense to continue
920 if (!HaveVSrc && !HaveSSrc)
923 // No scalar allowed when we have both VSrc and SSrc
924 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
926 // Second go over the operands and try to fold them
927 std::vector<SDValue> Ops;
928 bool Promote2e64 = false;
929 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
930 i != e && Op < NumOps; ++i, ++Op) {
932 const SDValue &Operand = Node->getOperand(i);
933 Ops.push_back(Operand);
935 // Already folded immediate ?
936 if (isa<ConstantSDNode>(Operand.getNode()) ||
937 isa<ConstantFPSDNode>(Operand.getNode()))
940 // Is this a VSrc or SSrc operand ?
941 unsigned RegClass = Desc->OpInfo[Op].RegClass;
942 if (isVSrc(RegClass) || isSSrc(RegClass)) {
943 // Try to fold the immediates
944 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
945 // Folding didn't worked, make sure we don't hit the SReg limit
946 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
951 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
953 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
954 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
956 // Test if it makes sense to swap operands
957 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
958 (!fitsRegClass(DAG, Ops[1], RegClass) &&
959 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
961 // Swap commutable operands
962 SDValue Tmp = Ops[1];
972 if (DescE64 && !Immediate) {
974 // Test if it makes sense to switch to e64 encoding
975 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
976 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
980 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
981 (!fitsRegClass(DAG, Ops[i], RegClass) &&
982 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
984 // Switch to e64 encoding
994 // Add the modifier flags while promoting
995 for (unsigned i = 0; i < 4; ++i)
996 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
999 // Add optional chain and glue
1000 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1001 Ops.push_back(Node->getOperand(i));
1003 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1004 // this case a brand new node is always be created, even if the operands
1005 // are the same as before. So, manually check if anything has been changed.
1006 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1010 // Create a complete new instruction
1011 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1014 /// \brief Helper function for adjustWritemask
1015 static unsigned SubIdx2Lane(unsigned Idx) {
1018 case AMDGPU::sub0: return 0;
1019 case AMDGPU::sub1: return 1;
1020 case AMDGPU::sub2: return 2;
1021 case AMDGPU::sub3: return 3;
1025 /// \brief Adjust the writemask of MIMG instructions
1026 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1027 SelectionDAG &DAG) const {
1028 SDNode *Users[4] = { };
1029 unsigned Writemask = 0, Lane = 0;
1031 // Try to figure out the used register components
1032 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1035 // Abort if we can't understand the usage
1036 if (!I->isMachineOpcode() ||
1037 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1040 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1042 // Abort if we have more than one user per component
1047 Writemask |= 1 << Lane;
1050 // Abort if all components are used
1051 if (Writemask == 0xf)
1054 // Adjust the writemask in the node
1055 std::vector<SDValue> Ops;
1056 Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1057 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1058 Ops.push_back(Node->getOperand(i));
1059 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1061 // If we only got one lane, replace it with a copy
1062 if (Writemask == (1U << Lane)) {
1063 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1064 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1065 SDLoc(), Users[Lane]->getValueType(0),
1066 SDValue(Node, 0), RC);
1067 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1071 // Update the users of the node with the new indices
1072 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1074 SDNode *User = Users[i];
1078 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1079 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1083 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1084 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1085 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1090 /// \brief Fold the instructions after slecting them
1091 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1092 SelectionDAG &DAG) const {
1093 const SIInstrInfo *TII =
1094 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1095 Node = AdjustRegClass(Node, DAG);
1097 if (TII->isMIMG(Node->getMachineOpcode()))
1098 adjustWritemask(Node, DAG);
1100 return foldOperands(Node, DAG);
1103 /// \brief Assign the register class depending on the number of
1104 /// bits set in the writemask
1105 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1106 SDNode *Node) const {
1107 const SIInstrInfo *TII =
1108 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1109 if (!TII->isMIMG(MI->getOpcode()))
1112 unsigned VReg = MI->getOperand(0).getReg();
1113 unsigned Writemask = MI->getOperand(1).getImm();
1114 unsigned BitsSet = 0;
1115 for (unsigned i = 0; i < 4; ++i)
1116 BitsSet += Writemask & (1 << i) ? 1 : 0;
1118 const TargetRegisterClass *RC;
1121 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1122 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1123 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1126 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1127 MRI.setRegClass(VReg, RC);
1130 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1131 SelectionDAG &DAG) const {
1134 unsigned NewOpcode = N->getMachineOpcode();
1136 switch (N->getMachineOpcode()) {
1138 case AMDGPU::S_LOAD_DWORD_IMM:
1139 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1141 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1142 if (NewOpcode == N->getMachineOpcode()) {
1143 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1146 case AMDGPU::S_LOAD_DWORDX4_IMM:
1147 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1148 if (NewOpcode == N->getMachineOpcode()) {
1149 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1151 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1154 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1156 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1157 DAG.getConstant(0, MVT::i64)), 0),
1159 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1161 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1166 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1167 const TargetRegisterClass *RC,
1168 unsigned Reg, EVT VT) const {
1169 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1171 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1172 cast<RegisterSDNode>(VReg)->getReg(), VT);