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 "AMDGPUIntrinsicInfo.h"
18 #include "AMDGPUSubtarget.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/ADT/SmallString.h"
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32 AMDGPUTargetLowering(TM) {
33 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
34 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
36 addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
37 addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
39 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
40 addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
42 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
43 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
44 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
46 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
47 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
49 addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
50 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
52 addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
53 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
55 computeRegisterProperties();
58 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
59 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
60 setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
61 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
62 setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
63 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
65 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
66 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
67 setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
68 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
69 setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
70 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
72 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
73 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
74 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
75 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
77 setOperationAction(ISD::ADD, MVT::i32, Legal);
78 setOperationAction(ISD::ADDC, MVT::i32, Legal);
79 setOperationAction(ISD::ADDE, MVT::i32, Legal);
80 setOperationAction(ISD::SUBC, MVT::i32, Legal);
81 setOperationAction(ISD::SUBE, MVT::i32, Legal);
83 // We need to custom lower vector stores from local memory
84 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
85 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
86 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
87 setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
89 setOperationAction(ISD::STORE, MVT::v8i32, Custom);
90 setOperationAction(ISD::STORE, MVT::v16i32, Custom);
92 // We need to custom lower loads/stores from private memory
93 setOperationAction(ISD::LOAD, MVT::i32, Custom);
94 setOperationAction(ISD::LOAD, MVT::i64, Custom);
95 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
96 setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
97 setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
99 setOperationAction(ISD::STORE, MVT::i1, Custom);
100 setOperationAction(ISD::STORE, MVT::i32, Custom);
101 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
102 setOperationAction(ISD::STORE, MVT::v4i32, Custom);
104 setOperationAction(ISD::SELECT, MVT::f32, Promote);
105 AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
106 setOperationAction(ISD::SELECT, MVT::i64, Custom);
107 setOperationAction(ISD::SELECT, MVT::f64, Promote);
108 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
110 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
111 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
112 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
113 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
115 setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
116 setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
118 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
119 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
120 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
124 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
128 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
130 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
132 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
134 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
135 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
136 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
137 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
139 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
140 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
142 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
143 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
144 setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
145 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
146 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
147 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
149 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
150 setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
151 setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
152 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
154 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
155 setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
156 setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
157 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
158 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
160 setTruncStoreAction(MVT::i32, MVT::i8, Custom);
161 setTruncStoreAction(MVT::i32, MVT::i16, Custom);
162 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
163 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
164 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
165 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167 setOperationAction(ISD::LOAD, MVT::i1, Custom);
169 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
170 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
171 setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
173 // These should use UDIVREM, so set them to expand
174 setOperationAction(ISD::UDIV, MVT::i64, Expand);
175 setOperationAction(ISD::UREM, MVT::i64, Expand);
177 // We only support LOAD/STORE and vector manipulation ops for vectors
178 // with > 4 elements.
180 MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
183 for (MVT VT : VecTypes) {
184 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
188 case ISD::BUILD_VECTOR:
190 case ISD::EXTRACT_VECTOR_ELT:
191 case ISD::INSERT_VECTOR_ELT:
192 case ISD::CONCAT_VECTORS:
193 case ISD::INSERT_SUBVECTOR:
194 case ISD::EXTRACT_SUBVECTOR:
197 setOperationAction(Op, VT, Expand);
203 for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
204 MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
205 setOperationAction(ISD::FTRUNC, VT, Expand);
206 setOperationAction(ISD::FCEIL, VT, Expand);
207 setOperationAction(ISD::FFLOOR, VT, Expand);
210 if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
211 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
212 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
213 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
214 setOperationAction(ISD::FRINT, MVT::f64, Legal);
217 // FIXME: These should be removed and handled the same was as f32 fneg. Source
218 // modifiers also work for the double instructions.
219 setOperationAction(ISD::FNEG, MVT::f64, Expand);
220 setOperationAction(ISD::FABS, MVT::f64, Expand);
222 setTargetDAGCombine(ISD::SELECT_CC);
223 setTargetDAGCombine(ISD::SETCC);
225 setTargetDAGCombine(ISD::UINT_TO_FP);
227 setSchedulingPreference(Sched::RegPressure);
230 //===----------------------------------------------------------------------===//
231 // TargetLowering queries
232 //===----------------------------------------------------------------------===//
234 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
236 bool *IsFast) const {
240 // XXX: This depends on the address space and also we may want to revist
241 // the alignment values we specify in the DataLayout.
243 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
244 // which isn't a simple VT.
245 if (!VT.isSimple() || VT == MVT::Other)
248 // XXX - CI changes say "Support for unaligned memory accesses" but I don't
249 // see what for specifically. The wording everywhere else seems to be the
252 // 3.6.4 - Operations using pairs of VGPRs (for example: double-floats) have
253 // no alignment restrictions.
254 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
255 // Using any pair of GPRs should be the same as any other pair.
258 return VT.bitsGE(MVT::i64);
261 // XXX - The only mention I see of this in the ISA manual is for LDS direct
262 // reads the "byte address and must be dword aligned". Is it also true for the
263 // normal loads and stores?
264 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS)
267 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
268 // byte-address are ignored, thus forcing Dword alignment.
271 return VT.bitsGT(MVT::i32);
274 bool SITargetLowering::shouldSplitVectorType(EVT VT) const {
275 return VT.getScalarType().bitsLE(MVT::i16);
278 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
280 const SIInstrInfo *TII =
281 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
282 return TII->isInlineConstant(Imm);
285 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
286 SDLoc DL, SDValue Chain,
287 unsigned Offset, bool Signed) const {
288 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
289 PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
290 AMDGPUAS::CONSTANT_ADDRESS);
291 SDValue BasePtr = DAG.getCopyFromReg(Chain, DL,
292 MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
293 SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
294 DAG.getConstant(Offset, MVT::i64));
295 return DAG.getExtLoad(Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
296 MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
297 false, false, MemVT.getSizeInBits() >> 3);
301 SDValue SITargetLowering::LowerFormalArguments(
303 CallingConv::ID CallConv,
305 const SmallVectorImpl<ISD::InputArg> &Ins,
306 SDLoc DL, SelectionDAG &DAG,
307 SmallVectorImpl<SDValue> &InVals) const {
309 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
311 MachineFunction &MF = DAG.getMachineFunction();
312 FunctionType *FType = MF.getFunction()->getFunctionType();
313 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
315 assert(CallConv == CallingConv::C);
317 SmallVector<ISD::InputArg, 16> Splits;
318 uint32_t Skipped = 0;
320 for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
321 const ISD::InputArg &Arg = Ins[i];
323 // First check if it's a PS input addr
324 if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
325 !Arg.Flags.isByVal()) {
327 assert((PSInputNum <= 15) && "Too many PS inputs!");
330 // We can savely skip PS inputs
336 Info->PSInputAddr |= 1 << PSInputNum++;
339 // Second split vertices into their elements
340 if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
341 ISD::InputArg NewArg = Arg;
342 NewArg.Flags.setSplit();
343 NewArg.VT = Arg.VT.getVectorElementType();
345 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
346 // three or five element vertex only needs three or five registers,
347 // NOT four or eigth.
348 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
349 unsigned NumElements = ParamType->getVectorNumElements();
351 for (unsigned j = 0; j != NumElements; ++j) {
352 Splits.push_back(NewArg);
353 NewArg.PartOffset += NewArg.VT.getStoreSize();
356 } else if (Info->ShaderType != ShaderType::COMPUTE) {
357 Splits.push_back(Arg);
361 SmallVector<CCValAssign, 16> ArgLocs;
362 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
363 getTargetMachine(), ArgLocs, *DAG.getContext());
365 // At least one interpolation mode must be enabled or else the GPU will hang.
366 if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
367 Info->PSInputAddr |= 1;
368 CCInfo.AllocateReg(AMDGPU::VGPR0);
369 CCInfo.AllocateReg(AMDGPU::VGPR1);
372 // The pointer to the list of arguments is stored in SGPR0, SGPR1
373 if (Info->ShaderType == ShaderType::COMPUTE) {
374 CCInfo.AllocateReg(AMDGPU::SGPR0);
375 CCInfo.AllocateReg(AMDGPU::SGPR1);
376 MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
379 if (Info->ShaderType == ShaderType::COMPUTE) {
380 getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
384 AnalyzeFormalArguments(CCInfo, Splits);
386 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
388 const ISD::InputArg &Arg = Ins[i];
389 if (Skipped & (1 << i)) {
390 InVals.push_back(DAG.getUNDEF(Arg.VT));
394 CCValAssign &VA = ArgLocs[ArgIdx++];
395 EVT VT = VA.getLocVT();
399 EVT MemVT = Splits[i].VT;
400 // The first 36 bytes of the input buffer contains information about
401 // thread group and global sizes.
402 SDValue Arg = LowerParameter(DAG, VT, MemVT, DL, DAG.getRoot(),
403 36 + VA.getLocMemOffset(),
404 Ins[i].Flags.isSExt());
405 InVals.push_back(Arg);
408 assert(VA.isRegLoc() && "Parameter must be in a register!");
410 unsigned Reg = VA.getLocReg();
412 if (VT == MVT::i64) {
413 // For now assume it is a pointer
414 Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
415 &AMDGPU::SReg_64RegClass);
416 Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
417 InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
421 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
423 Reg = MF.addLiveIn(Reg, RC);
424 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
426 if (Arg.VT.isVector()) {
428 // Build a vector from the registers
429 Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
430 unsigned NumElements = ParamType->getVectorNumElements();
432 SmallVector<SDValue, 4> Regs;
434 for (unsigned j = 1; j != NumElements; ++j) {
435 Reg = ArgLocs[ArgIdx++].getLocReg();
436 Reg = MF.addLiveIn(Reg, RC);
437 Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
440 // Fill up the missing vector elements
441 NumElements = Arg.VT.getVectorNumElements() - NumElements;
442 for (unsigned j = 0; j != NumElements; ++j)
443 Regs.push_back(DAG.getUNDEF(VT));
445 InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
449 InVals.push_back(Val);
454 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
455 MachineInstr * MI, MachineBasicBlock * BB) const {
457 MachineBasicBlock::iterator I = *MI;
458 const SIInstrInfo *TII =
459 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
460 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
462 switch (MI->getOpcode()) {
464 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
465 case AMDGPU::BRANCH: return BB;
466 case AMDGPU::SI_ADDR64_RSRC: {
467 unsigned SuperReg = MI->getOperand(0).getReg();
468 unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
469 unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
470 unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
471 unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
472 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
473 .addOperand(MI->getOperand(1));
474 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
476 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
477 .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
478 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
480 .addImm(AMDGPU::sub0)
482 .addImm(AMDGPU::sub1);
483 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
485 .addImm(AMDGPU::sub0_sub1)
487 .addImm(AMDGPU::sub2_sub3);
488 MI->eraseFromParent();
491 case AMDGPU::V_SUB_F64: {
492 unsigned DestReg = MI->getOperand(0).getReg();
493 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
494 .addImm(0) // SRC0 modifiers
495 .addReg(MI->getOperand(1).getReg())
496 .addImm(1) // SRC1 modifiers
497 .addReg(MI->getOperand(2).getReg())
498 .addImm(0) // SRC2 modifiers
502 MI->eraseFromParent();
505 case AMDGPU::SI_RegisterStorePseudo: {
506 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
507 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
508 MachineInstrBuilder MIB =
509 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
511 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
512 MIB.addOperand(MI->getOperand(i));
514 MI->eraseFromParent();
517 case AMDGPU::FABS_SI: {
518 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
519 const SIInstrInfo *TII =
520 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
521 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
522 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
525 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_AND_B32_e32),
526 MI->getOperand(0).getReg())
527 .addReg(MI->getOperand(1).getReg())
529 MI->eraseFromParent();
532 case AMDGPU::FNEG_SI: {
533 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
534 const SIInstrInfo *TII =
535 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
536 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
537 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
540 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_XOR_B32_e32),
541 MI->getOperand(0).getReg())
542 .addReg(MI->getOperand(1).getReg())
544 MI->eraseFromParent();
547 case AMDGPU::FCLAMP_SI: {
548 const SIInstrInfo *TII =
549 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
550 BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F32_e64),
551 MI->getOperand(0).getReg())
552 .addImm(0) // SRC0 modifiers
553 .addOperand(MI->getOperand(1))
554 .addImm(0) // SRC1 modifiers
558 MI->eraseFromParent();
564 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
565 if (!VT.isVector()) {
568 return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
571 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
575 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
576 VT = VT.getScalarType();
581 switch (VT.getSimpleVT().SimpleTy) {
583 return false; /* There is V_MAD_F32 for f32 */
593 //===----------------------------------------------------------------------===//
594 // Custom DAG Lowering Operations
595 //===----------------------------------------------------------------------===//
597 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
598 MachineFunction &MF = DAG.getMachineFunction();
599 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
600 switch (Op.getOpcode()) {
601 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
602 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
604 LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
605 if (Op.getValueType().isVector() &&
606 (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
607 Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
608 (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
609 Op.getValueType().getVectorNumElements() > 4))) {
610 SDValue MergedValues[2] = {
611 SplitVectorLoad(Op, DAG),
614 return DAG.getMergeValues(MergedValues, SDLoc(Op));
616 return LowerLOAD(Op, DAG);
620 case ISD::SELECT: return LowerSELECT(Op, DAG);
621 case ISD::STORE: return LowerSTORE(Op, DAG);
622 case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
623 case ISD::INTRINSIC_WO_CHAIN: {
624 unsigned IntrinsicID =
625 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
626 EVT VT = Op.getValueType();
628 //XXX: Hardcoded we only use two to store the pointer to the parameters.
629 unsigned NumUserSGPRs = 2;
630 switch (IntrinsicID) {
631 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
632 case Intrinsic::r600_read_ngroups_x:
633 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
634 case Intrinsic::r600_read_ngroups_y:
635 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
636 case Intrinsic::r600_read_ngroups_z:
637 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
638 case Intrinsic::r600_read_global_size_x:
639 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
640 case Intrinsic::r600_read_global_size_y:
641 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
642 case Intrinsic::r600_read_global_size_z:
643 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
644 case Intrinsic::r600_read_local_size_x:
645 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
646 case Intrinsic::r600_read_local_size_y:
647 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
648 case Intrinsic::r600_read_local_size_z:
649 return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
650 case Intrinsic::r600_read_tgid_x:
651 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
652 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
653 case Intrinsic::r600_read_tgid_y:
654 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
655 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
656 case Intrinsic::r600_read_tgid_z:
657 return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
658 AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
659 case Intrinsic::r600_read_tidig_x:
660 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
662 case Intrinsic::r600_read_tidig_y:
663 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
665 case Intrinsic::r600_read_tidig_z:
666 return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
668 case AMDGPUIntrinsic::SI_load_const: {
674 MachineMemOperand *MMO = MF.getMachineMemOperand(
675 MachinePointerInfo(),
676 MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
677 VT.getSizeInBits() / 8, 4);
678 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
679 Op->getVTList(), Ops, VT, MMO);
681 case AMDGPUIntrinsic::SI_sample:
682 return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
683 case AMDGPUIntrinsic::SI_sampleb:
684 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
685 case AMDGPUIntrinsic::SI_sampled:
686 return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
687 case AMDGPUIntrinsic::SI_samplel:
688 return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
689 case AMDGPUIntrinsic::SI_vs_load_input:
690 return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
697 case ISD::INTRINSIC_VOID:
698 SDValue Chain = Op.getOperand(0);
699 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
701 switch (IntrinsicID) {
702 case AMDGPUIntrinsic::SI_tbuffer_store: {
720 EVT VT = Op.getOperand(3).getValueType();
722 MachineMemOperand *MMO = MF.getMachineMemOperand(
723 MachinePointerInfo(),
724 MachineMemOperand::MOStore,
725 VT.getSizeInBits() / 8, 4);
726 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
727 Op->getVTList(), Ops, VT, MMO);
736 /// \brief Helper function for LowerBRCOND
737 static SDNode *findUser(SDValue Value, unsigned Opcode) {
739 SDNode *Parent = Value.getNode();
740 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
743 if (I.getUse().get() != Value)
746 if (I->getOpcode() == Opcode)
752 /// This transforms the control flow intrinsics to get the branch destination as
753 /// last parameter, also switches branch target with BR if the need arise
754 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
755 SelectionDAG &DAG) const {
759 SDNode *Intr = BRCOND.getOperand(1).getNode();
760 SDValue Target = BRCOND.getOperand(2);
761 SDNode *BR = nullptr;
763 if (Intr->getOpcode() == ISD::SETCC) {
764 // As long as we negate the condition everything is fine
765 SDNode *SetCC = Intr;
766 assert(SetCC->getConstantOperandVal(1) == 1);
767 assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
769 Intr = SetCC->getOperand(0).getNode();
772 // Get the target from BR if we don't negate the condition
773 BR = findUser(BRCOND, ISD::BR);
774 Target = BR->getOperand(1);
777 assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
779 // Build the result and
780 SmallVector<EVT, 4> Res;
781 for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
782 Res.push_back(Intr->getValueType(i));
784 // operands of the new intrinsic call
785 SmallVector<SDValue, 4> Ops;
786 Ops.push_back(BRCOND.getOperand(0));
787 for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
788 Ops.push_back(Intr->getOperand(i));
789 Ops.push_back(Target);
791 // build the new intrinsic call
792 SDNode *Result = DAG.getNode(
793 Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
794 DAG.getVTList(Res), Ops).getNode();
797 // Give the branch instruction our target
802 DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops);
805 SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
807 // Copy the intrinsic results to registers
808 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
809 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
813 Chain = DAG.getCopyToReg(
815 CopyToReg->getOperand(1),
816 SDValue(Result, i - 1),
819 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
822 // Remove the old intrinsic from the chain
823 DAG.ReplaceAllUsesOfValueWith(
824 SDValue(Intr, Intr->getNumValues() - 1),
825 Intr->getOperand(0));
830 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
832 LoadSDNode *Load = cast<LoadSDNode>(Op);
833 SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
834 SDValue MergedValues[2];
835 MergedValues[1] = Load->getChain();
837 MergedValues[0] = Ret;
838 return DAG.getMergeValues(MergedValues, DL);
841 if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
845 EVT MemVT = Load->getMemoryVT();
847 assert(!MemVT.isVector() && "Private loads should be scalarized");
848 assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
850 SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
851 DAG.getConstant(2, MVT::i32));
852 Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
853 Load->getChain(), Ptr,
854 DAG.getTargetConstant(0, MVT::i32),
856 if (MemVT.getSizeInBits() == 64) {
857 SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
858 DAG.getConstant(1, MVT::i32));
860 SDValue LoadUpper = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
861 Load->getChain(), IncPtr,
862 DAG.getTargetConstant(0, MVT::i32),
865 Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ret, LoadUpper);
868 MergedValues[0] = Ret;
869 return DAG.getMergeValues(MergedValues, DL);
873 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
875 SelectionDAG &DAG) const {
876 return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
882 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
883 if (Op.getValueType() != MVT::i64)
887 SDValue Cond = Op.getOperand(0);
889 SDValue Zero = DAG.getConstant(0, MVT::i32);
890 SDValue One = DAG.getConstant(1, MVT::i32);
892 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
893 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
895 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
896 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
898 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
900 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
901 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
903 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
905 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
906 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
909 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
911 StoreSDNode *Store = cast<StoreSDNode>(Op);
912 EVT VT = Store->getMemoryVT();
914 // These stores are legal.
915 if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
916 VT.isVector() && VT.getVectorNumElements() == 2 &&
917 VT.getVectorElementType() == MVT::i32)
920 SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
924 if (VT.isVector() && VT.getVectorNumElements() >= 8)
925 return SplitVectorStore(Op, DAG);
928 return DAG.getTruncStore(Store->getChain(), DL,
929 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
930 Store->getBasePtr(), MVT::i1, Store->getMemOperand());
932 if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
935 SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
936 DAG.getConstant(2, MVT::i32));
937 SDValue Chain = Store->getChain();
938 SmallVector<SDValue, 8> Values;
940 if (Store->isTruncatingStore()) {
942 if (Store->getMemoryVT() == MVT::i8) {
944 } else if (Store->getMemoryVT() == MVT::i16) {
947 SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
948 Chain, Store->getBasePtr(),
949 DAG.getConstant(0, MVT::i32));
950 SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
951 DAG.getConstant(0x3, MVT::i32));
952 SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
953 DAG.getConstant(3, MVT::i32));
954 SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
955 DAG.getConstant(Mask, MVT::i32));
956 SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
957 MaskedValue, ShiftAmt);
958 SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
959 DAG.getConstant(32, MVT::i32), ShiftAmt);
960 SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
961 DAG.getConstant(Mask, MVT::i32),
963 Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
964 Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
966 Values.push_back(Dst);
967 } else if (VT == MVT::i64) {
968 for (unsigned i = 0; i < 2; ++i) {
969 Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
970 Store->getValue(), DAG.getConstant(i, MVT::i32)));
972 } else if (VT == MVT::i128) {
973 for (unsigned i = 0; i < 2; ++i) {
974 for (unsigned j = 0; j < 2; ++j) {
975 Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
976 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
977 Store->getValue(), DAG.getConstant(i, MVT::i32)),
978 DAG.getConstant(j, MVT::i32)));
982 Values.push_back(Store->getValue());
985 for (unsigned i = 0; i < Values.size(); ++i) {
986 SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
987 Ptr, DAG.getConstant(i, MVT::i32));
988 Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
989 Chain, Values[i], PartPtr,
990 DAG.getTargetConstant(0, MVT::i32));
995 //===----------------------------------------------------------------------===//
996 // Custom DAG optimizations
997 //===----------------------------------------------------------------------===//
999 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1000 DAGCombinerInfo &DCI) {
1001 EVT VT = N->getValueType(0);
1002 EVT ScalarVT = VT.getScalarType();
1003 if (ScalarVT != MVT::f32)
1006 SelectionDAG &DAG = DCI.DAG;
1009 SDValue Src = N->getOperand(0);
1010 EVT SrcVT = Src.getValueType();
1012 // TODO: We could try to match extracting the higher bytes, which would be
1013 // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1014 // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1015 // about in practice.
1016 if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1017 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1018 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1019 DCI.AddToWorklist(Cvt.getNode());
1024 // We are primarily trying to catch operations on illegal vector types
1025 // before they are expanded.
1026 // For scalars, we can use the more flexible method of checking masked bits
1027 // after legalization.
1028 if (!DCI.isBeforeLegalize() ||
1029 !SrcVT.isVector() ||
1030 SrcVT.getVectorElementType() != MVT::i8) {
1034 assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1036 // Weird sized vectors are a pain to handle, but we know 3 is really the same
1038 unsigned NElts = SrcVT.getVectorNumElements();
1039 if (!SrcVT.isSimple() && NElts != 3)
1042 // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1043 // prevent a mess from expanding to v4i32 and repacking.
1044 if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1045 EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1046 EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1047 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1049 LoadSDNode *Load = cast<LoadSDNode>(Src);
1050 SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1054 Load->getMemOperand());
1056 // Make sure successors of the original load stay after it by updating
1057 // them to use the new Chain.
1058 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1060 SmallVector<SDValue, 4> Elts;
1061 if (RegVT.isVector())
1062 DAG.ExtractVectorElements(NewLoad, Elts);
1064 Elts.push_back(NewLoad);
1066 SmallVector<SDValue, 4> Ops;
1068 unsigned EltIdx = 0;
1069 for (SDValue Elt : Elts) {
1070 unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1071 for (unsigned I = 0; I < ComponentsInElt; ++I) {
1072 unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1073 SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1074 DCI.AddToWorklist(Cvt.getNode());
1081 assert(Ops.size() == NElts);
1083 return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1089 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1090 DAGCombinerInfo &DCI) const {
1091 SelectionDAG &DAG = DCI.DAG;
1093 EVT VT = N->getValueType(0);
1095 switch (N->getOpcode()) {
1096 default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1097 case ISD::SELECT_CC: {
1098 ConstantSDNode *True, *False;
1099 // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
1100 if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1101 && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1102 && True->isAllOnesValue()
1103 && False->isNullValue()
1105 return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
1106 N->getOperand(1), N->getOperand(4));
1112 SDValue Arg0 = N->getOperand(0);
1113 SDValue Arg1 = N->getOperand(1);
1114 SDValue CC = N->getOperand(2);
1115 ConstantSDNode * C = nullptr;
1116 ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1118 // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1120 && Arg0.getOpcode() == ISD::SIGN_EXTEND
1121 && Arg0.getOperand(0).getValueType() == MVT::i1
1122 && (C = dyn_cast<ConstantSDNode>(Arg1))
1124 && CCOp == ISD::SETNE) {
1125 return SimplifySetCC(VT, Arg0.getOperand(0),
1126 DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1131 case AMDGPUISD::CVT_F32_UBYTE0:
1132 case AMDGPUISD::CVT_F32_UBYTE1:
1133 case AMDGPUISD::CVT_F32_UBYTE2:
1134 case AMDGPUISD::CVT_F32_UBYTE3: {
1135 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1137 SDValue Src = N->getOperand(0);
1138 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1140 APInt KnownZero, KnownOne;
1141 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1142 !DCI.isBeforeLegalizeOps());
1143 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1144 if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1145 TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1146 DCI.CommitTargetLoweringOpt(TLO);
1152 case ISD::UINT_TO_FP: {
1153 return performUCharToFloatCombine(N, DCI);
1157 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1160 /// \brief Test if RegClass is one of the VSrc classes
1161 static bool isVSrc(unsigned RegClass) {
1162 return AMDGPU::VSrc_32RegClassID == RegClass ||
1163 AMDGPU::VSrc_64RegClassID == RegClass;
1166 /// \brief Test if RegClass is one of the SSrc classes
1167 static bool isSSrc(unsigned RegClass) {
1168 return AMDGPU::SSrc_32RegClassID == RegClass ||
1169 AMDGPU::SSrc_64RegClassID == RegClass;
1172 /// \brief Analyze the possible immediate value Op
1174 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1175 /// and the immediate value if it's a literal immediate
1176 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1183 if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1184 if (Node->getZExtValue() >> 32) {
1187 Imm.I = Node->getSExtValue();
1188 } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1189 if (N->getValueType(0) != MVT::f32)
1191 Imm.F = Node->getValueAPF().convertToFloat();
1193 return -1; // It isn't an immediate
1195 if ((Imm.I >= -16 && Imm.I <= 64) ||
1196 Imm.F == 0.5f || Imm.F == -0.5f ||
1197 Imm.F == 1.0f || Imm.F == -1.0f ||
1198 Imm.F == 2.0f || Imm.F == -2.0f ||
1199 Imm.F == 4.0f || Imm.F == -4.0f)
1200 return 0; // It's an inline immediate
1202 return Imm.I; // It's a literal immediate
1205 /// \brief Try to fold an immediate directly into an instruction
1206 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1207 bool &ScalarSlotUsed) const {
1209 MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1210 const SIInstrInfo *TII =
1211 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1212 if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1215 const SDValue &Op = Mov->getOperand(0);
1216 int32_t Value = analyzeImmediate(Op.getNode());
1218 // Not an immediate at all
1221 } else if (Value == 0) {
1222 // Inline immediates can always be fold
1226 } else if (Value == Immediate) {
1227 // Already fold literal immediate
1231 } else if (!ScalarSlotUsed && !Immediate) {
1232 // Fold this literal immediate
1233 ScalarSlotUsed = true;
1243 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1244 SelectionDAG &DAG, const SDValue &Op) const {
1245 const SIInstrInfo *TII =
1246 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1247 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1249 if (!Op->isMachineOpcode()) {
1250 switch(Op->getOpcode()) {
1251 case ISD::CopyFromReg: {
1252 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1253 unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1254 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1255 return MRI.getRegClass(Reg);
1257 return TRI.getPhysRegClass(Reg);
1259 default: return nullptr;
1262 const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1263 int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1264 if (OpClassID != -1) {
1265 return TRI.getRegClass(OpClassID);
1267 switch(Op.getMachineOpcode()) {
1268 case AMDGPU::COPY_TO_REGCLASS:
1269 // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1270 OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1272 // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1273 // class, then the register class for the value could be either a
1274 // VReg or and SReg. In order to get a more accurate
1275 if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1276 OpClassID == AMDGPU::VSrc_64RegClassID) {
1277 return getRegClassForNode(DAG, Op.getOperand(0));
1279 return TRI.getRegClass(OpClassID);
1280 case AMDGPU::EXTRACT_SUBREG: {
1281 int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1282 const TargetRegisterClass *SuperClass =
1283 getRegClassForNode(DAG, Op.getOperand(0));
1284 return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1286 case AMDGPU::REG_SEQUENCE:
1287 // Operand 0 is the register class id for REG_SEQUENCE instructions.
1288 return TRI.getRegClass(
1289 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1291 return getRegClassFor(Op.getSimpleValueType());
1295 /// \brief Does "Op" fit into register class "RegClass" ?
1296 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1297 unsigned RegClass) const {
1298 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1299 const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1303 return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1306 /// \brief Make sure that we don't exeed the number of allowed scalars
1307 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1309 bool &ScalarSlotUsed) const {
1311 // First map the operands register class to a destination class
1312 if (RegClass == AMDGPU::VSrc_32RegClassID)
1313 RegClass = AMDGPU::VReg_32RegClassID;
1314 else if (RegClass == AMDGPU::VSrc_64RegClassID)
1315 RegClass = AMDGPU::VReg_64RegClassID;
1319 // Nothing to do if they fit naturally
1320 if (fitsRegClass(DAG, Operand, RegClass))
1323 // If the scalar slot isn't used yet use it now
1324 if (!ScalarSlotUsed) {
1325 ScalarSlotUsed = true;
1329 // This is a conservative aproach. It is possible that we can't determine the
1330 // correct register class and copy too often, but better safe than sorry.
1331 SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1332 SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1333 Operand.getValueType(), Operand, RC);
1334 Operand = SDValue(Node, 0);
1337 /// \returns true if \p Node's operands are different from the SDValue list
1339 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1340 for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1341 if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1348 /// \brief Try to fold the Nodes operands into the Node
1349 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1350 SelectionDAG &DAG) const {
1352 // Original encoding (either e32 or e64)
1353 int Opcode = Node->getMachineOpcode();
1354 const SIInstrInfo *TII =
1355 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1356 const MCInstrDesc *Desc = &TII->get(Opcode);
1358 unsigned NumDefs = Desc->getNumDefs();
1359 unsigned NumOps = Desc->getNumOperands();
1361 // Commuted opcode if available
1362 int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1363 const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1365 assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1366 assert(!DescRev || DescRev->getNumOperands() == NumOps);
1368 // e64 version if available, -1 otherwise
1369 int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1370 const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1371 int InputModifiers[3] = {0};
1373 assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1375 int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1376 bool HaveVSrc = false, HaveSSrc = false;
1378 // First figure out what we already have in this instruction.
1379 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1380 i != e && Op < NumOps; ++i, ++Op) {
1382 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1383 if (isVSrc(RegClass))
1385 else if (isSSrc(RegClass))
1390 int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1391 if (Imm != -1 && Imm != 0) {
1392 // Literal immediate
1397 // If we neither have VSrc nor SSrc, it makes no sense to continue.
1398 if (!HaveVSrc && !HaveSSrc)
1401 // No scalar allowed when we have both VSrc and SSrc
1402 bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1404 // Second go over the operands and try to fold them
1405 std::vector<SDValue> Ops;
1406 bool Promote2e64 = false;
1407 for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1408 i != e && Op < NumOps; ++i, ++Op) {
1410 const SDValue &Operand = Node->getOperand(i);
1411 Ops.push_back(Operand);
1413 // Already folded immediate?
1414 if (isa<ConstantSDNode>(Operand.getNode()) ||
1415 isa<ConstantFPSDNode>(Operand.getNode()))
1418 // Is this a VSrc or SSrc operand?
1419 unsigned RegClass = Desc->OpInfo[Op].RegClass;
1420 if (isVSrc(RegClass) || isSSrc(RegClass)) {
1421 // Try to fold the immediates
1422 if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1423 // Folding didn't work, make sure we don't hit the SReg limit.
1424 ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1429 if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1431 unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1432 assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1434 // Test if it makes sense to swap operands
1435 if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1436 (!fitsRegClass(DAG, Ops[1], RegClass) &&
1437 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1439 // Swap commutable operands
1440 std::swap(Ops[0], Ops[1]);
1452 // Test if it makes sense to switch to e64 encoding
1453 unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1454 if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1457 int32_t TmpImm = -1;
1458 if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1459 (!fitsRegClass(DAG, Ops[i], RegClass) &&
1460 fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1462 // Switch to e64 encoding
1470 if (!DescE64 && !Promote2e64)
1472 if (!Operand.isMachineOpcode())
1474 if (Operand.getMachineOpcode() == AMDGPU::FNEG_SI) {
1476 Ops.push_back(Operand.getOperand(0));
1477 InputModifiers[i] = 1;
1484 else if (Operand.getMachineOpcode() == AMDGPU::FABS_SI) {
1486 Ops.push_back(Operand.getOperand(0));
1487 InputModifiers[i] = 2;
1497 std::vector<SDValue> OldOps(Ops);
1499 for (unsigned i = 0; i < OldOps.size(); ++i) {
1501 Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1502 Ops.push_back(OldOps[i]);
1504 // Add the modifier flags while promoting
1505 for (unsigned i = 0; i < 2; ++i)
1506 Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1509 // Add optional chain and glue
1510 for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1511 Ops.push_back(Node->getOperand(i));
1513 // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1514 // this case a brand new node is always be created, even if the operands
1515 // are the same as before. So, manually check if anything has been changed.
1516 if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1520 // Create a complete new instruction
1521 return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1524 /// \brief Helper function for adjustWritemask
1525 static unsigned SubIdx2Lane(unsigned Idx) {
1528 case AMDGPU::sub0: return 0;
1529 case AMDGPU::sub1: return 1;
1530 case AMDGPU::sub2: return 2;
1531 case AMDGPU::sub3: return 3;
1535 /// \brief Adjust the writemask of MIMG instructions
1536 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1537 SelectionDAG &DAG) const {
1538 SDNode *Users[4] = { };
1540 unsigned OldDmask = Node->getConstantOperandVal(0);
1541 unsigned NewDmask = 0;
1543 // Try to figure out the used register components
1544 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1547 // Abort if we can't understand the usage
1548 if (!I->isMachineOpcode() ||
1549 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1552 // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1553 // Note that subregs are packed, i.e. Lane==0 is the first bit set
1554 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1556 Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1558 // Set which texture component corresponds to the lane.
1560 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1562 Comp = countTrailingZeros(Dmask);
1563 Dmask &= ~(1 << Comp);
1566 // Abort if we have more than one user per component
1571 NewDmask |= 1 << Comp;
1574 // Abort if there's no change
1575 if (NewDmask == OldDmask)
1578 // Adjust the writemask in the node
1579 std::vector<SDValue> Ops;
1580 Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1581 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1582 Ops.push_back(Node->getOperand(i));
1583 Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1585 // If we only got one lane, replace it with a copy
1586 // (if NewDmask has only one bit set...)
1587 if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1588 SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1589 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1590 SDLoc(), Users[Lane]->getValueType(0),
1591 SDValue(Node, 0), RC);
1592 DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1596 // Update the users of the node with the new indices
1597 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1599 SDNode *User = Users[i];
1603 SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1604 DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1608 case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1609 case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1610 case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1615 /// \brief Fold the instructions after selecting them.
1616 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1617 SelectionDAG &DAG) const {
1618 const SIInstrInfo *TII =
1619 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1620 Node = AdjustRegClass(Node, DAG);
1622 if (TII->isMIMG(Node->getMachineOpcode()))
1623 adjustWritemask(Node, DAG);
1625 return foldOperands(Node, DAG);
1628 /// \brief Assign the register class depending on the number of
1629 /// bits set in the writemask
1630 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1631 SDNode *Node) const {
1632 const SIInstrInfo *TII =
1633 static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1634 if (!TII->isMIMG(MI->getOpcode()))
1637 unsigned VReg = MI->getOperand(0).getReg();
1638 unsigned Writemask = MI->getOperand(1).getImm();
1639 unsigned BitsSet = 0;
1640 for (unsigned i = 0; i < 4; ++i)
1641 BitsSet += Writemask & (1 << i) ? 1 : 0;
1643 const TargetRegisterClass *RC;
1646 case 1: RC = &AMDGPU::VReg_32RegClass; break;
1647 case 2: RC = &AMDGPU::VReg_64RegClass; break;
1648 case 3: RC = &AMDGPU::VReg_96RegClass; break;
1651 unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1652 MI->setDesc(TII->get(NewOpcode));
1653 MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1654 MRI.setRegClass(VReg, RC);
1657 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1658 SelectionDAG &DAG) const {
1661 unsigned NewOpcode = N->getMachineOpcode();
1663 switch (N->getMachineOpcode()) {
1665 case AMDGPU::S_LOAD_DWORD_IMM:
1666 NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1668 case AMDGPU::S_LOAD_DWORDX2_SGPR:
1669 if (NewOpcode == N->getMachineOpcode()) {
1670 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1673 case AMDGPU::S_LOAD_DWORDX4_IMM:
1674 case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1675 if (NewOpcode == N->getMachineOpcode()) {
1676 NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1678 if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1681 ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1683 SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1684 DAG.getConstant(0, MVT::i64)), 0),
1686 DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1688 return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1693 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1694 const TargetRegisterClass *RC,
1695 unsigned Reg, EVT VT) const {
1696 SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1698 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1699 cast<RegisterSDNode>(VReg)->getReg(), VT);