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