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