R600: Consolidate expansion of v2i32/v4i32 ops for EG/SI
[oota-llvm.git] / lib / Target / R600 / SIISelLowering.cpp
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SIISelLowering.h"
16 #include "AMDGPU.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"
26
27 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
28
29 using namespace llvm;
30
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32     AMDGPUTargetLowering(TM) {
33
34   addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
35   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
36
37   addRegisterClass(MVT::v16i8, &AMDGPU::SReg_128RegClass);
38   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
39   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
40
41   addRegisterClass(MVT::i32, &AMDGPU::VReg_32RegClass);
42   addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
43
44   addRegisterClass(MVT::v1i32, &AMDGPU::VReg_32RegClass);
45
46   addRegisterClass(MVT::v2i32, &AMDGPU::VReg_64RegClass);
47   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
48
49   addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
50   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
51   addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
52
53   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
54   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
55
56   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
57   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
58
59   computeRegisterProperties();
60
61   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
62   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
63   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
64   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
65
66   setOperationAction(ISD::ADD, MVT::i64, Legal);
67   setOperationAction(ISD::ADD, MVT::i32, Legal);
68
69   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
70   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
71
72   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
73
74   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
75
76   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
77
78   setTargetDAGCombine(ISD::SELECT_CC);
79
80   setTargetDAGCombine(ISD::SETCC);
81
82   setSchedulingPreference(Sched::RegPressure);
83 }
84
85 //===----------------------------------------------------------------------===//
86 // TargetLowering queries
87 //===----------------------------------------------------------------------===//
88
89 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
90                                                      bool *IsFast) const {
91   // XXX: This depends on the address space and also we may want to revist
92   // the alignment values we specify in the DataLayout.
93   return VT.bitsGT(MVT::i32);
94 }
95
96
97 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
98                                          SDLoc DL, SDValue Chain,
99                                          unsigned Offset) const {
100   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
101   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
102                                             AMDGPUAS::CONSTANT_ADDRESS);
103   EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
104   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
105                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
106   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
107                                              DAG.getConstant(Offset, MVT::i64));
108   return DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
109                             MachinePointerInfo(UndefValue::get(PtrTy)),
110                             VT, false, false, ArgVT.getSizeInBits() >> 3);
111
112 }
113
114 SDValue SITargetLowering::LowerFormalArguments(
115                                       SDValue Chain,
116                                       CallingConv::ID CallConv,
117                                       bool isVarArg,
118                                       const SmallVectorImpl<ISD::InputArg> &Ins,
119                                       SDLoc DL, SelectionDAG &DAG,
120                                       SmallVectorImpl<SDValue> &InVals) const {
121
122   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
123
124   MachineFunction &MF = DAG.getMachineFunction();
125   FunctionType *FType = MF.getFunction()->getFunctionType();
126   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
127
128   assert(CallConv == CallingConv::C);
129
130   SmallVector<ISD::InputArg, 16> Splits;
131   uint32_t Skipped = 0;
132
133   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
134     const ISD::InputArg &Arg = Ins[i];
135
136     // First check if it's a PS input addr
137     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
138
139       assert((PSInputNum <= 15) && "Too many PS inputs!");
140
141       if (!Arg.Used) {
142         // We can savely skip PS inputs
143         Skipped |= 1 << i;
144         ++PSInputNum;
145         continue;
146       }
147
148       Info->PSInputAddr |= 1 << PSInputNum++;
149     }
150
151     // Second split vertices into their elements
152     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
153       ISD::InputArg NewArg = Arg;
154       NewArg.Flags.setSplit();
155       NewArg.VT = Arg.VT.getVectorElementType();
156
157       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
158       // three or five element vertex only needs three or five registers,
159       // NOT four or eigth.
160       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
161       unsigned NumElements = ParamType->getVectorNumElements();
162
163       for (unsigned j = 0; j != NumElements; ++j) {
164         Splits.push_back(NewArg);
165         NewArg.PartOffset += NewArg.VT.getStoreSize();
166       }
167
168     } else {
169       Splits.push_back(Arg);
170     }
171   }
172
173   SmallVector<CCValAssign, 16> ArgLocs;
174   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
175                  getTargetMachine(), ArgLocs, *DAG.getContext());
176
177   // At least one interpolation mode must be enabled or else the GPU will hang.
178   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
179     Info->PSInputAddr |= 1;
180     CCInfo.AllocateReg(AMDGPU::VGPR0);
181     CCInfo.AllocateReg(AMDGPU::VGPR1);
182   }
183
184   // The pointer to the list of arguments is stored in SGPR0, SGPR1
185   if (Info->ShaderType == ShaderType::COMPUTE) {
186     CCInfo.AllocateReg(AMDGPU::SGPR0);
187     CCInfo.AllocateReg(AMDGPU::SGPR1);
188     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
189   }
190
191   AnalyzeFormalArguments(CCInfo, Splits);
192
193   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
194
195     const ISD::InputArg &Arg = Ins[i];
196     if (Skipped & (1 << i)) {
197       InVals.push_back(DAG.getUNDEF(Arg.VT));
198       continue;
199     }
200
201     CCValAssign &VA = ArgLocs[ArgIdx++];
202     EVT VT = VA.getLocVT();
203
204     if (VA.isMemLoc()) {
205       // The first 36 bytes of the input buffer contains information about
206       // thread group and global sizes.
207       SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
208                                    36 + VA.getLocMemOffset());
209       InVals.push_back(Arg);
210       continue;
211     }
212     assert(VA.isRegLoc() && "Parameter must be in a register!");
213
214     unsigned Reg = VA.getLocReg();
215
216     if (VT == MVT::i64) {
217       // For now assume it is a pointer
218       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
219                                      &AMDGPU::SReg_64RegClass);
220       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
221       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
222       continue;
223     }
224
225     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
226
227     Reg = MF.addLiveIn(Reg, RC);
228     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
229
230     if (Arg.VT.isVector()) {
231
232       // Build a vector from the registers
233       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
234       unsigned NumElements = ParamType->getVectorNumElements();
235
236       SmallVector<SDValue, 4> Regs;
237       Regs.push_back(Val);
238       for (unsigned j = 1; j != NumElements; ++j) {
239         Reg = ArgLocs[ArgIdx++].getLocReg();
240         Reg = MF.addLiveIn(Reg, RC);
241         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
242       }
243
244       // Fill up the missing vector elements
245       NumElements = Arg.VT.getVectorNumElements() - NumElements;
246       for (unsigned j = 0; j != NumElements; ++j)
247         Regs.push_back(DAG.getUNDEF(VT));
248
249       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
250                                    Regs.data(), Regs.size()));
251       continue;
252     }
253
254     InVals.push_back(Val);
255   }
256   return Chain;
257 }
258
259 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
260     MachineInstr * MI, MachineBasicBlock * BB) const {
261
262   MachineBasicBlock::iterator I = *MI;
263
264   switch (MI->getOpcode()) {
265   default:
266     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
267   case AMDGPU::BRANCH: return BB;
268   case AMDGPU::SI_ADDR64_RSRC: {
269     const SIInstrInfo *TII =
270       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
271     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
272     unsigned SuperReg = MI->getOperand(0).getReg();
273     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
274     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
275     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
276     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
277     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
278             .addOperand(MI->getOperand(1));
279     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
280             .addImm(0);
281     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
282             .addImm(RSRC_DATA_FORMAT >> 32);
283     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
284             .addReg(SubRegHiLo)
285             .addImm(AMDGPU::sub0)
286             .addReg(SubRegHiHi)
287             .addImm(AMDGPU::sub1);
288     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
289             .addReg(SubRegLo)
290             .addImm(AMDGPU::sub0_sub1)
291             .addReg(SubRegHi)
292             .addImm(AMDGPU::sub2_sub3);
293     MI->eraseFromParent();
294     break;
295   }
296   }
297   return BB;
298 }
299
300 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
301   return MVT::i1;
302 }
303
304 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
305   return MVT::i32;
306 }
307
308 //===----------------------------------------------------------------------===//
309 // Custom DAG Lowering Operations
310 //===----------------------------------------------------------------------===//
311
312 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
313   switch (Op.getOpcode()) {
314   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
315   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
316   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
317   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
318   case ISD::INTRINSIC_WO_CHAIN: {
319     unsigned IntrinsicID =
320                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
321     EVT VT = Op.getValueType();
322     SDLoc DL(Op);
323     //XXX: Hardcoded we only use two to store the pointer to the parameters.
324     unsigned NumUserSGPRs = 2;
325     switch (IntrinsicID) {
326     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
327     case Intrinsic::r600_read_ngroups_x:
328       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
329     case Intrinsic::r600_read_ngroups_y:
330       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
331     case Intrinsic::r600_read_ngroups_z:
332       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
333     case Intrinsic::r600_read_global_size_x:
334       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
335     case Intrinsic::r600_read_global_size_y:
336       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
337     case Intrinsic::r600_read_global_size_z:
338       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
339     case Intrinsic::r600_read_local_size_x:
340       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
341     case Intrinsic::r600_read_local_size_y:
342       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
343     case Intrinsic::r600_read_local_size_z:
344       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
345     case Intrinsic::r600_read_tgid_x:
346       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
347                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
348     case Intrinsic::r600_read_tgid_y:
349       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
350                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
351     case Intrinsic::r600_read_tgid_z:
352       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
353                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
354     case Intrinsic::r600_read_tidig_x:
355       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
356                                   AMDGPU::VGPR0, VT);
357     case Intrinsic::r600_read_tidig_y:
358       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
359                                   AMDGPU::VGPR1, VT);
360     case Intrinsic::r600_read_tidig_z:
361       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
362                                   AMDGPU::VGPR2, VT);
363
364     }
365   }
366   }
367   return SDValue();
368 }
369
370 /// \brief Helper function for LowerBRCOND
371 static SDNode *findUser(SDValue Value, unsigned Opcode) {
372
373   SDNode *Parent = Value.getNode();
374   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
375        I != E; ++I) {
376
377     if (I.getUse().get() != Value)
378       continue;
379
380     if (I->getOpcode() == Opcode)
381       return *I;
382   }
383   return 0;
384 }
385
386 /// This transforms the control flow intrinsics to get the branch destination as
387 /// last parameter, also switches branch target with BR if the need arise
388 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
389                                       SelectionDAG &DAG) const {
390
391   SDLoc DL(BRCOND);
392
393   SDNode *Intr = BRCOND.getOperand(1).getNode();
394   SDValue Target = BRCOND.getOperand(2);
395   SDNode *BR = 0;
396
397   if (Intr->getOpcode() == ISD::SETCC) {
398     // As long as we negate the condition everything is fine
399     SDNode *SetCC = Intr;
400     assert(SetCC->getConstantOperandVal(1) == 1);
401     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
402            ISD::SETNE);
403     Intr = SetCC->getOperand(0).getNode();
404
405   } else {
406     // Get the target from BR if we don't negate the condition
407     BR = findUser(BRCOND, ISD::BR);
408     Target = BR->getOperand(1);
409   }
410
411   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
412
413   // Build the result and
414   SmallVector<EVT, 4> Res;
415   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
416     Res.push_back(Intr->getValueType(i));
417
418   // operands of the new intrinsic call
419   SmallVector<SDValue, 4> Ops;
420   Ops.push_back(BRCOND.getOperand(0));
421   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
422     Ops.push_back(Intr->getOperand(i));
423   Ops.push_back(Target);
424
425   // build the new intrinsic call
426   SDNode *Result = DAG.getNode(
427     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
428     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
429
430   if (BR) {
431     // Give the branch instruction our target
432     SDValue Ops[] = {
433       BR->getOperand(0),
434       BRCOND.getOperand(2)
435     };
436     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
437   }
438
439   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
440
441   // Copy the intrinsic results to registers
442   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
443     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
444     if (!CopyToReg)
445       continue;
446
447     Chain = DAG.getCopyToReg(
448       Chain, DL,
449       CopyToReg->getOperand(1),
450       SDValue(Result, i - 1),
451       SDValue());
452
453     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
454   }
455
456   // Remove the old intrinsic from the chain
457   DAG.ReplaceAllUsesOfValueWith(
458     SDValue(Intr, Intr->getNumValues() - 1),
459     Intr->getOperand(0));
460
461   return Chain;
462 }
463
464 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
465   SDValue LHS = Op.getOperand(0);
466   SDValue RHS = Op.getOperand(1);
467   SDValue True = Op.getOperand(2);
468   SDValue False = Op.getOperand(3);
469   SDValue CC = Op.getOperand(4);
470   EVT VT = Op.getValueType();
471   SDLoc DL(Op);
472
473   // Possible Min/Max pattern
474   SDValue MinMax = LowerMinMax(Op, DAG);
475   if (MinMax.getNode()) {
476     return MinMax;
477   }
478
479   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
480   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
481 }
482
483 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
484                                            SelectionDAG &DAG) const {
485   EVT VT = Op.getValueType();
486   SDLoc DL(Op);
487
488   if (VT != MVT::i64) {
489     return SDValue();
490   }
491
492   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
493                                                  DAG.getConstant(31, MVT::i32));
494
495   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
496 }
497
498 //===----------------------------------------------------------------------===//
499 // Custom DAG optimizations
500 //===----------------------------------------------------------------------===//
501
502 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
503                                             DAGCombinerInfo &DCI) const {
504   SelectionDAG &DAG = DCI.DAG;
505   SDLoc DL(N);
506   EVT VT = N->getValueType(0);
507
508   switch (N->getOpcode()) {
509     default: break;
510     case ISD::SELECT_CC: {
511       N->dump();
512       ConstantSDNode *True, *False;
513       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
514       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
515           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
516           && True->isAllOnesValue()
517           && False->isNullValue()
518           && VT == MVT::i1) {
519         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
520                            N->getOperand(1), N->getOperand(4));
521
522       }
523       break;
524     }
525     case ISD::SETCC: {
526       SDValue Arg0 = N->getOperand(0);
527       SDValue Arg1 = N->getOperand(1);
528       SDValue CC = N->getOperand(2);
529       ConstantSDNode * C = NULL;
530       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
531
532       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
533       if (VT == MVT::i1
534           && Arg0.getOpcode() == ISD::SIGN_EXTEND
535           && Arg0.getOperand(0).getValueType() == MVT::i1
536           && (C = dyn_cast<ConstantSDNode>(Arg1))
537           && C->isNullValue()
538           && CCOp == ISD::SETNE) {
539         return SimplifySetCC(VT, Arg0.getOperand(0),
540                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
541       }
542       break;
543     }
544   }
545   return SDValue();
546 }
547
548 /// \brief Test if RegClass is one of the VSrc classes
549 static bool isVSrc(unsigned RegClass) {
550   return AMDGPU::VSrc_32RegClassID == RegClass ||
551          AMDGPU::VSrc_64RegClassID == RegClass;
552 }
553
554 /// \brief Test if RegClass is one of the SSrc classes
555 static bool isSSrc(unsigned RegClass) {
556   return AMDGPU::SSrc_32RegClassID == RegClass ||
557          AMDGPU::SSrc_64RegClassID == RegClass;
558 }
559
560 /// \brief Analyze the possible immediate value Op
561 ///
562 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
563 /// and the immediate value if it's a literal immediate
564 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
565
566   union {
567     int32_t I;
568     float F;
569   } Imm;
570
571   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
572     if (Node->getZExtValue() >> 32) {
573         return -1;
574     }
575     Imm.I = Node->getSExtValue();
576   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
577     Imm.F = Node->getValueAPF().convertToFloat();
578   else
579     return -1; // It isn't an immediate
580
581   if ((Imm.I >= -16 && Imm.I <= 64) ||
582       Imm.F == 0.5f || Imm.F == -0.5f ||
583       Imm.F == 1.0f || Imm.F == -1.0f ||
584       Imm.F == 2.0f || Imm.F == -2.0f ||
585       Imm.F == 4.0f || Imm.F == -4.0f)
586     return 0; // It's an inline immediate
587
588   return Imm.I; // It's a literal immediate
589 }
590
591 /// \brief Try to fold an immediate directly into an instruction
592 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
593                                bool &ScalarSlotUsed) const {
594
595   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
596   const SIInstrInfo *TII =
597     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
598   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
599     return false;
600
601   const SDValue &Op = Mov->getOperand(0);
602   int32_t Value = analyzeImmediate(Op.getNode());
603   if (Value == -1) {
604     // Not an immediate at all
605     return false;
606
607   } else if (Value == 0) {
608     // Inline immediates can always be fold
609     Operand = Op;
610     return true;
611
612   } else if (Value == Immediate) {
613     // Already fold literal immediate
614     Operand = Op;
615     return true;
616
617   } else if (!ScalarSlotUsed && !Immediate) {
618     // Fold this literal immediate
619     ScalarSlotUsed = true;
620     Immediate = Value;
621     Operand = Op;
622     return true;
623
624   }
625
626   return false;
627 }
628
629 /// \brief Does "Op" fit into register class "RegClass" ?
630 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
631                                     unsigned RegClass) const {
632
633   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
634   SDNode *Node = Op.getNode();
635
636   const TargetRegisterClass *OpClass;
637   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
638   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(Node)) {
639     const SIInstrInfo *TII =
640       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
641     const MCInstrDesc &Desc = TII->get(MN->getMachineOpcode());
642     int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
643     if (OpClassID == -1) {
644       switch (MN->getMachineOpcode()) {
645       case AMDGPU::REG_SEQUENCE:
646         // Operand 0 is the register class id for REG_SEQUENCE instructions.
647         OpClass = TRI->getRegClass(
648                        cast<ConstantSDNode>(MN->getOperand(0))->getZExtValue());
649         break;
650       default:
651         OpClass = getRegClassFor(Op.getSimpleValueType());
652         break;
653       }
654     } else {
655       OpClass = TRI->getRegClass(OpClassID);
656     }
657
658   } else if (Node->getOpcode() == ISD::CopyFromReg) {
659     RegisterSDNode *Reg = cast<RegisterSDNode>(Node->getOperand(1).getNode());
660     OpClass = MRI.getRegClass(Reg->getReg());
661
662   } else
663     return false;
664
665   return TRI->getRegClass(RegClass)->hasSubClassEq(OpClass);
666 }
667
668 /// \brief Make sure that we don't exeed the number of allowed scalars
669 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
670                                        unsigned RegClass,
671                                        bool &ScalarSlotUsed) const {
672
673   // First map the operands register class to a destination class
674   if (RegClass == AMDGPU::VSrc_32RegClassID)
675     RegClass = AMDGPU::VReg_32RegClassID;
676   else if (RegClass == AMDGPU::VSrc_64RegClassID)
677     RegClass = AMDGPU::VReg_64RegClassID;
678   else
679     return;
680
681   // Nothing todo if they fit naturaly
682   if (fitsRegClass(DAG, Operand, RegClass))
683     return;
684
685   // If the scalar slot isn't used yet use it now
686   if (!ScalarSlotUsed) {
687     ScalarSlotUsed = true;
688     return;
689   }
690
691   // This is a conservative aproach, it is possible that we can't determine
692   // the correct register class and copy too often, but better save than sorry.
693   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
694   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
695                                     Operand.getValueType(), Operand, RC);
696   Operand = SDValue(Node, 0);
697 }
698
699 /// \returns true if \p Node's operands are different from the SDValue list
700 /// \p Ops
701 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
702   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
703     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
704       return true;
705     }
706   }
707   return false;
708 }
709
710 /// \brief Try to fold the Nodes operands into the Node
711 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
712                                        SelectionDAG &DAG) const {
713
714   // Original encoding (either e32 or e64)
715   int Opcode = Node->getMachineOpcode();
716   const SIInstrInfo *TII =
717     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
718   const MCInstrDesc *Desc = &TII->get(Opcode);
719
720   unsigned NumDefs = Desc->getNumDefs();
721   unsigned NumOps = Desc->getNumOperands();
722
723   // Commuted opcode if available
724   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
725   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
726
727   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
728   assert(!DescRev || DescRev->getNumOperands() == NumOps);
729
730   // e64 version if available, -1 otherwise
731   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
732   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
733
734   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
735   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
736
737   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
738   bool HaveVSrc = false, HaveSSrc = false;
739
740   // First figure out what we alread have in this instruction
741   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
742        i != e && Op < NumOps; ++i, ++Op) {
743
744     unsigned RegClass = Desc->OpInfo[Op].RegClass;
745     if (isVSrc(RegClass))
746       HaveVSrc = true;
747     else if (isSSrc(RegClass))
748       HaveSSrc = true;
749     else
750       continue;
751
752     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
753     if (Imm != -1 && Imm != 0) {
754       // Literal immediate
755       Immediate = Imm;
756     }
757   }
758
759   // If we neither have VSrc nor SSrc it makes no sense to continue
760   if (!HaveVSrc && !HaveSSrc)
761     return Node;
762
763   // No scalar allowed when we have both VSrc and SSrc
764   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
765
766   // Second go over the operands and try to fold them
767   std::vector<SDValue> Ops;
768   bool Promote2e64 = false;
769   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
770        i != e && Op < NumOps; ++i, ++Op) {
771
772     const SDValue &Operand = Node->getOperand(i);
773     Ops.push_back(Operand);
774
775     // Already folded immediate ?
776     if (isa<ConstantSDNode>(Operand.getNode()) ||
777         isa<ConstantFPSDNode>(Operand.getNode()))
778       continue;
779
780     // Is this a VSrc or SSrc operand ?
781     unsigned RegClass = Desc->OpInfo[Op].RegClass;
782     if (isVSrc(RegClass) || isSSrc(RegClass)) {
783       // Try to fold the immediates
784       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
785         // Folding didn't worked, make sure we don't hit the SReg limit
786         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
787       }
788       continue;
789     }
790
791     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
792
793       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
794       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
795
796       // Test if it makes sense to swap operands
797       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
798           (!fitsRegClass(DAG, Ops[1], RegClass) &&
799            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
800
801         // Swap commutable operands
802         SDValue Tmp = Ops[1];
803         Ops[1] = Ops[0];
804         Ops[0] = Tmp;
805
806         Desc = DescRev;
807         DescRev = 0;
808         continue;
809       }
810     }
811
812     if (DescE64 && !Immediate) {
813
814       // Test if it makes sense to switch to e64 encoding
815       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
816       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
817         continue;
818
819       int32_t TmpImm = -1;
820       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
821           (!fitsRegClass(DAG, Ops[i], RegClass) &&
822            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
823
824         // Switch to e64 encoding
825         Immediate = -1;
826         Promote2e64 = true;
827         Desc = DescE64;
828         DescE64 = 0;
829       }
830     }
831   }
832
833   if (Promote2e64) {
834     // Add the modifier flags while promoting
835     for (unsigned i = 0; i < 4; ++i)
836       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
837   }
838
839   // Add optional chain and glue
840   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
841     Ops.push_back(Node->getOperand(i));
842
843   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
844   // this case a brand new node is always be created, even if the operands
845   // are the same as before.  So, manually check if anything has been changed.
846   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
847     return Node;
848   }
849
850   // Create a complete new instruction
851   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
852 }
853
854 /// \brief Helper function for adjustWritemask
855 static unsigned SubIdx2Lane(unsigned Idx) {
856   switch (Idx) {
857   default: return 0;
858   case AMDGPU::sub0: return 0;
859   case AMDGPU::sub1: return 1;
860   case AMDGPU::sub2: return 2;
861   case AMDGPU::sub3: return 3;
862   }
863 }
864
865 /// \brief Adjust the writemask of MIMG instructions
866 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
867                                        SelectionDAG &DAG) const {
868   SDNode *Users[4] = { };
869   unsigned Writemask = 0, Lane = 0;
870
871   // Try to figure out the used register components
872   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
873        I != E; ++I) {
874
875     // Abort if we can't understand the usage
876     if (!I->isMachineOpcode() ||
877         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
878       return;
879
880     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
881
882     // Abort if we have more than one user per component
883     if (Users[Lane])
884       return;
885
886     Users[Lane] = *I;
887     Writemask |= 1 << Lane;
888   }
889
890   // Abort if all components are used
891   if (Writemask == 0xf)
892     return;
893
894   // Adjust the writemask in the node
895   std::vector<SDValue> Ops;
896   Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
897   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
898     Ops.push_back(Node->getOperand(i));
899   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
900
901   // If we only got one lane, replace it with a copy
902   if (Writemask == (1U << Lane)) {
903     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
904     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
905                                       SDLoc(), Users[Lane]->getValueType(0),
906                                       SDValue(Node, 0), RC);
907     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
908     return;
909   }
910
911   // Update the users of the node with the new indices
912   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
913
914     SDNode *User = Users[i];
915     if (!User)
916       continue;
917
918     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
919     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
920
921     switch (Idx) {
922     default: break;
923     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
924     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
925     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
926     }
927   }
928 }
929
930 /// \brief Fold the instructions after slecting them
931 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
932                                           SelectionDAG &DAG) const {
933   Node = AdjustRegClass(Node, DAG);
934
935   if (AMDGPU::isMIMG(Node->getMachineOpcode()) != -1)
936     adjustWritemask(Node, DAG);
937
938   return foldOperands(Node, DAG);
939 }
940
941 /// \brief Assign the register class depending on the number of
942 /// bits set in the writemask
943 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
944                                                      SDNode *Node) const {
945   if (AMDGPU::isMIMG(MI->getOpcode()) == -1)
946     return;
947
948   unsigned VReg = MI->getOperand(0).getReg();
949   unsigned Writemask = MI->getOperand(1).getImm();
950   unsigned BitsSet = 0;
951   for (unsigned i = 0; i < 4; ++i)
952     BitsSet += Writemask & (1 << i) ? 1 : 0;
953
954   const TargetRegisterClass *RC;
955   switch (BitsSet) {
956   default: return;
957   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
958   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
959   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
960   }
961
962   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
963   MRI.setRegClass(VReg, RC);
964 }
965
966 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
967                                                 SelectionDAG &DAG) const {
968
969   SDLoc DL(N);
970   unsigned NewOpcode = N->getMachineOpcode();
971
972   switch (N->getMachineOpcode()) {
973   default: return N;
974   case AMDGPU::REG_SEQUENCE: {
975     // MVT::i128 only use SGPRs, so i128 REG_SEQUENCEs don't need to be
976     // rewritten.
977     if (N->getValueType(0) == MVT::i128) {
978       return N;
979     }
980     const SDValue Ops[] = {
981       DAG.getTargetConstant(AMDGPU::VReg_64RegClassID, MVT::i32),
982       N->getOperand(1) , N->getOperand(2),
983       N->getOperand(3), N->getOperand(4)
984     };
985     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::i64, Ops);
986   }
987
988   case AMDGPU::S_LOAD_DWORD_IMM:
989     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
990     // Fall-through
991   case AMDGPU::S_LOAD_DWORDX2_SGPR:
992     if (NewOpcode == N->getMachineOpcode()) {
993       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
994     }
995     // Fall-through
996   case AMDGPU::S_LOAD_DWORDX4_IMM:
997   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
998     if (NewOpcode == N->getMachineOpcode()) {
999       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1000     }
1001     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1002       return N;
1003     }
1004     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1005     SDValue Ops[] = {
1006       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1007                                  DAG.getConstant(0, MVT::i64)), 0),
1008       N->getOperand(0),
1009       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1010     };
1011     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1012   }
1013   }
1014 }
1015
1016 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1017                                                const TargetRegisterClass *RC,
1018                                                unsigned Reg, EVT VT) const {
1019   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1020
1021   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1022                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1023 }