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