R600: Make sign_extend_inreg legal.
[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 "AMDGPUSubtarget.h"
18 #include "AMDILIntrinsicInfo.h"
19 #include "SIInstrInfo.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/CodeGen/CallingConvLower.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/IR/Function.h"
27
28 using namespace llvm;
29
30 SITargetLowering::SITargetLowering(TargetMachine &TM) :
31     AMDGPUTargetLowering(TM) {
32   addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
33   addRegisterClass(MVT::i64, &AMDGPU::VSrc_64RegClass);
34
35   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
36   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
37
38   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
39   addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
40
41   addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
42   addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
43   addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
44
45   addRegisterClass(MVT::v4i32, &AMDGPU::VSrc_128RegClass);
46   addRegisterClass(MVT::v4f32, &AMDGPU::VSrc_128RegClass);
47
48   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
49   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
50
51   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
52   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
53
54   computeRegisterProperties();
55
56   // Condition Codes
57   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
58   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
59   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
60   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
61   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
62   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
63
64   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
65   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
66   setCondCodeAction(ISD::SETUGE, MVT::f64, Expand);
67   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
68   setCondCodeAction(ISD::SETULE, MVT::f64, Expand);
69   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
70
71   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
72   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
73   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
74   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
75
76   setOperationAction(ISD::ADD, MVT::i32, Legal);
77   setOperationAction(ISD::ADDC, MVT::i32, Legal);
78   setOperationAction(ISD::ADDE, MVT::i32, Legal);
79
80   // We need to custom lower vector stores from local memory
81   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
82   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
83   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
84   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
85
86   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
87   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
88
89   // We need to custom lower loads/stores from private memory
90   setOperationAction(ISD::LOAD, MVT::i32, Custom);
91   setOperationAction(ISD::LOAD, MVT::i64, Custom);
92   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
93   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
94   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
95
96   setOperationAction(ISD::STORE, MVT::i1, Custom);
97   setOperationAction(ISD::STORE, MVT::i32, Custom);
98   setOperationAction(ISD::STORE, MVT::i64, Custom);
99   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
100   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
101
102   setOperationAction(ISD::SELECT, MVT::i64, Custom);
103   setOperationAction(ISD::SELECT, MVT::f64, Promote);
104   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
105
106   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
107   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
108
109   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
110
111   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
112   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
113
114   setOperationAction(ISD::ANY_EXTEND, MVT::i64, Custom);
115   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
116   setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
117
118   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
121
122   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
125
126   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
129
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
131
132   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
133
134   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
135   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
136   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
137   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
138
139   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
140
141   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
142   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
143   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
144   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
145   setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
146   setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
147
148   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
149   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
150   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
151   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
152
153   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
154   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
155   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
156   setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
157   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
158
159   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
160   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
163   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
164   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
165
166   setOperationAction(ISD::LOAD, MVT::i1, Custom);
167
168   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
169   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
170   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
171
172   // We only support LOAD/STORE and vector manipulation ops for vectors
173   // with > 4 elements.
174   MVT VecTypes[] = {
175     MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
176   };
177
178   const size_t NumVecTypes = array_lengthof(VecTypes);
179   for (unsigned Type = 0; Type < NumVecTypes; ++Type) {
180     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
181       switch(Op) {
182       case ISD::LOAD:
183       case ISD::STORE:
184       case ISD::BUILD_VECTOR:
185       case ISD::BITCAST:
186       case ISD::EXTRACT_VECTOR_ELT:
187       case ISD::INSERT_VECTOR_ELT:
188       case ISD::CONCAT_VECTORS:
189       case ISD::INSERT_SUBVECTOR:
190       case ISD::EXTRACT_SUBVECTOR:
191         break;
192       default:
193         setOperationAction(Op, VecTypes[Type], Expand);
194         break;
195       }
196     }
197   }
198
199   for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
200     MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
201     setOperationAction(ISD::FTRUNC, VT, Expand);
202     setOperationAction(ISD::FCEIL, VT, Expand);
203     setOperationAction(ISD::FFLOOR, VT, Expand);
204   }
205
206   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
207     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
208     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
209     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
210     setOperationAction(ISD::FRINT, MVT::f64, Legal);
211   }
212
213   setTargetDAGCombine(ISD::SELECT_CC);
214   setTargetDAGCombine(ISD::SETCC);
215
216   setSchedulingPreference(Sched::RegPressure);
217 }
218
219 //===----------------------------------------------------------------------===//
220 // TargetLowering queries
221 //===----------------------------------------------------------------------===//
222
223 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
224                                                      unsigned AddrSpace,
225                                                      bool *IsFast) const {
226   // XXX: This depends on the address space and also we may want to revist
227   // the alignment values we specify in the DataLayout.
228   if (!VT.isSimple() || VT == MVT::Other)
229     return false;
230   return VT.bitsGT(MVT::i32);
231 }
232
233 bool SITargetLowering::shouldSplitVectorType(EVT VT) const {
234   return VT.getScalarType().bitsLE(MVT::i16);
235 }
236
237 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
238                                                          Type *Ty) const {
239   const SIInstrInfo *TII =
240     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
241   return TII->isInlineConstant(Imm);
242 }
243
244 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
245                                          SDLoc DL, SDValue Chain,
246                                          unsigned Offset, bool Signed) const {
247   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
248   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
249                                             AMDGPUAS::CONSTANT_ADDRESS);
250   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
251                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
252   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
253                                              DAG.getConstant(Offset, MVT::i64));
254   return DAG.getExtLoad(Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
255                             MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
256                             false, false, MemVT.getSizeInBits() >> 3);
257
258 }
259
260 SDValue SITargetLowering::LowerFormalArguments(
261                                       SDValue Chain,
262                                       CallingConv::ID CallConv,
263                                       bool isVarArg,
264                                       const SmallVectorImpl<ISD::InputArg> &Ins,
265                                       SDLoc DL, SelectionDAG &DAG,
266                                       SmallVectorImpl<SDValue> &InVals) const {
267
268   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
269
270   MachineFunction &MF = DAG.getMachineFunction();
271   FunctionType *FType = MF.getFunction()->getFunctionType();
272   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
273
274   assert(CallConv == CallingConv::C);
275
276   SmallVector<ISD::InputArg, 16> Splits;
277   uint32_t Skipped = 0;
278
279   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
280     const ISD::InputArg &Arg = Ins[i];
281
282     // First check if it's a PS input addr
283     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
284         !Arg.Flags.isByVal()) {
285
286       assert((PSInputNum <= 15) && "Too many PS inputs!");
287
288       if (!Arg.Used) {
289         // We can savely skip PS inputs
290         Skipped |= 1 << i;
291         ++PSInputNum;
292         continue;
293       }
294
295       Info->PSInputAddr |= 1 << PSInputNum++;
296     }
297
298     // Second split vertices into their elements
299     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
300       ISD::InputArg NewArg = Arg;
301       NewArg.Flags.setSplit();
302       NewArg.VT = Arg.VT.getVectorElementType();
303
304       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
305       // three or five element vertex only needs three or five registers,
306       // NOT four or eigth.
307       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
308       unsigned NumElements = ParamType->getVectorNumElements();
309
310       for (unsigned j = 0; j != NumElements; ++j) {
311         Splits.push_back(NewArg);
312         NewArg.PartOffset += NewArg.VT.getStoreSize();
313       }
314
315     } else if (Info->ShaderType != ShaderType::COMPUTE) {
316       Splits.push_back(Arg);
317     }
318   }
319
320   SmallVector<CCValAssign, 16> ArgLocs;
321   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
322                  getTargetMachine(), ArgLocs, *DAG.getContext());
323
324   // At least one interpolation mode must be enabled or else the GPU will hang.
325   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
326     Info->PSInputAddr |= 1;
327     CCInfo.AllocateReg(AMDGPU::VGPR0);
328     CCInfo.AllocateReg(AMDGPU::VGPR1);
329   }
330
331   // The pointer to the list of arguments is stored in SGPR0, SGPR1
332   if (Info->ShaderType == ShaderType::COMPUTE) {
333     CCInfo.AllocateReg(AMDGPU::SGPR0);
334     CCInfo.AllocateReg(AMDGPU::SGPR1);
335     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
336   }
337
338   if (Info->ShaderType == ShaderType::COMPUTE) {
339     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
340                             Splits);
341   }
342
343   AnalyzeFormalArguments(CCInfo, Splits);
344
345   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
346
347     const ISD::InputArg &Arg = Ins[i];
348     if (Skipped & (1 << i)) {
349       InVals.push_back(DAG.getUNDEF(Arg.VT));
350       continue;
351     }
352
353     CCValAssign &VA = ArgLocs[ArgIdx++];
354     EVT VT = VA.getLocVT();
355
356     if (VA.isMemLoc()) {
357       VT = Ins[i].VT;
358       EVT MemVT = Splits[i].VT;
359       // The first 36 bytes of the input buffer contains information about
360       // thread group and global sizes.
361       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, DAG.getRoot(),
362                                    36 + VA.getLocMemOffset(),
363                                    Ins[i].Flags.isSExt());
364       InVals.push_back(Arg);
365       continue;
366     }
367     assert(VA.isRegLoc() && "Parameter must be in a register!");
368
369     unsigned Reg = VA.getLocReg();
370
371     if (VT == MVT::i64) {
372       // For now assume it is a pointer
373       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
374                                      &AMDGPU::SReg_64RegClass);
375       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
376       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
377       continue;
378     }
379
380     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
381
382     Reg = MF.addLiveIn(Reg, RC);
383     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
384
385     if (Arg.VT.isVector()) {
386
387       // Build a vector from the registers
388       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
389       unsigned NumElements = ParamType->getVectorNumElements();
390
391       SmallVector<SDValue, 4> Regs;
392       Regs.push_back(Val);
393       for (unsigned j = 1; j != NumElements; ++j) {
394         Reg = ArgLocs[ArgIdx++].getLocReg();
395         Reg = MF.addLiveIn(Reg, RC);
396         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
397       }
398
399       // Fill up the missing vector elements
400       NumElements = Arg.VT.getVectorNumElements() - NumElements;
401       for (unsigned j = 0; j != NumElements; ++j)
402         Regs.push_back(DAG.getUNDEF(VT));
403
404       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
405                                    Regs.data(), Regs.size()));
406       continue;
407     }
408
409     InVals.push_back(Val);
410   }
411   return Chain;
412 }
413
414 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
415     MachineInstr * MI, MachineBasicBlock * BB) const {
416
417   MachineBasicBlock::iterator I = *MI;
418
419   switch (MI->getOpcode()) {
420   default:
421     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
422   case AMDGPU::BRANCH: return BB;
423   case AMDGPU::SI_ADDR64_RSRC: {
424     const SIInstrInfo *TII =
425       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
426     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
427     unsigned SuperReg = MI->getOperand(0).getReg();
428     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
429     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
430     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
431     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
432     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
433             .addOperand(MI->getOperand(1));
434     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
435             .addImm(0);
436     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
437             .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
438     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
439             .addReg(SubRegHiLo)
440             .addImm(AMDGPU::sub0)
441             .addReg(SubRegHiHi)
442             .addImm(AMDGPU::sub1);
443     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
444             .addReg(SubRegLo)
445             .addImm(AMDGPU::sub0_sub1)
446             .addReg(SubRegHi)
447             .addImm(AMDGPU::sub2_sub3);
448     MI->eraseFromParent();
449     break;
450   }
451   case AMDGPU::V_SUB_F64: {
452     const SIInstrInfo *TII =
453       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
454     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
455             MI->getOperand(0).getReg())
456             .addReg(MI->getOperand(1).getReg())
457             .addReg(MI->getOperand(2).getReg())
458             .addImm(0)  /* src2 */
459             .addImm(0)  /* ABS */
460             .addImm(0)  /* CLAMP */
461             .addImm(0)  /* OMOD */
462             .addImm(2); /* NEG */
463     MI->eraseFromParent();
464     break;
465   }
466   case AMDGPU::SI_RegisterStorePseudo: {
467     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
468     const SIInstrInfo *TII =
469       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
470     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
471     MachineInstrBuilder MIB =
472         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
473                 Reg);
474     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
475       MIB.addOperand(MI->getOperand(i));
476
477     MI->eraseFromParent();
478   }
479   }
480   return BB;
481 }
482
483 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
484   if (!VT.isVector()) {
485     return MVT::i1;
486   }
487   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
488 }
489
490 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
491   return MVT::i32;
492 }
493
494 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
495   VT = VT.getScalarType();
496
497   if (!VT.isSimple())
498     return false;
499
500   switch (VT.getSimpleVT().SimpleTy) {
501   case MVT::f32:
502     return false; /* There is V_MAD_F32 for f32 */
503   case MVT::f64:
504     return true;
505   default:
506     break;
507   }
508
509   return false;
510 }
511
512 //===----------------------------------------------------------------------===//
513 // Custom DAG Lowering Operations
514 //===----------------------------------------------------------------------===//
515
516 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
517   MachineFunction &MF = DAG.getMachineFunction();
518   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
519   switch (Op.getOpcode()) {
520   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
521   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
522   case ISD::LOAD: {
523     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
524     if (Op.getValueType().isVector() &&
525         (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
526          Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
527          (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
528           Op.getValueType().getVectorNumElements() > 4))) {
529       SDValue MergedValues[2] = {
530         SplitVectorLoad(Op, DAG),
531         Load->getChain()
532       };
533       return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
534     } else {
535       return LowerLOAD(Op, DAG);
536     }
537   }
538
539   case ISD::SELECT: return LowerSELECT(Op, DAG);
540   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
541   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
542   case ISD::STORE: return LowerSTORE(Op, DAG);
543   case ISD::ANY_EXTEND: // Fall-through
544   case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
545   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
546   case ISD::INTRINSIC_WO_CHAIN: {
547     unsigned IntrinsicID =
548                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
549     EVT VT = Op.getValueType();
550     SDLoc DL(Op);
551     //XXX: Hardcoded we only use two to store the pointer to the parameters.
552     unsigned NumUserSGPRs = 2;
553     switch (IntrinsicID) {
554     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
555     case Intrinsic::r600_read_ngroups_x:
556       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
557     case Intrinsic::r600_read_ngroups_y:
558       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
559     case Intrinsic::r600_read_ngroups_z:
560       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
561     case Intrinsic::r600_read_global_size_x:
562       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
563     case Intrinsic::r600_read_global_size_y:
564       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
565     case Intrinsic::r600_read_global_size_z:
566       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
567     case Intrinsic::r600_read_local_size_x:
568       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
569     case Intrinsic::r600_read_local_size_y:
570       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
571     case Intrinsic::r600_read_local_size_z:
572       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
573     case Intrinsic::r600_read_tgid_x:
574       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
575                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
576     case Intrinsic::r600_read_tgid_y:
577       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
578                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
579     case Intrinsic::r600_read_tgid_z:
580       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
581                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
582     case Intrinsic::r600_read_tidig_x:
583       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
584                                   AMDGPU::VGPR0, VT);
585     case Intrinsic::r600_read_tidig_y:
586       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
587                                   AMDGPU::VGPR1, VT);
588     case Intrinsic::r600_read_tidig_z:
589       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
590                                   AMDGPU::VGPR2, VT);
591     case AMDGPUIntrinsic::SI_load_const: {
592       SDValue Ops [] = {
593         Op.getOperand(1),
594         Op.getOperand(2)
595       };
596
597       MachineMemOperand *MMO = MF.getMachineMemOperand(
598           MachinePointerInfo(),
599           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
600           VT.getSizeInBits() / 8, 4);
601       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
602                                      Op->getVTList(), Ops, 2, VT, MMO);
603     }
604     case AMDGPUIntrinsic::SI_sample:
605       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
606     case AMDGPUIntrinsic::SI_sampleb:
607       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
608     case AMDGPUIntrinsic::SI_sampled:
609       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
610     case AMDGPUIntrinsic::SI_samplel:
611       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
612     case AMDGPUIntrinsic::SI_vs_load_input:
613       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
614                          Op.getOperand(1),
615                          Op.getOperand(2),
616                          Op.getOperand(3));
617     }
618   }
619
620   case ISD::INTRINSIC_VOID:
621     SDValue Chain = Op.getOperand(0);
622     unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
623
624     switch (IntrinsicID) {
625       case AMDGPUIntrinsic::SI_tbuffer_store: {
626         SDLoc DL(Op);
627         SDValue Ops [] = {
628           Chain,
629           Op.getOperand(2),
630           Op.getOperand(3),
631           Op.getOperand(4),
632           Op.getOperand(5),
633           Op.getOperand(6),
634           Op.getOperand(7),
635           Op.getOperand(8),
636           Op.getOperand(9),
637           Op.getOperand(10),
638           Op.getOperand(11),
639           Op.getOperand(12),
640           Op.getOperand(13),
641           Op.getOperand(14)
642         };
643         EVT VT = Op.getOperand(3).getValueType();
644
645         MachineMemOperand *MMO = MF.getMachineMemOperand(
646             MachinePointerInfo(),
647             MachineMemOperand::MOStore,
648             VT.getSizeInBits() / 8, 4);
649         return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
650                                        Op->getVTList(), Ops,
651                                        sizeof(Ops)/sizeof(Ops[0]), VT, MMO);
652       }
653       default:
654         break;
655     }
656   }
657   return SDValue();
658 }
659
660 /// \brief Helper function for LowerBRCOND
661 static SDNode *findUser(SDValue Value, unsigned Opcode) {
662
663   SDNode *Parent = Value.getNode();
664   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
665        I != E; ++I) {
666
667     if (I.getUse().get() != Value)
668       continue;
669
670     if (I->getOpcode() == Opcode)
671       return *I;
672   }
673   return 0;
674 }
675
676 /// This transforms the control flow intrinsics to get the branch destination as
677 /// last parameter, also switches branch target with BR if the need arise
678 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
679                                       SelectionDAG &DAG) const {
680
681   SDLoc DL(BRCOND);
682
683   SDNode *Intr = BRCOND.getOperand(1).getNode();
684   SDValue Target = BRCOND.getOperand(2);
685   SDNode *BR = 0;
686
687   if (Intr->getOpcode() == ISD::SETCC) {
688     // As long as we negate the condition everything is fine
689     SDNode *SetCC = Intr;
690     assert(SetCC->getConstantOperandVal(1) == 1);
691     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
692            ISD::SETNE);
693     Intr = SetCC->getOperand(0).getNode();
694
695   } else {
696     // Get the target from BR if we don't negate the condition
697     BR = findUser(BRCOND, ISD::BR);
698     Target = BR->getOperand(1);
699   }
700
701   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
702
703   // Build the result and
704   SmallVector<EVT, 4> Res;
705   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
706     Res.push_back(Intr->getValueType(i));
707
708   // operands of the new intrinsic call
709   SmallVector<SDValue, 4> Ops;
710   Ops.push_back(BRCOND.getOperand(0));
711   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
712     Ops.push_back(Intr->getOperand(i));
713   Ops.push_back(Target);
714
715   // build the new intrinsic call
716   SDNode *Result = DAG.getNode(
717     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
718     DAG.getVTList(Res), Ops.data(), Ops.size()).getNode();
719
720   if (BR) {
721     // Give the branch instruction our target
722     SDValue Ops[] = {
723       BR->getOperand(0),
724       BRCOND.getOperand(2)
725     };
726     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
727   }
728
729   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
730
731   // Copy the intrinsic results to registers
732   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
733     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
734     if (!CopyToReg)
735       continue;
736
737     Chain = DAG.getCopyToReg(
738       Chain, DL,
739       CopyToReg->getOperand(1),
740       SDValue(Result, i - 1),
741       SDValue());
742
743     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
744   }
745
746   // Remove the old intrinsic from the chain
747   DAG.ReplaceAllUsesOfValueWith(
748     SDValue(Intr, Intr->getNumValues() - 1),
749     Intr->getOperand(0));
750
751   return Chain;
752 }
753
754 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
755   SDLoc DL(Op);
756   LoadSDNode *Load = cast<LoadSDNode>(Op);
757   SDValue Ret = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
758   SDValue MergedValues[2];
759   MergedValues[1] = Load->getChain();
760   if (Ret.getNode()) {
761     MergedValues[0] = Ret;
762     return DAG.getMergeValues(MergedValues, 2, DL);
763   }
764
765   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
766     return SDValue();
767   }
768
769   EVT MemVT = Load->getMemoryVT();
770
771   assert(!MemVT.isVector() && "Private loads should be scalarized");
772   assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
773
774   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
775                             DAG.getConstant(2, MVT::i32));
776   Ret = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
777                     Load->getChain(), Ptr,
778                     DAG.getTargetConstant(0, MVT::i32),
779                     Op.getOperand(2));
780   if (MemVT.getSizeInBits() == 64) {
781     SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
782                                  DAG.getConstant(1, MVT::i32));
783
784     SDValue LoadUpper = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
785                                     Load->getChain(), IncPtr,
786                                     DAG.getTargetConstant(0, MVT::i32),
787                                     Op.getOperand(2));
788
789     Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ret, LoadUpper);
790   }
791
792   MergedValues[0] = Ret;
793   return DAG.getMergeValues(MergedValues, 2, DL);
794
795 }
796
797 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
798                                                const SDValue &Op,
799                                                SelectionDAG &DAG) const {
800   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
801                      Op.getOperand(2),
802                      Op.getOperand(3),
803                      Op.getOperand(4));
804 }
805
806 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
807   if (Op.getValueType() != MVT::i64)
808     return SDValue();
809
810   SDLoc DL(Op);
811   SDValue Cond = Op.getOperand(0);
812
813   SDValue Zero = DAG.getConstant(0, MVT::i32);
814   SDValue One = DAG.getConstant(1, MVT::i32);
815
816   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
817   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
818
819   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
820   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
821
822   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
823
824   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
825   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
826
827   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
828
829   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
830   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
831 }
832
833 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
834   SDValue LHS = Op.getOperand(0);
835   SDValue RHS = Op.getOperand(1);
836   SDValue True = Op.getOperand(2);
837   SDValue False = Op.getOperand(3);
838   SDValue CC = Op.getOperand(4);
839   EVT VT = Op.getValueType();
840   SDLoc DL(Op);
841
842   // Possible Min/Max pattern
843   SDValue MinMax = LowerMinMax(Op, DAG);
844   if (MinMax.getNode()) {
845     return MinMax;
846   }
847
848   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
849   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
850 }
851
852 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
853                                            SelectionDAG &DAG) const {
854   EVT VT = Op.getValueType();
855   SDLoc DL(Op);
856
857   if (VT != MVT::i64) {
858     return SDValue();
859   }
860
861   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
862                                                  DAG.getConstant(31, MVT::i32));
863
864   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
865 }
866
867 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
868   SDLoc DL(Op);
869   StoreSDNode *Store = cast<StoreSDNode>(Op);
870   EVT VT = Store->getMemoryVT();
871
872   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
873   if (Ret.getNode())
874     return Ret;
875
876   if (VT.isVector() && VT.getVectorNumElements() >= 8)
877       return SplitVectorStore(Op, DAG);
878
879   if (VT == MVT::i1)
880     return DAG.getTruncStore(Store->getChain(), DL,
881                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
882                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
883
884   if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
885     return SDValue();
886
887   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
888                             DAG.getConstant(2, MVT::i32));
889   SDValue Chain = Store->getChain();
890   SmallVector<SDValue, 8> Values;
891
892   if (Store->isTruncatingStore()) {
893     unsigned Mask = 0;
894     if (Store->getMemoryVT() == MVT::i8) {
895       Mask = 0xff;
896     } else if (Store->getMemoryVT() == MVT::i16) {
897       Mask = 0xffff;
898     }
899     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
900                               Chain, Store->getBasePtr(),
901                               DAG.getConstant(0, MVT::i32));
902     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
903                                   DAG.getConstant(0x3, MVT::i32));
904     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
905                                    DAG.getConstant(3, MVT::i32));
906     SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
907                                       DAG.getConstant(Mask, MVT::i32));
908     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
909                                        MaskedValue, ShiftAmt);
910     SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
911                                   DAG.getConstant(32, MVT::i32), ShiftAmt);
912     SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
913                                   DAG.getConstant(Mask, MVT::i32),
914                                   RotrAmt);
915     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
916     Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
917
918     Values.push_back(Dst);
919   } else if (VT == MVT::i64) {
920     for (unsigned i = 0; i < 2; ++i) {
921       Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
922                        Store->getValue(), DAG.getConstant(i, MVT::i32)));
923     }
924   } else if (VT == MVT::i128) {
925     for (unsigned i = 0; i < 2; ++i) {
926       for (unsigned j = 0; j < 2; ++j) {
927         Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
928                            DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
929                            Store->getValue(), DAG.getConstant(i, MVT::i32)),
930                          DAG.getConstant(j, MVT::i32)));
931       }
932     }
933   } else {
934     Values.push_back(Store->getValue());
935   }
936
937   for (unsigned i = 0; i < Values.size(); ++i) {
938     SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
939                                   Ptr, DAG.getConstant(i, MVT::i32));
940     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
941                         Chain, Values[i], PartPtr,
942                         DAG.getTargetConstant(0, MVT::i32));
943   }
944   return Chain;
945 }
946
947
948 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
949                                            SelectionDAG &DAG) const {
950   EVT VT = Op.getValueType();
951   SDLoc DL(Op);
952
953   if (VT != MVT::i64) {
954     return SDValue();
955   }
956
957   SDValue Src = Op.getOperand(0);
958   if (Src.getValueType() != MVT::i32)
959     Src = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Src);
960
961   SDValue Zero = DAG.getConstant(0, MVT::i32);
962   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Src, Zero);
963 }
964
965 //===----------------------------------------------------------------------===//
966 // Custom DAG optimizations
967 //===----------------------------------------------------------------------===//
968
969 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
970                                             DAGCombinerInfo &DCI) const {
971   SelectionDAG &DAG = DCI.DAG;
972   SDLoc DL(N);
973   EVT VT = N->getValueType(0);
974
975   switch (N->getOpcode()) {
976     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
977     case ISD::SELECT_CC: {
978       ConstantSDNode *True, *False;
979       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
980       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
981           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
982           && True->isAllOnesValue()
983           && False->isNullValue()
984           && VT == MVT::i1) {
985         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
986                            N->getOperand(1), N->getOperand(4));
987
988       }
989       break;
990     }
991     case ISD::SETCC: {
992       SDValue Arg0 = N->getOperand(0);
993       SDValue Arg1 = N->getOperand(1);
994       SDValue CC = N->getOperand(2);
995       ConstantSDNode * C = NULL;
996       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
997
998       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
999       if (VT == MVT::i1
1000           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1001           && Arg0.getOperand(0).getValueType() == MVT::i1
1002           && (C = dyn_cast<ConstantSDNode>(Arg1))
1003           && C->isNullValue()
1004           && CCOp == ISD::SETNE) {
1005         return SimplifySetCC(VT, Arg0.getOperand(0),
1006                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1007       }
1008       break;
1009     }
1010   }
1011   return SDValue();
1012 }
1013
1014 /// \brief Test if RegClass is one of the VSrc classes
1015 static bool isVSrc(unsigned RegClass) {
1016   return AMDGPU::VSrc_32RegClassID == RegClass ||
1017          AMDGPU::VSrc_64RegClassID == RegClass;
1018 }
1019
1020 /// \brief Test if RegClass is one of the SSrc classes
1021 static bool isSSrc(unsigned RegClass) {
1022   return AMDGPU::SSrc_32RegClassID == RegClass ||
1023          AMDGPU::SSrc_64RegClassID == RegClass;
1024 }
1025
1026 /// \brief Analyze the possible immediate value Op
1027 ///
1028 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1029 /// and the immediate value if it's a literal immediate
1030 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1031
1032   union {
1033     int32_t I;
1034     float F;
1035   } Imm;
1036
1037   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1038     if (Node->getZExtValue() >> 32) {
1039         return -1;
1040     }
1041     Imm.I = Node->getSExtValue();
1042   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1043     if (N->getValueType(0) != MVT::f32)
1044       return -1;
1045     Imm.F = Node->getValueAPF().convertToFloat();
1046   } else
1047     return -1; // It isn't an immediate
1048
1049   if ((Imm.I >= -16 && Imm.I <= 64) ||
1050       Imm.F == 0.5f || Imm.F == -0.5f ||
1051       Imm.F == 1.0f || Imm.F == -1.0f ||
1052       Imm.F == 2.0f || Imm.F == -2.0f ||
1053       Imm.F == 4.0f || Imm.F == -4.0f)
1054     return 0; // It's an inline immediate
1055
1056   return Imm.I; // It's a literal immediate
1057 }
1058
1059 /// \brief Try to fold an immediate directly into an instruction
1060 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1061                                bool &ScalarSlotUsed) const {
1062
1063   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1064   const SIInstrInfo *TII =
1065     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1066   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
1067     return false;
1068
1069   const SDValue &Op = Mov->getOperand(0);
1070   int32_t Value = analyzeImmediate(Op.getNode());
1071   if (Value == -1) {
1072     // Not an immediate at all
1073     return false;
1074
1075   } else if (Value == 0) {
1076     // Inline immediates can always be fold
1077     Operand = Op;
1078     return true;
1079
1080   } else if (Value == Immediate) {
1081     // Already fold literal immediate
1082     Operand = Op;
1083     return true;
1084
1085   } else if (!ScalarSlotUsed && !Immediate) {
1086     // Fold this literal immediate
1087     ScalarSlotUsed = true;
1088     Immediate = Value;
1089     Operand = Op;
1090     return true;
1091
1092   }
1093
1094   return false;
1095 }
1096
1097 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1098                                    SelectionDAG &DAG, const SDValue &Op) const {
1099   const SIInstrInfo *TII =
1100     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1101   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1102
1103   if (!Op->isMachineOpcode()) {
1104     switch(Op->getOpcode()) {
1105     case ISD::CopyFromReg: {
1106       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1107       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1108       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1109         return MRI.getRegClass(Reg);
1110       }
1111       return TRI.getPhysRegClass(Reg);
1112     }
1113     default:  return NULL;
1114     }
1115   }
1116   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1117   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1118   if (OpClassID != -1) {
1119     return TRI.getRegClass(OpClassID);
1120   }
1121   switch(Op.getMachineOpcode()) {
1122   case AMDGPU::COPY_TO_REGCLASS:
1123     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1124     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1125
1126     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1127     // class, then the register class for the value could be either a
1128     // VReg or and SReg.  In order to get a more accurate
1129     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1130         OpClassID == AMDGPU::VSrc_64RegClassID) {
1131       return getRegClassForNode(DAG, Op.getOperand(0));
1132     }
1133     return TRI.getRegClass(OpClassID);
1134   case AMDGPU::EXTRACT_SUBREG: {
1135     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1136     const TargetRegisterClass *SuperClass =
1137       getRegClassForNode(DAG, Op.getOperand(0));
1138     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1139   }
1140   case AMDGPU::REG_SEQUENCE:
1141     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1142     return TRI.getRegClass(
1143       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1144   default:
1145     return getRegClassFor(Op.getSimpleValueType());
1146   }
1147 }
1148
1149 /// \brief Does "Op" fit into register class "RegClass" ?
1150 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1151                                     unsigned RegClass) const {
1152   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1153   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1154   if (!RC) {
1155     return false;
1156   }
1157   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1158 }
1159
1160 /// \brief Make sure that we don't exeed the number of allowed scalars
1161 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1162                                        unsigned RegClass,
1163                                        bool &ScalarSlotUsed) const {
1164
1165   // First map the operands register class to a destination class
1166   if (RegClass == AMDGPU::VSrc_32RegClassID)
1167     RegClass = AMDGPU::VReg_32RegClassID;
1168   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1169     RegClass = AMDGPU::VReg_64RegClassID;
1170   else
1171     return;
1172
1173   // Nothing to do if they fit naturally
1174   if (fitsRegClass(DAG, Operand, RegClass))
1175     return;
1176
1177   // If the scalar slot isn't used yet use it now
1178   if (!ScalarSlotUsed) {
1179     ScalarSlotUsed = true;
1180     return;
1181   }
1182
1183   // This is a conservative aproach. It is possible that we can't determine the
1184   // correct register class and copy too often, but better safe than sorry.
1185   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1186   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1187                                     Operand.getValueType(), Operand, RC);
1188   Operand = SDValue(Node, 0);
1189 }
1190
1191 /// \returns true if \p Node's operands are different from the SDValue list
1192 /// \p Ops
1193 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1194   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1195     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1196       return true;
1197     }
1198   }
1199   return false;
1200 }
1201
1202 /// \brief Try to fold the Nodes operands into the Node
1203 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1204                                        SelectionDAG &DAG) const {
1205
1206   // Original encoding (either e32 or e64)
1207   int Opcode = Node->getMachineOpcode();
1208   const SIInstrInfo *TII =
1209     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1210   const MCInstrDesc *Desc = &TII->get(Opcode);
1211
1212   unsigned NumDefs = Desc->getNumDefs();
1213   unsigned NumOps = Desc->getNumOperands();
1214
1215   // Commuted opcode if available
1216   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1217   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
1218
1219   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1220   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1221
1222   // e64 version if available, -1 otherwise
1223   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1224   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
1225
1226   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1227   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
1228
1229   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1230   bool HaveVSrc = false, HaveSSrc = false;
1231
1232   // First figure out what we alread have in this instruction
1233   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1234        i != e && Op < NumOps; ++i, ++Op) {
1235
1236     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1237     if (isVSrc(RegClass))
1238       HaveVSrc = true;
1239     else if (isSSrc(RegClass))
1240       HaveSSrc = true;
1241     else
1242       continue;
1243
1244     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1245     if (Imm != -1 && Imm != 0) {
1246       // Literal immediate
1247       Immediate = Imm;
1248     }
1249   }
1250
1251   // If we neither have VSrc nor SSrc it makes no sense to continue
1252   if (!HaveVSrc && !HaveSSrc)
1253     return Node;
1254
1255   // No scalar allowed when we have both VSrc and SSrc
1256   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1257
1258   // Second go over the operands and try to fold them
1259   std::vector<SDValue> Ops;
1260   bool Promote2e64 = false;
1261   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1262        i != e && Op < NumOps; ++i, ++Op) {
1263
1264     const SDValue &Operand = Node->getOperand(i);
1265     Ops.push_back(Operand);
1266
1267     // Already folded immediate ?
1268     if (isa<ConstantSDNode>(Operand.getNode()) ||
1269         isa<ConstantFPSDNode>(Operand.getNode()))
1270       continue;
1271
1272     // Is this a VSrc or SSrc operand ?
1273     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1274     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1275       // Try to fold the immediates
1276       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1277         // Folding didn't worked, make sure we don't hit the SReg limit
1278         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1279       }
1280       continue;
1281     }
1282
1283     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1284
1285       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1286       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1287
1288       // Test if it makes sense to swap operands
1289       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1290           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1291            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1292
1293         // Swap commutable operands
1294         std::swap(Ops[0], Ops[1]);
1295
1296         Desc = DescRev;
1297         DescRev = 0;
1298         continue;
1299       }
1300     }
1301
1302     if (DescE64 && !Immediate) {
1303
1304       // Test if it makes sense to switch to e64 encoding
1305       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1306       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1307         continue;
1308
1309       int32_t TmpImm = -1;
1310       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1311           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1312            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1313
1314         // Switch to e64 encoding
1315         Immediate = -1;
1316         Promote2e64 = true;
1317         Desc = DescE64;
1318         DescE64 = 0;
1319       }
1320     }
1321   }
1322
1323   if (Promote2e64) {
1324     // Add the modifier flags while promoting
1325     for (unsigned i = 0; i < 4; ++i)
1326       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1327   }
1328
1329   // Add optional chain and glue
1330   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1331     Ops.push_back(Node->getOperand(i));
1332
1333   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1334   // this case a brand new node is always be created, even if the operands
1335   // are the same as before.  So, manually check if anything has been changed.
1336   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1337     return Node;
1338   }
1339
1340   // Create a complete new instruction
1341   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1342 }
1343
1344 /// \brief Helper function for adjustWritemask
1345 static unsigned SubIdx2Lane(unsigned Idx) {
1346   switch (Idx) {
1347   default: return 0;
1348   case AMDGPU::sub0: return 0;
1349   case AMDGPU::sub1: return 1;
1350   case AMDGPU::sub2: return 2;
1351   case AMDGPU::sub3: return 3;
1352   }
1353 }
1354
1355 /// \brief Adjust the writemask of MIMG instructions
1356 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1357                                        SelectionDAG &DAG) const {
1358   SDNode *Users[4] = { };
1359   unsigned Lane = 0;
1360   unsigned OldDmask = Node->getConstantOperandVal(0);
1361   unsigned NewDmask = 0;
1362
1363   // Try to figure out the used register components
1364   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1365        I != E; ++I) {
1366
1367     // Abort if we can't understand the usage
1368     if (!I->isMachineOpcode() ||
1369         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1370       return;
1371
1372     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1373     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1374     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1375     // set, etc.
1376     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1377
1378     // Set which texture component corresponds to the lane.
1379     unsigned Comp;
1380     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1381       assert(Dmask);
1382       Comp = countTrailingZeros(Dmask);
1383       Dmask &= ~(1 << Comp);
1384     }
1385
1386     // Abort if we have more than one user per component
1387     if (Users[Lane])
1388       return;
1389
1390     Users[Lane] = *I;
1391     NewDmask |= 1 << Comp;
1392   }
1393
1394   // Abort if there's no change
1395   if (NewDmask == OldDmask)
1396     return;
1397
1398   // Adjust the writemask in the node
1399   std::vector<SDValue> Ops;
1400   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1401   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1402     Ops.push_back(Node->getOperand(i));
1403   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1404
1405   // If we only got one lane, replace it with a copy
1406   // (if NewDmask has only one bit set...)
1407   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1408     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1409     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1410                                       SDLoc(), Users[Lane]->getValueType(0),
1411                                       SDValue(Node, 0), RC);
1412     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1413     return;
1414   }
1415
1416   // Update the users of the node with the new indices
1417   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1418
1419     SDNode *User = Users[i];
1420     if (!User)
1421       continue;
1422
1423     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1424     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1425
1426     switch (Idx) {
1427     default: break;
1428     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1429     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1430     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1431     }
1432   }
1433 }
1434
1435 /// \brief Fold the instructions after slecting them
1436 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1437                                           SelectionDAG &DAG) const {
1438   const SIInstrInfo *TII =
1439       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1440   Node = AdjustRegClass(Node, DAG);
1441
1442   if (TII->isMIMG(Node->getMachineOpcode()))
1443     adjustWritemask(Node, DAG);
1444
1445   return foldOperands(Node, DAG);
1446 }
1447
1448 /// \brief Assign the register class depending on the number of
1449 /// bits set in the writemask
1450 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1451                                                      SDNode *Node) const {
1452   const SIInstrInfo *TII =
1453       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1454   if (!TII->isMIMG(MI->getOpcode()))
1455     return;
1456
1457   unsigned VReg = MI->getOperand(0).getReg();
1458   unsigned Writemask = MI->getOperand(1).getImm();
1459   unsigned BitsSet = 0;
1460   for (unsigned i = 0; i < 4; ++i)
1461     BitsSet += Writemask & (1 << i) ? 1 : 0;
1462
1463   const TargetRegisterClass *RC;
1464   switch (BitsSet) {
1465   default: return;
1466   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1467   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1468   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1469   }
1470
1471   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1472   MI->setDesc(TII->get(NewOpcode));
1473   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1474   MRI.setRegClass(VReg, RC);
1475 }
1476
1477 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1478                                                 SelectionDAG &DAG) const {
1479
1480   SDLoc DL(N);
1481   unsigned NewOpcode = N->getMachineOpcode();
1482
1483   switch (N->getMachineOpcode()) {
1484   default: return N;
1485   case AMDGPU::S_LOAD_DWORD_IMM:
1486     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1487     // Fall-through
1488   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1489     if (NewOpcode == N->getMachineOpcode()) {
1490       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1491     }
1492     // Fall-through
1493   case AMDGPU::S_LOAD_DWORDX4_IMM:
1494   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1495     if (NewOpcode == N->getMachineOpcode()) {
1496       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1497     }
1498     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1499       return N;
1500     }
1501     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1502     SDValue Ops[] = {
1503       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1504                                  DAG.getConstant(0, MVT::i64)), 0),
1505       N->getOperand(0),
1506       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1507     };
1508     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1509   }
1510   }
1511 }
1512
1513 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1514                                                const TargetRegisterClass *RC,
1515                                                unsigned Reg, EVT VT) const {
1516   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1517
1518   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1519                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1520 }