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