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