R600/SI: implement range reduction for sin/cos
[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 "AMDGPUIntrinsicInfo.h"
18 #include "AMDGPUSubtarget.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 #include "llvm/ADT/SmallString.h"
28
29 using namespace llvm;
30
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32     AMDGPUTargetLowering(TM) {
33   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
34   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
35
36   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
37   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
38
39   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
40   addRegisterClass(MVT::f32, &AMDGPU::VReg_32RegClass);
41
42   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
43   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
44   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
45
46   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
47   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_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   setOperationAction(ISD::SUBC, MVT::i32, Legal);
81   setOperationAction(ISD::SUBE, MVT::i32, Legal);
82
83   setOperationAction(ISD::FSIN, MVT::f32, Custom);
84   setOperationAction(ISD::FCOS, MVT::f32, Custom);
85
86   // We need to custom lower vector stores from local memory
87   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
88   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
89   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
90   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
91
92   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
93   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
94
95   // We need to custom lower loads/stores from private memory
96   setOperationAction(ISD::LOAD, MVT::i32, Custom);
97   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
98   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
99   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
100
101   setOperationAction(ISD::STORE, MVT::i1, Custom);
102   setOperationAction(ISD::STORE, MVT::i32, Custom);
103   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
104   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
105
106   setOperationAction(ISD::SELECT, MVT::f32, Promote);
107   AddPromotedToType(ISD::SELECT, MVT::f32, MVT::i32);
108   setOperationAction(ISD::SELECT, MVT::i64, Custom);
109   setOperationAction(ISD::SELECT, MVT::f64, Promote);
110   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
111
112   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
113   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
114   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
115   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
116
117   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
118   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
119
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
123
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
127
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
131
132   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Custom);
133
134   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
135
136   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
137   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
138   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
139   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
140
141   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
142   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
143
144   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
145   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
146   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
147   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
148   setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, Expand);
149   setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, Expand);
150
151   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
152   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
153   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
154   setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Expand);
155
156   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
157   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
158   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
159   setLoadExtAction(ISD::EXTLOAD, MVT::i32, Expand);
160   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
161
162   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
163   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
164   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
165   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
166   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
167   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
168
169   setOperationAction(ISD::LOAD, MVT::i1, Custom);
170
171   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Expand);
172   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
173
174   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
177
178   // These should use UDIVREM, so set them to expand
179   setOperationAction(ISD::UDIV, MVT::i64, Expand);
180   setOperationAction(ISD::UREM, MVT::i64, Expand);
181
182   // We only support LOAD/STORE and vector manipulation ops for vectors
183   // with > 4 elements.
184   MVT VecTypes[] = {
185     MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32
186   };
187
188   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189   setOperationAction(ISD::SELECT, MVT::i1, Promote);
190
191   for (MVT VT : VecTypes) {
192     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
193       switch(Op) {
194       case ISD::LOAD:
195       case ISD::STORE:
196       case ISD::BUILD_VECTOR:
197       case ISD::BITCAST:
198       case ISD::EXTRACT_VECTOR_ELT:
199       case ISD::INSERT_VECTOR_ELT:
200       case ISD::CONCAT_VECTORS:
201       case ISD::INSERT_SUBVECTOR:
202       case ISD::EXTRACT_SUBVECTOR:
203         break;
204       default:
205         setOperationAction(Op, VT, Expand);
206         break;
207       }
208     }
209   }
210
211   for (int I = MVT::v1f64; I <= MVT::v8f64; ++I) {
212     MVT::SimpleValueType VT = static_cast<MVT::SimpleValueType>(I);
213     setOperationAction(ISD::FTRUNC, VT, Expand);
214     setOperationAction(ISD::FCEIL, VT, Expand);
215     setOperationAction(ISD::FFLOOR, VT, Expand);
216   }
217
218   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
219     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
220     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
221     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
222     setOperationAction(ISD::FRINT, MVT::f64, Legal);
223   }
224
225   // FIXME: These should be removed and handled the same was as f32 fneg. Source
226   // modifiers also work for the double instructions.
227   setOperationAction(ISD::FNEG, MVT::f64, Expand);
228   setOperationAction(ISD::FABS, MVT::f64, Expand);
229
230   setOperationAction(ISD::FDIV, MVT::f32, Custom);
231
232   setTargetDAGCombine(ISD::SELECT_CC);
233   setTargetDAGCombine(ISD::SETCC);
234
235   setTargetDAGCombine(ISD::UINT_TO_FP);
236
237   setSchedulingPreference(Sched::RegPressure);
238 }
239
240 //===----------------------------------------------------------------------===//
241 // TargetLowering queries
242 //===----------------------------------------------------------------------===//
243
244 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
245                                                      unsigned AddrSpace,
246                                                      bool *IsFast) const {
247   if (IsFast)
248     *IsFast = false;
249
250   // XXX: This depends on the address space and also we may want to revist
251   // the alignment values we specify in the DataLayout.
252
253   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
254   // which isn't a simple VT.
255   if (!VT.isSimple() || VT == MVT::Other)
256     return false;
257
258   // XXX - CI changes say "Support for unaligned memory accesses" but I don't
259   // see what for specifically. The wording everywhere else seems to be the
260   // same.
261
262   // 3.6.4 - Operations using pairs of VGPRs (for example: double-floats) have
263   // no alignment restrictions.
264   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
265     // Using any pair of GPRs should be the same as any other pair.
266     if (IsFast)
267       *IsFast = true;
268     return VT.bitsGE(MVT::i64);
269   }
270
271   // XXX - The only mention I see of this in the ISA manual is for LDS direct
272   // reads the "byte address and must be dword aligned". Is it also true for the
273   // normal loads and stores?
274   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS)
275     return false;
276
277   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
278   // byte-address are ignored, thus forcing Dword alignment.
279   if (IsFast)
280     *IsFast = true;
281   return VT.bitsGT(MVT::i32);
282 }
283
284 TargetLoweringBase::LegalizeTypeAction
285 SITargetLowering::getPreferredVectorAction(EVT VT) const {
286   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
287     return TypeSplitVector;
288
289   return TargetLoweringBase::getPreferredVectorAction(VT);
290 }
291
292 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
293                                                          Type *Ty) const {
294   const SIInstrInfo *TII =
295     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
296   return TII->isInlineConstant(Imm);
297 }
298
299 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
300                                          SDLoc DL, SDValue Chain,
301                                          unsigned Offset, bool Signed) const {
302   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
303   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
304                                             AMDGPUAS::CONSTANT_ADDRESS);
305   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
306                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
307   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
308                                              DAG.getConstant(Offset, MVT::i64));
309   return DAG.getExtLoad(Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD, DL, VT, Chain, Ptr,
310                             MachinePointerInfo(UndefValue::get(PtrTy)), MemVT,
311                             false, false, MemVT.getSizeInBits() >> 3);
312
313 }
314
315 SDValue SITargetLowering::LowerFormalArguments(
316                                       SDValue Chain,
317                                       CallingConv::ID CallConv,
318                                       bool isVarArg,
319                                       const SmallVectorImpl<ISD::InputArg> &Ins,
320                                       SDLoc DL, SelectionDAG &DAG,
321                                       SmallVectorImpl<SDValue> &InVals) const {
322
323   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
324
325   MachineFunction &MF = DAG.getMachineFunction();
326   FunctionType *FType = MF.getFunction()->getFunctionType();
327   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
328
329   assert(CallConv == CallingConv::C);
330
331   SmallVector<ISD::InputArg, 16> Splits;
332   uint32_t Skipped = 0;
333
334   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
335     const ISD::InputArg &Arg = Ins[i];
336
337     // First check if it's a PS input addr
338     if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
339         !Arg.Flags.isByVal()) {
340
341       assert((PSInputNum <= 15) && "Too many PS inputs!");
342
343       if (!Arg.Used) {
344         // We can savely skip PS inputs
345         Skipped |= 1 << i;
346         ++PSInputNum;
347         continue;
348       }
349
350       Info->PSInputAddr |= 1 << PSInputNum++;
351     }
352
353     // Second split vertices into their elements
354     if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
355       ISD::InputArg NewArg = Arg;
356       NewArg.Flags.setSplit();
357       NewArg.VT = Arg.VT.getVectorElementType();
358
359       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
360       // three or five element vertex only needs three or five registers,
361       // NOT four or eigth.
362       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
363       unsigned NumElements = ParamType->getVectorNumElements();
364
365       for (unsigned j = 0; j != NumElements; ++j) {
366         Splits.push_back(NewArg);
367         NewArg.PartOffset += NewArg.VT.getStoreSize();
368       }
369
370     } else if (Info->getShaderType() != ShaderType::COMPUTE) {
371       Splits.push_back(Arg);
372     }
373   }
374
375   SmallVector<CCValAssign, 16> ArgLocs;
376   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
377                  getTargetMachine(), ArgLocs, *DAG.getContext());
378
379   // At least one interpolation mode must be enabled or else the GPU will hang.
380   if (Info->getShaderType() == ShaderType::PIXEL &&
381       (Info->PSInputAddr & 0x7F) == 0) {
382     Info->PSInputAddr |= 1;
383     CCInfo.AllocateReg(AMDGPU::VGPR0);
384     CCInfo.AllocateReg(AMDGPU::VGPR1);
385   }
386
387   // The pointer to the list of arguments is stored in SGPR0, SGPR1
388   if (Info->getShaderType() == ShaderType::COMPUTE) {
389     CCInfo.AllocateReg(AMDGPU::SGPR0);
390     CCInfo.AllocateReg(AMDGPU::SGPR1);
391     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
392   }
393
394   if (Info->getShaderType() == ShaderType::COMPUTE) {
395     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
396                             Splits);
397   }
398
399   AnalyzeFormalArguments(CCInfo, Splits);
400
401   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
402
403     const ISD::InputArg &Arg = Ins[i];
404     if (Skipped & (1 << i)) {
405       InVals.push_back(DAG.getUNDEF(Arg.VT));
406       continue;
407     }
408
409     CCValAssign &VA = ArgLocs[ArgIdx++];
410     EVT VT = VA.getLocVT();
411
412     if (VA.isMemLoc()) {
413       VT = Ins[i].VT;
414       EVT MemVT = Splits[i].VT;
415       // The first 36 bytes of the input buffer contains information about
416       // thread group and global sizes.
417       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, DAG.getRoot(),
418                                    36 + VA.getLocMemOffset(),
419                                    Ins[i].Flags.isSExt());
420       InVals.push_back(Arg);
421       continue;
422     }
423     assert(VA.isRegLoc() && "Parameter must be in a register!");
424
425     unsigned Reg = VA.getLocReg();
426
427     if (VT == MVT::i64) {
428       // For now assume it is a pointer
429       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
430                                      &AMDGPU::SReg_64RegClass);
431       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
432       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
433       continue;
434     }
435
436     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
437
438     Reg = MF.addLiveIn(Reg, RC);
439     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
440
441     if (Arg.VT.isVector()) {
442
443       // Build a vector from the registers
444       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
445       unsigned NumElements = ParamType->getVectorNumElements();
446
447       SmallVector<SDValue, 4> Regs;
448       Regs.push_back(Val);
449       for (unsigned j = 1; j != NumElements; ++j) {
450         Reg = ArgLocs[ArgIdx++].getLocReg();
451         Reg = MF.addLiveIn(Reg, RC);
452         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
453       }
454
455       // Fill up the missing vector elements
456       NumElements = Arg.VT.getVectorNumElements() - NumElements;
457       for (unsigned j = 0; j != NumElements; ++j)
458         Regs.push_back(DAG.getUNDEF(VT));
459
460       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
461       continue;
462     }
463
464     InVals.push_back(Val);
465   }
466   return Chain;
467 }
468
469 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
470     MachineInstr * MI, MachineBasicBlock * BB) const {
471
472   MachineBasicBlock::iterator I = *MI;
473   const SIInstrInfo *TII =
474     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
475   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
476
477   switch (MI->getOpcode()) {
478   default:
479     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
480   case AMDGPU::BRANCH: return BB;
481   case AMDGPU::SI_ADDR64_RSRC: {
482     unsigned SuperReg = MI->getOperand(0).getReg();
483     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
484     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
485     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
486     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
487     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
488             .addOperand(MI->getOperand(1));
489     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
490             .addImm(0);
491     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
492             .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
493     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
494             .addReg(SubRegHiLo)
495             .addImm(AMDGPU::sub0)
496             .addReg(SubRegHiHi)
497             .addImm(AMDGPU::sub1);
498     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
499             .addReg(SubRegLo)
500             .addImm(AMDGPU::sub0_sub1)
501             .addReg(SubRegHi)
502             .addImm(AMDGPU::sub2_sub3);
503     MI->eraseFromParent();
504     break;
505   }
506   case AMDGPU::V_SUB_F64: {
507     unsigned DestReg = MI->getOperand(0).getReg();
508     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
509       .addImm(0)  // SRC0 modifiers
510       .addReg(MI->getOperand(1).getReg())
511       .addImm(1)  // SRC1 modifiers
512       .addReg(MI->getOperand(2).getReg())
513       .addImm(0)  // SRC2 modifiers
514       .addImm(0)  // src2
515       .addImm(0)  // CLAMP
516       .addImm(0); // OMOD
517     MI->eraseFromParent();
518     break;
519   }
520   case AMDGPU::SI_RegisterStorePseudo: {
521     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
522     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
523     MachineInstrBuilder MIB =
524         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
525                 Reg);
526     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
527       MIB.addOperand(MI->getOperand(i));
528
529     MI->eraseFromParent();
530     break;
531   }
532   case AMDGPU::FABS_SI: {
533     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
534     const SIInstrInfo *TII =
535       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
536     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
537     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
538             Reg)
539             .addImm(0x7fffffff);
540     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_AND_B32_e32),
541             MI->getOperand(0).getReg())
542             .addReg(MI->getOperand(1).getReg())
543             .addReg(Reg);
544     MI->eraseFromParent();
545     break;
546   }
547   case AMDGPU::FNEG_SI: {
548     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
549     const SIInstrInfo *TII =
550       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
551     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
552     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_MOV_B32_e32),
553             Reg)
554             .addImm(0x80000000);
555     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_XOR_B32_e32),
556             MI->getOperand(0).getReg())
557             .addReg(MI->getOperand(1).getReg())
558             .addReg(Reg);
559     MI->eraseFromParent();
560     break;
561   }
562   case AMDGPU::FCLAMP_SI: {
563     const SIInstrInfo *TII =
564       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
565     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F32_e64),
566             MI->getOperand(0).getReg())
567             .addImm(0) // SRC0 modifiers
568             .addOperand(MI->getOperand(1))
569             .addImm(0) // SRC1 modifiers
570             .addImm(0) // SRC1
571             .addImm(1) // CLAMP
572             .addImm(0); // OMOD
573     MI->eraseFromParent();
574   }
575   }
576   return BB;
577 }
578
579 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
580   if (!VT.isVector()) {
581     return MVT::i1;
582   }
583   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
584 }
585
586 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
587   return MVT::i32;
588 }
589
590 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
591   VT = VT.getScalarType();
592
593   if (!VT.isSimple())
594     return false;
595
596   switch (VT.getSimpleVT().SimpleTy) {
597   case MVT::f32:
598     return false; /* There is V_MAD_F32 for f32 */
599   case MVT::f64:
600     return true;
601   default:
602     break;
603   }
604
605   return false;
606 }
607
608 //===----------------------------------------------------------------------===//
609 // Custom DAG Lowering Operations
610 //===----------------------------------------------------------------------===//
611
612 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
613   MachineFunction &MF = DAG.getMachineFunction();
614   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
615   switch (Op.getOpcode()) {
616   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
617   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
618   case ISD::LOAD: {
619     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
620     EVT VT = Op.getValueType();
621
622     // These loads are legal.
623     if (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
624         VT.isVector() && VT.getVectorNumElements() == 2 &&
625         VT.getVectorElementType() == MVT::i32)
626       return SDValue();
627
628     if (Op.getValueType().isVector() &&
629         (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
630          Load->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
631          (Load->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
632           Op.getValueType().getVectorNumElements() > 4))) {
633       return SplitVectorLoad(Op, DAG);
634     } else {
635       SDValue Result = LowerLOAD(Op, DAG);
636       assert((!Result.getNode() ||
637               Result.getNode()->getNumValues() == 2) &&
638              "Load should return a value and a chain");
639       return Result;
640     }
641   }
642
643   case ISD::FSIN:
644   case ISD::FCOS:
645     return LowerTrig(Op, DAG);
646   case ISD::SELECT: return LowerSELECT(Op, DAG);
647   case ISD::FDIV: return LowerFDIV(Op, DAG);
648   case ISD::STORE: return LowerSTORE(Op, DAG);
649   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
650   case ISD::INTRINSIC_WO_CHAIN: {
651     unsigned IntrinsicID =
652                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
653     EVT VT = Op.getValueType();
654     SDLoc DL(Op);
655     //XXX: Hardcoded we only use two to store the pointer to the parameters.
656     unsigned NumUserSGPRs = 2;
657     switch (IntrinsicID) {
658     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
659     case Intrinsic::r600_read_ngroups_x:
660       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 0, false);
661     case Intrinsic::r600_read_ngroups_y:
662       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
663     case Intrinsic::r600_read_ngroups_z:
664       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
665     case Intrinsic::r600_read_global_size_x:
666       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
667     case Intrinsic::r600_read_global_size_y:
668       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
669     case Intrinsic::r600_read_global_size_z:
670       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
671     case Intrinsic::r600_read_local_size_x:
672       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
673     case Intrinsic::r600_read_local_size_y:
674       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
675     case Intrinsic::r600_read_local_size_z:
676       return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
677     case Intrinsic::r600_read_tgid_x:
678       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
679                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
680     case Intrinsic::r600_read_tgid_y:
681       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
682                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
683     case Intrinsic::r600_read_tgid_z:
684       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
685                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
686     case Intrinsic::r600_read_tidig_x:
687       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
688                                   AMDGPU::VGPR0, VT);
689     case Intrinsic::r600_read_tidig_y:
690       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
691                                   AMDGPU::VGPR1, VT);
692     case Intrinsic::r600_read_tidig_z:
693       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
694                                   AMDGPU::VGPR2, VT);
695     case AMDGPUIntrinsic::SI_load_const: {
696       SDValue Ops [] = {
697         Op.getOperand(1),
698         Op.getOperand(2)
699       };
700
701       MachineMemOperand *MMO = MF.getMachineMemOperand(
702           MachinePointerInfo(),
703           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
704           VT.getSizeInBits() / 8, 4);
705       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
706                                      Op->getVTList(), Ops, VT, MMO);
707     }
708     case AMDGPUIntrinsic::SI_sample:
709       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
710     case AMDGPUIntrinsic::SI_sampleb:
711       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
712     case AMDGPUIntrinsic::SI_sampled:
713       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
714     case AMDGPUIntrinsic::SI_samplel:
715       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
716     case AMDGPUIntrinsic::SI_vs_load_input:
717       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
718                          Op.getOperand(1),
719                          Op.getOperand(2),
720                          Op.getOperand(3));
721     }
722   }
723
724   case ISD::INTRINSIC_VOID:
725     SDValue Chain = Op.getOperand(0);
726     unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
727
728     switch (IntrinsicID) {
729       case AMDGPUIntrinsic::SI_tbuffer_store: {
730         SDLoc DL(Op);
731         SDValue Ops [] = {
732           Chain,
733           Op.getOperand(2),
734           Op.getOperand(3),
735           Op.getOperand(4),
736           Op.getOperand(5),
737           Op.getOperand(6),
738           Op.getOperand(7),
739           Op.getOperand(8),
740           Op.getOperand(9),
741           Op.getOperand(10),
742           Op.getOperand(11),
743           Op.getOperand(12),
744           Op.getOperand(13),
745           Op.getOperand(14)
746         };
747         EVT VT = Op.getOperand(3).getValueType();
748
749         MachineMemOperand *MMO = MF.getMachineMemOperand(
750             MachinePointerInfo(),
751             MachineMemOperand::MOStore,
752             VT.getSizeInBits() / 8, 4);
753         return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
754                                        Op->getVTList(), Ops, VT, MMO);
755       }
756       default:
757         break;
758     }
759   }
760   return SDValue();
761 }
762
763 /// \brief Helper function for LowerBRCOND
764 static SDNode *findUser(SDValue Value, unsigned Opcode) {
765
766   SDNode *Parent = Value.getNode();
767   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
768        I != E; ++I) {
769
770     if (I.getUse().get() != Value)
771       continue;
772
773     if (I->getOpcode() == Opcode)
774       return *I;
775   }
776   return nullptr;
777 }
778
779 /// This transforms the control flow intrinsics to get the branch destination as
780 /// last parameter, also switches branch target with BR if the need arise
781 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
782                                       SelectionDAG &DAG) const {
783
784   SDLoc DL(BRCOND);
785
786   SDNode *Intr = BRCOND.getOperand(1).getNode();
787   SDValue Target = BRCOND.getOperand(2);
788   SDNode *BR = nullptr;
789
790   if (Intr->getOpcode() == ISD::SETCC) {
791     // As long as we negate the condition everything is fine
792     SDNode *SetCC = Intr;
793     assert(SetCC->getConstantOperandVal(1) == 1);
794     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
795            ISD::SETNE);
796     Intr = SetCC->getOperand(0).getNode();
797
798   } else {
799     // Get the target from BR if we don't negate the condition
800     BR = findUser(BRCOND, ISD::BR);
801     Target = BR->getOperand(1);
802   }
803
804   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
805
806   // Build the result and
807   SmallVector<EVT, 4> Res;
808   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
809     Res.push_back(Intr->getValueType(i));
810
811   // operands of the new intrinsic call
812   SmallVector<SDValue, 4> Ops;
813   Ops.push_back(BRCOND.getOperand(0));
814   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
815     Ops.push_back(Intr->getOperand(i));
816   Ops.push_back(Target);
817
818   // build the new intrinsic call
819   SDNode *Result = DAG.getNode(
820     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
821     DAG.getVTList(Res), Ops).getNode();
822
823   if (BR) {
824     // Give the branch instruction our target
825     SDValue Ops[] = {
826       BR->getOperand(0),
827       BRCOND.getOperand(2)
828     };
829     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops);
830   }
831
832   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
833
834   // Copy the intrinsic results to registers
835   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
836     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
837     if (!CopyToReg)
838       continue;
839
840     Chain = DAG.getCopyToReg(
841       Chain, DL,
842       CopyToReg->getOperand(1),
843       SDValue(Result, i - 1),
844       SDValue());
845
846     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
847   }
848
849   // Remove the old intrinsic from the chain
850   DAG.ReplaceAllUsesOfValueWith(
851     SDValue(Intr, Intr->getNumValues() - 1),
852     Intr->getOperand(0));
853
854   return Chain;
855 }
856
857 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
858   SDLoc DL(Op);
859   LoadSDNode *Load = cast<LoadSDNode>(Op);
860   SDValue Lowered = AMDGPUTargetLowering::LowerLOAD(Op, DAG);
861   if (Lowered.getNode())
862     return Lowered;
863
864   if (Load->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
865     return SDValue();
866   }
867
868   EVT MemVT = Load->getMemoryVT();
869
870   assert(!MemVT.isVector() && "Private loads should be scalarized");
871   assert(!MemVT.isFloatingPoint() && "FP loads should be promoted to int");
872
873   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Load->getBasePtr(),
874                             DAG.getConstant(2, MVT::i32));
875
876   // FIXME: REGISTER_LOAD should probably have a chain result.
877   SDValue Chain = Load->getChain();
878   SDValue LoLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
879                                Chain, Ptr,
880                                DAG.getTargetConstant(0, MVT::i32),
881                                Op.getOperand(2));
882
883   SDValue Ret = LoLoad.getValue(0);
884   if (MemVT.getSizeInBits() == 64) {
885     // TODO: This needs a test to make sure the right thing is happening with
886     // the chain. That is hard without general function support.
887
888     SDValue IncPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
889                                  DAG.getConstant(1, MVT::i32));
890
891     SDValue HiLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
892                                  Chain, IncPtr,
893                                  DAG.getTargetConstant(0, MVT::i32),
894                                  Op.getOperand(2));
895
896     Ret = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, LoLoad, HiLoad);
897     // Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
898     //                     LoLoad.getValue(1), HiLoad.getValue(1));
899   }
900
901   SDValue Ops[] = {
902     Ret,
903     Chain
904   };
905
906   return DAG.getMergeValues(Ops, DL);
907 }
908
909 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
910                                                const SDValue &Op,
911                                                SelectionDAG &DAG) const {
912   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
913                      Op.getOperand(2),
914                      Op.getOperand(3),
915                      Op.getOperand(4));
916 }
917
918 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
919   if (Op.getValueType() != MVT::i64)
920     return SDValue();
921
922   SDLoc DL(Op);
923   SDValue Cond = Op.getOperand(0);
924
925   SDValue Zero = DAG.getConstant(0, MVT::i32);
926   SDValue One = DAG.getConstant(1, MVT::i32);
927
928   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
929   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
930
931   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
932   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
933
934   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
935
936   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
937   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
938
939   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
940
941   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
942   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
943 }
944
945 // Catch division cases where we can use shortcuts with rcp and rsq
946 // instructions.
947 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
948   SDLoc SL(Op);
949   SDValue LHS = Op.getOperand(0);
950   SDValue RHS = Op.getOperand(1);
951   EVT VT = Op.getValueType();
952   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
953
954   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
955     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
956         CLHS->isExactlyValue(1.0)) {
957       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
958       // the CI documentation has a worst case error of 1 ulp.
959       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
960       // use it as long as we aren't trying to use denormals.
961
962       // 1.0 / sqrt(x) -> rsq(x)
963       //
964       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
965       // error seems really high at 2^29 ULP.
966       if (RHS.getOpcode() == ISD::FSQRT)
967         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
968
969       // 1.0 / x -> rcp(x)
970       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
971     }
972   }
973
974   if (Unsafe) {
975     // Turn into multiply by the reciprocal.
976     // x / y -> x * (1.0 / y)
977     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
978     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
979   }
980
981   return SDValue();
982 }
983
984 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
985   SDValue FastLowered = LowerFastFDIV(Op, DAG);
986   if (FastLowered.getNode())
987     return FastLowered;
988
989   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
990   // selection error for now rather than do something incorrect.
991   if (Subtarget->hasFP32Denormals())
992     return SDValue();
993
994   SDLoc SL(Op);
995   SDValue LHS = Op.getOperand(0);
996   SDValue RHS = Op.getOperand(1);
997
998   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
999
1000   const APFloat K0Val(BitsToFloat(0x6f800000));
1001   const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1002
1003   const APFloat K1Val(BitsToFloat(0x2f800000));
1004   const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1005
1006   const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1007
1008   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1009
1010   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1011
1012   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1013
1014   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1015
1016   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1017
1018   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1019
1020   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1021 }
1022
1023 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1024   return SDValue();
1025 }
1026
1027 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1028   EVT VT = Op.getValueType();
1029
1030   if (VT == MVT::f32)
1031     return LowerFDIV32(Op, DAG);
1032
1033   if (VT == MVT::f64)
1034     return LowerFDIV64(Op, DAG);
1035
1036   llvm_unreachable("Unexpected type for fdiv");
1037 }
1038
1039 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1040   SDLoc DL(Op);
1041   StoreSDNode *Store = cast<StoreSDNode>(Op);
1042   EVT VT = Store->getMemoryVT();
1043
1044   // These stores are legal.
1045   if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1046       VT.isVector() && VT.getVectorNumElements() == 2 &&
1047       VT.getVectorElementType() == MVT::i32)
1048     return SDValue();
1049
1050   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1051   if (Ret.getNode())
1052     return Ret;
1053
1054   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1055       return SplitVectorStore(Op, DAG);
1056
1057   if (VT == MVT::i1)
1058     return DAG.getTruncStore(Store->getChain(), DL,
1059                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1060                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1061
1062   if (Store->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS)
1063     return SDValue();
1064
1065   SDValue Ptr = DAG.getNode(ISD::SRL, DL, MVT::i32, Store->getBasePtr(),
1066                             DAG.getConstant(2, MVT::i32));
1067   SDValue Chain = Store->getChain();
1068   SmallVector<SDValue, 8> Values;
1069
1070   if (Store->isTruncatingStore()) {
1071     unsigned Mask = 0;
1072     if (Store->getMemoryVT() == MVT::i8) {
1073       Mask = 0xff;
1074     } else if (Store->getMemoryVT() == MVT::i16) {
1075       Mask = 0xffff;
1076     }
1077     SDValue Dst = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, MVT::i32,
1078                               Chain, Store->getBasePtr(),
1079                               DAG.getConstant(0, MVT::i32));
1080     SDValue ByteIdx = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getBasePtr(),
1081                                   DAG.getConstant(0x3, MVT::i32));
1082     SDValue ShiftAmt = DAG.getNode(ISD::SHL, DL, MVT::i32, ByteIdx,
1083                                    DAG.getConstant(3, MVT::i32));
1084     SDValue MaskedValue = DAG.getNode(ISD::AND, DL, MVT::i32, Store->getValue(),
1085                                       DAG.getConstant(Mask, MVT::i32));
1086     SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, MVT::i32,
1087                                        MaskedValue, ShiftAmt);
1088     SDValue RotrAmt = DAG.getNode(ISD::SUB, DL, MVT::i32,
1089                                   DAG.getConstant(32, MVT::i32), ShiftAmt);
1090     SDValue DstMask = DAG.getNode(ISD::ROTR, DL, MVT::i32,
1091                                   DAG.getConstant(Mask, MVT::i32),
1092                                   RotrAmt);
1093     Dst = DAG.getNode(ISD::AND, DL, MVT::i32, Dst, DstMask);
1094     Dst = DAG.getNode(ISD::OR, DL, MVT::i32, Dst, ShiftedValue);
1095
1096     Values.push_back(Dst);
1097   } else if (VT == MVT::i64) {
1098     for (unsigned i = 0; i < 2; ++i) {
1099       Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
1100                        Store->getValue(), DAG.getConstant(i, MVT::i32)));
1101     }
1102   } else if (VT == MVT::i128) {
1103     for (unsigned i = 0; i < 2; ++i) {
1104       for (unsigned j = 0; j < 2; ++j) {
1105         Values.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
1106                            DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64,
1107                            Store->getValue(), DAG.getConstant(i, MVT::i32)),
1108                          DAG.getConstant(j, MVT::i32)));
1109       }
1110     }
1111   } else {
1112     Values.push_back(Store->getValue());
1113   }
1114
1115   for (unsigned i = 0; i < Values.size(); ++i) {
1116     SDValue PartPtr = DAG.getNode(ISD::ADD, DL, MVT::i32,
1117                                   Ptr, DAG.getConstant(i, MVT::i32));
1118     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1119                         Chain, Values[i], PartPtr,
1120                         DAG.getTargetConstant(0, MVT::i32));
1121   }
1122   return Chain;
1123 }
1124
1125 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1126   EVT VT = Op.getValueType();
1127   SDValue Arg = Op.getOperand(0);
1128   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1129         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1130           DAG.getConstantFP(0.5 / M_PI, VT)));
1131
1132   switch (Op.getOpcode()) {
1133   case ISD::FCOS:
1134     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1135   case ISD::FSIN:
1136     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1137   default:
1138     llvm_unreachable("Wrong trig opcode");
1139   }
1140 }
1141
1142 //===----------------------------------------------------------------------===//
1143 // Custom DAG optimizations
1144 //===----------------------------------------------------------------------===//
1145
1146 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1147                                                      DAGCombinerInfo &DCI) {
1148   EVT VT = N->getValueType(0);
1149   EVT ScalarVT = VT.getScalarType();
1150   if (ScalarVT != MVT::f32)
1151     return SDValue();
1152
1153   SelectionDAG &DAG = DCI.DAG;
1154   SDLoc DL(N);
1155
1156   SDValue Src = N->getOperand(0);
1157   EVT SrcVT = Src.getValueType();
1158
1159   // TODO: We could try to match extracting the higher bytes, which would be
1160   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1161   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1162   // about in practice.
1163   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1164     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1165       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1166       DCI.AddToWorklist(Cvt.getNode());
1167       return Cvt;
1168     }
1169   }
1170
1171   // We are primarily trying to catch operations on illegal vector types
1172   // before they are expanded.
1173   // For scalars, we can use the more flexible method of checking masked bits
1174   // after legalization.
1175   if (!DCI.isBeforeLegalize() ||
1176       !SrcVT.isVector() ||
1177       SrcVT.getVectorElementType() != MVT::i8) {
1178     return SDValue();
1179   }
1180
1181   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1182
1183   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1184   // size as 4.
1185   unsigned NElts = SrcVT.getVectorNumElements();
1186   if (!SrcVT.isSimple() && NElts != 3)
1187     return SDValue();
1188
1189   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1190   // prevent a mess from expanding to v4i32 and repacking.
1191   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1192     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1193     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1194     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1195
1196     LoadSDNode *Load = cast<LoadSDNode>(Src);
1197     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1198                                      Load->getChain(),
1199                                      Load->getBasePtr(),
1200                                      LoadVT,
1201                                      Load->getMemOperand());
1202
1203     // Make sure successors of the original load stay after it by updating
1204     // them to use the new Chain.
1205     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1206
1207     SmallVector<SDValue, 4> Elts;
1208     if (RegVT.isVector())
1209       DAG.ExtractVectorElements(NewLoad, Elts);
1210     else
1211       Elts.push_back(NewLoad);
1212
1213     SmallVector<SDValue, 4> Ops;
1214
1215     unsigned EltIdx = 0;
1216     for (SDValue Elt : Elts) {
1217       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1218       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1219         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1220         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1221         DCI.AddToWorklist(Cvt.getNode());
1222         Ops.push_back(Cvt);
1223       }
1224
1225       ++EltIdx;
1226     }
1227
1228     assert(Ops.size() == NElts);
1229
1230     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1231   }
1232
1233   return SDValue();
1234 }
1235
1236 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1237                                             DAGCombinerInfo &DCI) const {
1238   SelectionDAG &DAG = DCI.DAG;
1239   SDLoc DL(N);
1240   EVT VT = N->getValueType(0);
1241
1242   switch (N->getOpcode()) {
1243     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1244     case ISD::SELECT_CC: {
1245       ConstantSDNode *True, *False;
1246       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
1247       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1248           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1249           && True->isAllOnesValue()
1250           && False->isNullValue()
1251           && VT == MVT::i1) {
1252         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
1253                            N->getOperand(1), N->getOperand(4));
1254
1255       }
1256       break;
1257     }
1258     case ISD::SETCC: {
1259       SDValue Arg0 = N->getOperand(0);
1260       SDValue Arg1 = N->getOperand(1);
1261       SDValue CC = N->getOperand(2);
1262       ConstantSDNode * C = nullptr;
1263       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1264
1265       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1266       if (VT == MVT::i1
1267           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1268           && Arg0.getOperand(0).getValueType() == MVT::i1
1269           && (C = dyn_cast<ConstantSDNode>(Arg1))
1270           && C->isNullValue()
1271           && CCOp == ISD::SETNE) {
1272         return SimplifySetCC(VT, Arg0.getOperand(0),
1273                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1274       }
1275       break;
1276     }
1277
1278   case AMDGPUISD::CVT_F32_UBYTE0:
1279   case AMDGPUISD::CVT_F32_UBYTE1:
1280   case AMDGPUISD::CVT_F32_UBYTE2:
1281   case AMDGPUISD::CVT_F32_UBYTE3: {
1282     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1283
1284     SDValue Src = N->getOperand(0);
1285     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1286
1287     APInt KnownZero, KnownOne;
1288     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1289                                           !DCI.isBeforeLegalizeOps());
1290     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1291     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1292         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1293       DCI.CommitTargetLoweringOpt(TLO);
1294     }
1295
1296     break;
1297   }
1298
1299   case ISD::UINT_TO_FP: {
1300     return performUCharToFloatCombine(N, DCI);
1301   }
1302   }
1303
1304   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1305 }
1306
1307 /// \brief Test if RegClass is one of the VSrc classes
1308 static bool isVSrc(unsigned RegClass) {
1309   return AMDGPU::VSrc_32RegClassID == RegClass ||
1310          AMDGPU::VSrc_64RegClassID == RegClass;
1311 }
1312
1313 /// \brief Test if RegClass is one of the SSrc classes
1314 static bool isSSrc(unsigned RegClass) {
1315   return AMDGPU::SSrc_32RegClassID == RegClass ||
1316          AMDGPU::SSrc_64RegClassID == RegClass;
1317 }
1318
1319 /// \brief Analyze the possible immediate value Op
1320 ///
1321 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1322 /// and the immediate value if it's a literal immediate
1323 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1324
1325   union {
1326     int32_t I;
1327     float F;
1328   } Imm;
1329
1330   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1331     if (Node->getZExtValue() >> 32) {
1332         return -1;
1333     }
1334     Imm.I = Node->getSExtValue();
1335   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1336     if (N->getValueType(0) != MVT::f32)
1337       return -1;
1338     Imm.F = Node->getValueAPF().convertToFloat();
1339   } else
1340     return -1; // It isn't an immediate
1341
1342   if ((Imm.I >= -16 && Imm.I <= 64) ||
1343       Imm.F == 0.5f || Imm.F == -0.5f ||
1344       Imm.F == 1.0f || Imm.F == -1.0f ||
1345       Imm.F == 2.0f || Imm.F == -2.0f ||
1346       Imm.F == 4.0f || Imm.F == -4.0f)
1347     return 0; // It's an inline immediate
1348
1349   return Imm.I; // It's a literal immediate
1350 }
1351
1352 /// \brief Try to fold an immediate directly into an instruction
1353 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1354                                bool &ScalarSlotUsed) const {
1355
1356   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1357   const SIInstrInfo *TII =
1358     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1359   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1360     return false;
1361
1362   const SDValue &Op = Mov->getOperand(0);
1363   int32_t Value = analyzeImmediate(Op.getNode());
1364   if (Value == -1) {
1365     // Not an immediate at all
1366     return false;
1367
1368   } else if (Value == 0) {
1369     // Inline immediates can always be fold
1370     Operand = Op;
1371     return true;
1372
1373   } else if (Value == Immediate) {
1374     // Already fold literal immediate
1375     Operand = Op;
1376     return true;
1377
1378   } else if (!ScalarSlotUsed && !Immediate) {
1379     // Fold this literal immediate
1380     ScalarSlotUsed = true;
1381     Immediate = Value;
1382     Operand = Op;
1383     return true;
1384
1385   }
1386
1387   return false;
1388 }
1389
1390 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1391                                    SelectionDAG &DAG, const SDValue &Op) const {
1392   const SIInstrInfo *TII =
1393     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1394   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1395
1396   if (!Op->isMachineOpcode()) {
1397     switch(Op->getOpcode()) {
1398     case ISD::CopyFromReg: {
1399       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1400       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1401       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1402         return MRI.getRegClass(Reg);
1403       }
1404       return TRI.getPhysRegClass(Reg);
1405     }
1406     default:  return nullptr;
1407     }
1408   }
1409   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1410   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1411   if (OpClassID != -1) {
1412     return TRI.getRegClass(OpClassID);
1413   }
1414   switch(Op.getMachineOpcode()) {
1415   case AMDGPU::COPY_TO_REGCLASS:
1416     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1417     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1418
1419     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1420     // class, then the register class for the value could be either a
1421     // VReg or and SReg.  In order to get a more accurate
1422     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1423         OpClassID == AMDGPU::VSrc_64RegClassID) {
1424       return getRegClassForNode(DAG, Op.getOperand(0));
1425     }
1426     return TRI.getRegClass(OpClassID);
1427   case AMDGPU::EXTRACT_SUBREG: {
1428     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1429     const TargetRegisterClass *SuperClass =
1430       getRegClassForNode(DAG, Op.getOperand(0));
1431     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1432   }
1433   case AMDGPU::REG_SEQUENCE:
1434     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1435     return TRI.getRegClass(
1436       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1437   default:
1438     return getRegClassFor(Op.getSimpleValueType());
1439   }
1440 }
1441
1442 /// \brief Does "Op" fit into register class "RegClass" ?
1443 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1444                                     unsigned RegClass) const {
1445   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1446   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1447   if (!RC) {
1448     return false;
1449   }
1450   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1451 }
1452
1453 /// \brief Make sure that we don't exeed the number of allowed scalars
1454 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1455                                        unsigned RegClass,
1456                                        bool &ScalarSlotUsed) const {
1457
1458   // First map the operands register class to a destination class
1459   if (RegClass == AMDGPU::VSrc_32RegClassID)
1460     RegClass = AMDGPU::VReg_32RegClassID;
1461   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1462     RegClass = AMDGPU::VReg_64RegClassID;
1463   else
1464     return;
1465
1466   // Nothing to do if they fit naturally
1467   if (fitsRegClass(DAG, Operand, RegClass))
1468     return;
1469
1470   // If the scalar slot isn't used yet use it now
1471   if (!ScalarSlotUsed) {
1472     ScalarSlotUsed = true;
1473     return;
1474   }
1475
1476   // This is a conservative aproach. It is possible that we can't determine the
1477   // correct register class and copy too often, but better safe than sorry.
1478   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1479   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1480                                     Operand.getValueType(), Operand, RC);
1481   Operand = SDValue(Node, 0);
1482 }
1483
1484 /// \returns true if \p Node's operands are different from the SDValue list
1485 /// \p Ops
1486 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1487   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1488     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1489       return true;
1490     }
1491   }
1492   return false;
1493 }
1494
1495 /// \brief Try to fold the Nodes operands into the Node
1496 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1497                                        SelectionDAG &DAG) const {
1498
1499   // Original encoding (either e32 or e64)
1500   int Opcode = Node->getMachineOpcode();
1501   const SIInstrInfo *TII =
1502     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1503   const MCInstrDesc *Desc = &TII->get(Opcode);
1504
1505   unsigned NumDefs = Desc->getNumDefs();
1506   unsigned NumOps = Desc->getNumOperands();
1507
1508   // Commuted opcode if available
1509   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1510   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1511
1512   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1513   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1514
1515   // e64 version if available, -1 otherwise
1516   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1517   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1518   int InputModifiers[3] = {0};
1519
1520   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1521
1522   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1523   bool HaveVSrc = false, HaveSSrc = false;
1524
1525   // First figure out what we already have in this instruction.
1526   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1527        i != e && Op < NumOps; ++i, ++Op) {
1528
1529     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1530     if (isVSrc(RegClass))
1531       HaveVSrc = true;
1532     else if (isSSrc(RegClass))
1533       HaveSSrc = true;
1534     else
1535       continue;
1536
1537     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1538     if (Imm != -1 && Imm != 0) {
1539       // Literal immediate
1540       Immediate = Imm;
1541     }
1542   }
1543
1544   // If we neither have VSrc nor SSrc, it makes no sense to continue.
1545   if (!HaveVSrc && !HaveSSrc)
1546     return Node;
1547
1548   // No scalar allowed when we have both VSrc and SSrc
1549   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1550
1551   // Second go over the operands and try to fold them
1552   std::vector<SDValue> Ops;
1553   bool Promote2e64 = false;
1554   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1555        i != e && Op < NumOps; ++i, ++Op) {
1556
1557     const SDValue &Operand = Node->getOperand(i);
1558     Ops.push_back(Operand);
1559
1560     // Already folded immediate?
1561     if (isa<ConstantSDNode>(Operand.getNode()) ||
1562         isa<ConstantFPSDNode>(Operand.getNode()))
1563       continue;
1564
1565     // Is this a VSrc or SSrc operand?
1566     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1567     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1568       // Try to fold the immediates
1569       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1570         // Folding didn't work, make sure we don't hit the SReg limit.
1571         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1572       }
1573       continue;
1574     }
1575
1576     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1577
1578       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1579       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1580
1581       // Test if it makes sense to swap operands
1582       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1583           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1584            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1585
1586         // Swap commutable operands
1587         std::swap(Ops[0], Ops[1]);
1588
1589         Desc = DescRev;
1590         DescRev = nullptr;
1591         continue;
1592       }
1593     }
1594
1595     if (Immediate)
1596       continue;
1597
1598     if (DescE64) {
1599       // Test if it makes sense to switch to e64 encoding
1600       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1601       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1602         continue;
1603
1604       int32_t TmpImm = -1;
1605       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1606           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1607            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1608
1609         // Switch to e64 encoding
1610         Immediate = -1;
1611         Promote2e64 = true;
1612         Desc = DescE64;
1613         DescE64 = nullptr;
1614       }
1615     }
1616
1617     if (!DescE64 && !Promote2e64)
1618       continue;
1619     if (!Operand.isMachineOpcode())
1620       continue;
1621     if (Operand.getMachineOpcode() == AMDGPU::FNEG_SI) {
1622       Ops.pop_back();
1623       Ops.push_back(Operand.getOperand(0));
1624       InputModifiers[i] = 1;
1625       Promote2e64 = true;
1626       if (!DescE64)
1627         continue;
1628       Desc = DescE64;
1629       DescE64 = nullptr;
1630     }
1631     else if (Operand.getMachineOpcode() == AMDGPU::FABS_SI) {
1632       Ops.pop_back();
1633       Ops.push_back(Operand.getOperand(0));
1634       InputModifiers[i] = 2;
1635       Promote2e64 = true;
1636       if (!DescE64)
1637         continue;
1638       Desc = DescE64;
1639       DescE64 = nullptr;
1640     }
1641   }
1642
1643   if (Promote2e64) {
1644     std::vector<SDValue> OldOps(Ops);
1645     Ops.clear();
1646     for (unsigned i = 0; i < OldOps.size(); ++i) {
1647       // src_modifier
1648       Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1649       Ops.push_back(OldOps[i]);
1650     }
1651     // Add the modifier flags while promoting
1652     for (unsigned i = 0; i < 2; ++i)
1653       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1654   }
1655
1656   // Add optional chain and glue
1657   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1658     Ops.push_back(Node->getOperand(i));
1659
1660   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1661   // this case a brand new node is always be created, even if the operands
1662   // are the same as before.  So, manually check if anything has been changed.
1663   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1664     return Node;
1665   }
1666
1667   // Create a complete new instruction
1668   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1669 }
1670
1671 /// \brief Helper function for adjustWritemask
1672 static unsigned SubIdx2Lane(unsigned Idx) {
1673   switch (Idx) {
1674   default: return 0;
1675   case AMDGPU::sub0: return 0;
1676   case AMDGPU::sub1: return 1;
1677   case AMDGPU::sub2: return 2;
1678   case AMDGPU::sub3: return 3;
1679   }
1680 }
1681
1682 /// \brief Adjust the writemask of MIMG instructions
1683 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1684                                        SelectionDAG &DAG) const {
1685   SDNode *Users[4] = { };
1686   unsigned Lane = 0;
1687   unsigned OldDmask = Node->getConstantOperandVal(0);
1688   unsigned NewDmask = 0;
1689
1690   // Try to figure out the used register components
1691   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1692        I != E; ++I) {
1693
1694     // Abort if we can't understand the usage
1695     if (!I->isMachineOpcode() ||
1696         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1697       return;
1698
1699     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1700     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1701     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1702     // set, etc.
1703     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1704
1705     // Set which texture component corresponds to the lane.
1706     unsigned Comp;
1707     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1708       assert(Dmask);
1709       Comp = countTrailingZeros(Dmask);
1710       Dmask &= ~(1 << Comp);
1711     }
1712
1713     // Abort if we have more than one user per component
1714     if (Users[Lane])
1715       return;
1716
1717     Users[Lane] = *I;
1718     NewDmask |= 1 << Comp;
1719   }
1720
1721   // Abort if there's no change
1722   if (NewDmask == OldDmask)
1723     return;
1724
1725   // Adjust the writemask in the node
1726   std::vector<SDValue> Ops;
1727   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1728   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1729     Ops.push_back(Node->getOperand(i));
1730   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1731
1732   // If we only got one lane, replace it with a copy
1733   // (if NewDmask has only one bit set...)
1734   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1735     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1736     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1737                                       SDLoc(), Users[Lane]->getValueType(0),
1738                                       SDValue(Node, 0), RC);
1739     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1740     return;
1741   }
1742
1743   // Update the users of the node with the new indices
1744   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1745
1746     SDNode *User = Users[i];
1747     if (!User)
1748       continue;
1749
1750     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1751     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1752
1753     switch (Idx) {
1754     default: break;
1755     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1756     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1757     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1758     }
1759   }
1760 }
1761
1762 /// \brief Fold the instructions after selecting them.
1763 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1764                                           SelectionDAG &DAG) const {
1765   const SIInstrInfo *TII =
1766       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1767   Node = AdjustRegClass(Node, DAG);
1768
1769   if (TII->isMIMG(Node->getMachineOpcode()))
1770     adjustWritemask(Node, DAG);
1771
1772   return foldOperands(Node, DAG);
1773 }
1774
1775 /// \brief Assign the register class depending on the number of
1776 /// bits set in the writemask
1777 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1778                                                      SDNode *Node) const {
1779   const SIInstrInfo *TII =
1780       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1781   if (!TII->isMIMG(MI->getOpcode()))
1782     return;
1783
1784   unsigned VReg = MI->getOperand(0).getReg();
1785   unsigned Writemask = MI->getOperand(1).getImm();
1786   unsigned BitsSet = 0;
1787   for (unsigned i = 0; i < 4; ++i)
1788     BitsSet += Writemask & (1 << i) ? 1 : 0;
1789
1790   const TargetRegisterClass *RC;
1791   switch (BitsSet) {
1792   default: return;
1793   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1794   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1795   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1796   }
1797
1798   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1799   MI->setDesc(TII->get(NewOpcode));
1800   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1801   MRI.setRegClass(VReg, RC);
1802 }
1803
1804 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1805                                                 SelectionDAG &DAG) const {
1806
1807   SDLoc DL(N);
1808   unsigned NewOpcode = N->getMachineOpcode();
1809
1810   switch (N->getMachineOpcode()) {
1811   default: return N;
1812   case AMDGPU::S_LOAD_DWORD_IMM:
1813     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1814     // Fall-through
1815   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1816     if (NewOpcode == N->getMachineOpcode()) {
1817       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1818     }
1819     // Fall-through
1820   case AMDGPU::S_LOAD_DWORDX4_IMM:
1821   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1822     if (NewOpcode == N->getMachineOpcode()) {
1823       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1824     }
1825     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1826       return N;
1827     }
1828     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1829     SDValue Ops[] = {
1830       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1831                                  DAG.getConstant(0, MVT::i64)), 0),
1832       N->getOperand(0),
1833       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1834     };
1835     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1836   }
1837   }
1838 }
1839
1840 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1841                                                const TargetRegisterClass *RC,
1842                                                unsigned Reg, EVT VT) const {
1843   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1844
1845   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1846                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1847 }