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