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