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