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