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