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