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