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