R600/SI: Make sure SCRATCH_WAVE_OFFSET is added as Live-In to the function
[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       InVals.push_back(Arg);
508       continue;
509     }
510     assert(VA.isRegLoc() && "Parameter must be in a register!");
511
512     unsigned Reg = VA.getLocReg();
513
514     if (VT == MVT::i64) {
515       // For now assume it is a pointer
516       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
517                                      &AMDGPU::SReg_64RegClass);
518       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
519       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
520       continue;
521     }
522
523     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
524
525     Reg = MF.addLiveIn(Reg, RC);
526     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
527
528     if (Arg.VT.isVector()) {
529
530       // Build a vector from the registers
531       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
532       unsigned NumElements = ParamType->getVectorNumElements();
533
534       SmallVector<SDValue, 4> Regs;
535       Regs.push_back(Val);
536       for (unsigned j = 1; j != NumElements; ++j) {
537         Reg = ArgLocs[ArgIdx++].getLocReg();
538         Reg = MF.addLiveIn(Reg, RC);
539         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
540       }
541
542       // Fill up the missing vector elements
543       NumElements = Arg.VT.getVectorNumElements() - NumElements;
544       for (unsigned j = 0; j != NumElements; ++j)
545         Regs.push_back(DAG.getUNDEF(VT));
546
547       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
548       continue;
549     }
550
551     InVals.push_back(Val);
552   }
553   return Chain;
554 }
555
556 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
557     MachineInstr * MI, MachineBasicBlock * BB) const {
558
559   MachineBasicBlock::iterator I = *MI;
560   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
561       getTargetMachine().getSubtargetImpl()->getInstrInfo());
562   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
563
564   switch (MI->getOpcode()) {
565   default:
566     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
567   case AMDGPU::BRANCH: return BB;
568   case AMDGPU::SI_ADDR64_RSRC: {
569     unsigned SuperReg = MI->getOperand(0).getReg();
570     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
571     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
572     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
573     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
574     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
575             .addOperand(MI->getOperand(1));
576     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
577             .addImm(0);
578     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
579             .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
580     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
581             .addReg(SubRegHiLo)
582             .addImm(AMDGPU::sub0)
583             .addReg(SubRegHiHi)
584             .addImm(AMDGPU::sub1);
585     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
586             .addReg(SubRegLo)
587             .addImm(AMDGPU::sub0_sub1)
588             .addReg(SubRegHi)
589             .addImm(AMDGPU::sub2_sub3);
590     MI->eraseFromParent();
591     break;
592   }
593   case AMDGPU::SI_BUFFER_RSRC: {
594     unsigned SuperReg = MI->getOperand(0).getReg();
595     unsigned Args[4];
596     for (unsigned i = 0, e = 4; i < e; ++i) {
597       MachineOperand &Arg = MI->getOperand(i + 1);
598
599       if (Arg.isReg()) {
600         Args[i] = Arg.getReg();
601         continue;
602       }
603
604       assert(Arg.isImm());
605       unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
606       BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), Reg)
607               .addImm(Arg.getImm());
608       Args[i] = Reg;
609     }
610     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE),
611             SuperReg)
612             .addReg(Args[0])
613             .addImm(AMDGPU::sub0)
614             .addReg(Args[1])
615             .addImm(AMDGPU::sub1)
616             .addReg(Args[2])
617             .addImm(AMDGPU::sub2)
618             .addReg(Args[3])
619             .addImm(AMDGPU::sub3);
620     MI->eraseFromParent();
621     break;
622   }
623   case AMDGPU::V_SUB_F64: {
624     unsigned DestReg = MI->getOperand(0).getReg();
625     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64), DestReg)
626       .addImm(0)  // SRC0 modifiers
627       .addReg(MI->getOperand(1).getReg())
628       .addImm(1)  // SRC1 modifiers
629       .addReg(MI->getOperand(2).getReg())
630       .addImm(0)  // CLAMP
631       .addImm(0); // OMOD
632     MI->eraseFromParent();
633     break;
634   }
635   case AMDGPU::SI_RegisterStorePseudo: {
636     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
637     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
638     MachineInstrBuilder MIB =
639         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
640                 Reg);
641     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
642       MIB.addOperand(MI->getOperand(i));
643
644     MI->eraseFromParent();
645     break;
646   }
647   case AMDGPU::FCLAMP_SI: {
648     const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
649         getTargetMachine().getSubtargetImpl()->getInstrInfo());
650     DebugLoc DL = MI->getDebugLoc();
651     unsigned DestReg = MI->getOperand(0).getReg();
652     BuildMI(*BB, I, DL, TII->get(AMDGPU::V_ADD_F32_e64), DestReg)
653       .addImm(0) // SRC0 modifiers
654       .addOperand(MI->getOperand(1))
655       .addImm(0) // SRC1 modifiers
656       .addImm(0) // SRC1
657       .addImm(1) // CLAMP
658       .addImm(0); // OMOD
659     MI->eraseFromParent();
660   }
661   }
662   return BB;
663 }
664
665 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
666   if (!VT.isVector()) {
667     return MVT::i1;
668   }
669   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
670 }
671
672 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
673   return MVT::i32;
674 }
675
676 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
677   VT = VT.getScalarType();
678
679   if (!VT.isSimple())
680     return false;
681
682   switch (VT.getSimpleVT().SimpleTy) {
683   case MVT::f32:
684     return false; /* There is V_MAD_F32 for f32 */
685   case MVT::f64:
686     return true;
687   default:
688     break;
689   }
690
691   return false;
692 }
693
694 //===----------------------------------------------------------------------===//
695 // Custom DAG Lowering Operations
696 //===----------------------------------------------------------------------===//
697
698 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
699   switch (Op.getOpcode()) {
700   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
701   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
702   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
703   case ISD::LOAD: {
704     SDValue Result = LowerLOAD(Op, DAG);
705     assert((!Result.getNode() ||
706             Result.getNode()->getNumValues() == 2) &&
707            "Load should return a value and a chain");
708     return Result;
709   }
710
711   case ISD::FSIN:
712   case ISD::FCOS:
713     return LowerTrig(Op, DAG);
714   case ISD::SELECT: return LowerSELECT(Op, DAG);
715   case ISD::FDIV: return LowerFDIV(Op, DAG);
716   case ISD::STORE: return LowerSTORE(Op, DAG);
717   case ISD::GlobalAddress: {
718     MachineFunction &MF = DAG.getMachineFunction();
719     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
720     return LowerGlobalAddress(MFI, Op, DAG);
721   }
722   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
723   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
724   }
725   return SDValue();
726 }
727
728 /// \brief Helper function for LowerBRCOND
729 static SDNode *findUser(SDValue Value, unsigned Opcode) {
730
731   SDNode *Parent = Value.getNode();
732   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
733        I != E; ++I) {
734
735     if (I.getUse().get() != Value)
736       continue;
737
738     if (I->getOpcode() == Opcode)
739       return *I;
740   }
741   return nullptr;
742 }
743
744 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
745
746   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
747   unsigned FrameIndex = FINode->getIndex();
748
749   return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
750 }
751
752 /// This transforms the control flow intrinsics to get the branch destination as
753 /// last parameter, also switches branch target with BR if the need arise
754 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
755                                       SelectionDAG &DAG) const {
756
757   SDLoc DL(BRCOND);
758
759   SDNode *Intr = BRCOND.getOperand(1).getNode();
760   SDValue Target = BRCOND.getOperand(2);
761   SDNode *BR = nullptr;
762
763   if (Intr->getOpcode() == ISD::SETCC) {
764     // As long as we negate the condition everything is fine
765     SDNode *SetCC = Intr;
766     assert(SetCC->getConstantOperandVal(1) == 1);
767     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
768            ISD::SETNE);
769     Intr = SetCC->getOperand(0).getNode();
770
771   } else {
772     // Get the target from BR if we don't negate the condition
773     BR = findUser(BRCOND, ISD::BR);
774     Target = BR->getOperand(1);
775   }
776
777   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
778
779   // Build the result and
780   SmallVector<EVT, 4> Res;
781   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
782     Res.push_back(Intr->getValueType(i));
783
784   // operands of the new intrinsic call
785   SmallVector<SDValue, 4> Ops;
786   Ops.push_back(BRCOND.getOperand(0));
787   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
788     Ops.push_back(Intr->getOperand(i));
789   Ops.push_back(Target);
790
791   // build the new intrinsic call
792   SDNode *Result = DAG.getNode(
793     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
794     DAG.getVTList(Res), Ops).getNode();
795
796   if (BR) {
797     // Give the branch instruction our target
798     SDValue Ops[] = {
799       BR->getOperand(0),
800       BRCOND.getOperand(2)
801     };
802     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
803     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
804     BR = NewBR.getNode();
805   }
806
807   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
808
809   // Copy the intrinsic results to registers
810   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
811     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
812     if (!CopyToReg)
813       continue;
814
815     Chain = DAG.getCopyToReg(
816       Chain, DL,
817       CopyToReg->getOperand(1),
818       SDValue(Result, i - 1),
819       SDValue());
820
821     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
822   }
823
824   // Remove the old intrinsic from the chain
825   DAG.ReplaceAllUsesOfValueWith(
826     SDValue(Intr, Intr->getNumValues() - 1),
827     Intr->getOperand(0));
828
829   return Chain;
830 }
831
832 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
833                                              SDValue Op,
834                                              SelectionDAG &DAG) const {
835   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
836
837   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
838     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
839
840   SDLoc DL(GSD);
841   const GlobalValue *GV = GSD->getGlobal();
842   MVT PtrVT = getPointerTy(GSD->getAddressSpace());
843
844   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
845   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
846
847   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
848                               DAG.getConstant(0, MVT::i32));
849   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
850                               DAG.getConstant(1, MVT::i32));
851
852   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
853                            PtrLo, GA);
854   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
855                            PtrHi, DAG.getConstant(0, MVT::i32),
856                            SDValue(Lo.getNode(), 1));
857   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
858 }
859
860 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
861                                                   SelectionDAG &DAG) const {
862   MachineFunction &MF = DAG.getMachineFunction();
863   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
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(), 0, false);
872   case Intrinsic::r600_read_ngroups_y:
873     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4, false);
874   case Intrinsic::r600_read_ngroups_z:
875     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 8, false);
876   case Intrinsic::r600_read_global_size_x:
877     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 12, false);
878   case Intrinsic::r600_read_global_size_y:
879     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 16, false);
880   case Intrinsic::r600_read_global_size_z:
881     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 20, false);
882   case Intrinsic::r600_read_local_size_x:
883     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 24, false);
884   case Intrinsic::r600_read_local_size_y:
885     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 28, false);
886   case Intrinsic::r600_read_local_size_z:
887     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 32, false);
888   case Intrinsic::r600_read_tgid_x:
889     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
890       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 0), VT);
891   case Intrinsic::r600_read_tgid_y:
892     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
893       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 1), VT);
894   case Intrinsic::r600_read_tgid_z:
895     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
896       AMDGPU::SReg_32RegClass.getRegister(MFI->NumUserSGPRs + 2), VT);
897   case Intrinsic::r600_read_tidig_x:
898     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
899                                 AMDGPU::VGPR0, VT);
900   case Intrinsic::r600_read_tidig_y:
901     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
902                                 AMDGPU::VGPR1, VT);
903   case Intrinsic::r600_read_tidig_z:
904     return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
905                                 AMDGPU::VGPR2, VT);
906   case AMDGPUIntrinsic::SI_load_const: {
907     SDValue Ops[] = {
908       Op.getOperand(1),
909       Op.getOperand(2)
910     };
911
912     MachineMemOperand *MMO = MF.getMachineMemOperand(
913       MachinePointerInfo(),
914       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
915       VT.getStoreSize(), 4);
916     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
917                                    Op->getVTList(), Ops, VT, MMO);
918   }
919   case AMDGPUIntrinsic::SI_sample:
920     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
921   case AMDGPUIntrinsic::SI_sampleb:
922     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
923   case AMDGPUIntrinsic::SI_sampled:
924     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
925   case AMDGPUIntrinsic::SI_samplel:
926     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
927   case AMDGPUIntrinsic::SI_vs_load_input:
928     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
929                        Op.getOperand(1),
930                        Op.getOperand(2),
931                        Op.getOperand(3));
932   default:
933     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
934   }
935 }
936
937 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
938                                               SelectionDAG &DAG) const {
939   MachineFunction &MF = DAG.getMachineFunction();
940   SDValue Chain = Op.getOperand(0);
941   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
942
943   switch (IntrinsicID) {
944   case AMDGPUIntrinsic::SI_tbuffer_store: {
945     SDLoc DL(Op);
946     SDValue Ops[] = {
947       Chain,
948       Op.getOperand(2),
949       Op.getOperand(3),
950       Op.getOperand(4),
951       Op.getOperand(5),
952       Op.getOperand(6),
953       Op.getOperand(7),
954       Op.getOperand(8),
955       Op.getOperand(9),
956       Op.getOperand(10),
957       Op.getOperand(11),
958       Op.getOperand(12),
959       Op.getOperand(13),
960       Op.getOperand(14)
961     };
962
963     EVT VT = Op.getOperand(3).getValueType();
964
965     MachineMemOperand *MMO = MF.getMachineMemOperand(
966       MachinePointerInfo(),
967       MachineMemOperand::MOStore,
968       VT.getStoreSize(), 4);
969     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
970                                    Op->getVTList(), Ops, VT, MMO);
971   }
972   default:
973     return SDValue();
974   }
975 }
976
977 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
978   SDLoc DL(Op);
979   LoadSDNode *Load = cast<LoadSDNode>(Op);
980
981   if (Op.getValueType().isVector()) {
982     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
983            "Custom lowering for non-i32 vectors hasn't been implemented.");
984     unsigned NumElements = Op.getValueType().getVectorNumElements();
985     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
986     switch (Load->getAddressSpace()) {
987       default: break;
988       case AMDGPUAS::GLOBAL_ADDRESS:
989       case AMDGPUAS::PRIVATE_ADDRESS:
990         // v4 loads are supported for private and global memory.
991         if (NumElements <= 4)
992           break;
993         // fall-through
994       case AMDGPUAS::LOCAL_ADDRESS:
995         return ScalarizeVectorLoad(Op, DAG);
996     }
997   }
998
999   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1000 }
1001
1002 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1003                                                const SDValue &Op,
1004                                                SelectionDAG &DAG) const {
1005   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1006                      Op.getOperand(2),
1007                      Op.getOperand(3),
1008                      Op.getOperand(4));
1009 }
1010
1011 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1012   if (Op.getValueType() != MVT::i64)
1013     return SDValue();
1014
1015   SDLoc DL(Op);
1016   SDValue Cond = Op.getOperand(0);
1017
1018   SDValue Zero = DAG.getConstant(0, MVT::i32);
1019   SDValue One = DAG.getConstant(1, MVT::i32);
1020
1021   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1022   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1023
1024   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1025   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1026
1027   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1028
1029   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1030   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1031
1032   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1033
1034   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1035   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1036 }
1037
1038 // Catch division cases where we can use shortcuts with rcp and rsq
1039 // instructions.
1040 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1041   SDLoc SL(Op);
1042   SDValue LHS = Op.getOperand(0);
1043   SDValue RHS = Op.getOperand(1);
1044   EVT VT = Op.getValueType();
1045   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1046
1047   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1048     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1049         CLHS->isExactlyValue(1.0)) {
1050       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1051       // the CI documentation has a worst case error of 1 ulp.
1052       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1053       // use it as long as we aren't trying to use denormals.
1054
1055       // 1.0 / sqrt(x) -> rsq(x)
1056       //
1057       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1058       // error seems really high at 2^29 ULP.
1059       if (RHS.getOpcode() == ISD::FSQRT)
1060         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1061
1062       // 1.0 / x -> rcp(x)
1063       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1064     }
1065   }
1066
1067   if (Unsafe) {
1068     // Turn into multiply by the reciprocal.
1069     // x / y -> x * (1.0 / y)
1070     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1071     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1072   }
1073
1074   return SDValue();
1075 }
1076
1077 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1078   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1079   if (FastLowered.getNode())
1080     return FastLowered;
1081
1082   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1083   // selection error for now rather than do something incorrect.
1084   if (Subtarget->hasFP32Denormals())
1085     return SDValue();
1086
1087   SDLoc SL(Op);
1088   SDValue LHS = Op.getOperand(0);
1089   SDValue RHS = Op.getOperand(1);
1090
1091   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1092
1093   const APFloat K0Val(BitsToFloat(0x6f800000));
1094   const SDValue K0 = DAG.getConstantFP(K0Val, MVT::f32);
1095
1096   const APFloat K1Val(BitsToFloat(0x2f800000));
1097   const SDValue K1 = DAG.getConstantFP(K1Val, MVT::f32);
1098
1099   const SDValue One = DAG.getTargetConstantFP(1.0, MVT::f32);
1100
1101   EVT SetCCVT = getSetCCResultType(*DAG.getContext(), MVT::f32);
1102
1103   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1104
1105   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1106
1107   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1108
1109   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1110
1111   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1112
1113   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1114 }
1115
1116 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1117   return SDValue();
1118 }
1119
1120 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1121   EVT VT = Op.getValueType();
1122
1123   if (VT == MVT::f32)
1124     return LowerFDIV32(Op, DAG);
1125
1126   if (VT == MVT::f64)
1127     return LowerFDIV64(Op, DAG);
1128
1129   llvm_unreachable("Unexpected type for fdiv");
1130 }
1131
1132 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1133   SDLoc DL(Op);
1134   StoreSDNode *Store = cast<StoreSDNode>(Op);
1135   EVT VT = Store->getMemoryVT();
1136
1137   // These stores are legal.
1138   if (Store->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
1139       VT.isVector() && VT.getVectorNumElements() == 2 &&
1140       VT.getVectorElementType() == MVT::i32)
1141     return SDValue();
1142
1143   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1144     if (VT.isVector() && VT.getVectorNumElements() > 4)
1145       return ScalarizeVectorStore(Op, DAG);
1146     return SDValue();
1147   }
1148
1149   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1150   if (Ret.getNode())
1151     return Ret;
1152
1153   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1154       return ScalarizeVectorStore(Op, DAG);
1155
1156   if (VT == MVT::i1)
1157     return DAG.getTruncStore(Store->getChain(), DL,
1158                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1159                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1160
1161   return SDValue();
1162 }
1163
1164 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1165   EVT VT = Op.getValueType();
1166   SDValue Arg = Op.getOperand(0);
1167   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
1168         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
1169           DAG.getConstantFP(0.5 / M_PI, VT)));
1170
1171   switch (Op.getOpcode()) {
1172   case ISD::FCOS:
1173     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1174   case ISD::FSIN:
1175     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1176   default:
1177     llvm_unreachable("Wrong trig opcode");
1178   }
1179 }
1180
1181 //===----------------------------------------------------------------------===//
1182 // Custom DAG optimizations
1183 //===----------------------------------------------------------------------===//
1184
1185 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1186                                                      DAGCombinerInfo &DCI) {
1187   EVT VT = N->getValueType(0);
1188   EVT ScalarVT = VT.getScalarType();
1189   if (ScalarVT != MVT::f32)
1190     return SDValue();
1191
1192   SelectionDAG &DAG = DCI.DAG;
1193   SDLoc DL(N);
1194
1195   SDValue Src = N->getOperand(0);
1196   EVT SrcVT = Src.getValueType();
1197
1198   // TODO: We could try to match extracting the higher bytes, which would be
1199   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1200   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1201   // about in practice.
1202   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1203     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1204       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1205       DCI.AddToWorklist(Cvt.getNode());
1206       return Cvt;
1207     }
1208   }
1209
1210   // We are primarily trying to catch operations on illegal vector types
1211   // before they are expanded.
1212   // For scalars, we can use the more flexible method of checking masked bits
1213   // after legalization.
1214   if (!DCI.isBeforeLegalize() ||
1215       !SrcVT.isVector() ||
1216       SrcVT.getVectorElementType() != MVT::i8) {
1217     return SDValue();
1218   }
1219
1220   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1221
1222   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1223   // size as 4.
1224   unsigned NElts = SrcVT.getVectorNumElements();
1225   if (!SrcVT.isSimple() && NElts != 3)
1226     return SDValue();
1227
1228   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1229   // prevent a mess from expanding to v4i32 and repacking.
1230   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1231     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1232     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1233     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1234
1235     LoadSDNode *Load = cast<LoadSDNode>(Src);
1236     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1237                                      Load->getChain(),
1238                                      Load->getBasePtr(),
1239                                      LoadVT,
1240                                      Load->getMemOperand());
1241
1242     // Make sure successors of the original load stay after it by updating
1243     // them to use the new Chain.
1244     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1245
1246     SmallVector<SDValue, 4> Elts;
1247     if (RegVT.isVector())
1248       DAG.ExtractVectorElements(NewLoad, Elts);
1249     else
1250       Elts.push_back(NewLoad);
1251
1252     SmallVector<SDValue, 4> Ops;
1253
1254     unsigned EltIdx = 0;
1255     for (SDValue Elt : Elts) {
1256       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1257       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1258         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1259         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1260         DCI.AddToWorklist(Cvt.getNode());
1261         Ops.push_back(Cvt);
1262       }
1263
1264       ++EltIdx;
1265     }
1266
1267     assert(Ops.size() == NElts);
1268
1269     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1270   }
1271
1272   return SDValue();
1273 }
1274
1275 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1276
1277 // This is a variant of
1278 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1279 //
1280 // The normal DAG combiner will do this, but only if the add has one use since
1281 // that would increase the number of instructions.
1282 //
1283 // This prevents us from seeing a constant offset that can be folded into a
1284 // memory instruction's addressing mode. If we know the resulting add offset of
1285 // a pointer can be folded into an addressing offset, we can replace the pointer
1286 // operand with the add of new constant offset. This eliminates one of the uses,
1287 // and may allow the remaining use to also be simplified.
1288 //
1289 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1290                                                unsigned AddrSpace,
1291                                                DAGCombinerInfo &DCI) const {
1292   SDValue N0 = N->getOperand(0);
1293   SDValue N1 = N->getOperand(1);
1294
1295   if (N0.getOpcode() != ISD::ADD)
1296     return SDValue();
1297
1298   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1299   if (!CN1)
1300     return SDValue();
1301
1302   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1303   if (!CAdd)
1304     return SDValue();
1305
1306   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1307       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1308
1309   // If the resulting offset is too large, we can't fold it into the addressing
1310   // mode offset.
1311   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1312   if (!TII->canFoldOffset(Offset.getZExtValue(), AddrSpace))
1313     return SDValue();
1314
1315   SelectionDAG &DAG = DCI.DAG;
1316   SDLoc SL(N);
1317   EVT VT = N->getValueType(0);
1318
1319   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1320   SDValue COffset = DAG.getConstant(Offset, MVT::i32);
1321
1322   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1323 }
1324
1325 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1326                                             DAGCombinerInfo &DCI) const {
1327   SelectionDAG &DAG = DCI.DAG;
1328   SDLoc DL(N);
1329   EVT VT = N->getValueType(0);
1330
1331   switch (N->getOpcode()) {
1332     default: return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1333     case ISD::SETCC: {
1334       SDValue Arg0 = N->getOperand(0);
1335       SDValue Arg1 = N->getOperand(1);
1336       SDValue CC = N->getOperand(2);
1337       ConstantSDNode * C = nullptr;
1338       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
1339
1340       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
1341       if (VT == MVT::i1
1342           && Arg0.getOpcode() == ISD::SIGN_EXTEND
1343           && Arg0.getOperand(0).getValueType() == MVT::i1
1344           && (C = dyn_cast<ConstantSDNode>(Arg1))
1345           && C->isNullValue()
1346           && CCOp == ISD::SETNE) {
1347         return SimplifySetCC(VT, Arg0.getOperand(0),
1348                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
1349       }
1350       break;
1351     }
1352
1353   case AMDGPUISD::CVT_F32_UBYTE0:
1354   case AMDGPUISD::CVT_F32_UBYTE1:
1355   case AMDGPUISD::CVT_F32_UBYTE2:
1356   case AMDGPUISD::CVT_F32_UBYTE3: {
1357     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1358
1359     SDValue Src = N->getOperand(0);
1360     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1361
1362     APInt KnownZero, KnownOne;
1363     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1364                                           !DCI.isBeforeLegalizeOps());
1365     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1366     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1367         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1368       DCI.CommitTargetLoweringOpt(TLO);
1369     }
1370
1371     break;
1372   }
1373
1374   case ISD::UINT_TO_FP: {
1375     return performUCharToFloatCombine(N, DCI);
1376   }
1377   case ISD::LOAD:
1378   case ISD::STORE:
1379   case ISD::ATOMIC_LOAD:
1380   case ISD::ATOMIC_STORE:
1381   case ISD::ATOMIC_CMP_SWAP:
1382   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1383   case ISD::ATOMIC_SWAP:
1384   case ISD::ATOMIC_LOAD_ADD:
1385   case ISD::ATOMIC_LOAD_SUB:
1386   case ISD::ATOMIC_LOAD_AND:
1387   case ISD::ATOMIC_LOAD_OR:
1388   case ISD::ATOMIC_LOAD_XOR:
1389   case ISD::ATOMIC_LOAD_NAND:
1390   case ISD::ATOMIC_LOAD_MIN:
1391   case ISD::ATOMIC_LOAD_MAX:
1392   case ISD::ATOMIC_LOAD_UMIN:
1393   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1394     if (DCI.isBeforeLegalize())
1395       break;
1396
1397     MemSDNode *MemNode = cast<MemSDNode>(N);
1398     SDValue Ptr = MemNode->getBasePtr();
1399
1400     // TODO: We could also do this for multiplies.
1401     unsigned AS = MemNode->getAddressSpace();
1402     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1403       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1404       if (NewPtr) {
1405         SmallVector<SDValue, 8> NewOps;
1406         for (unsigned I = 0, E = MemNode->getNumOperands(); I != E; ++I)
1407           NewOps.push_back(MemNode->getOperand(I));
1408
1409         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1410         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1411       }
1412     }
1413     break;
1414   }
1415   }
1416   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1417 }
1418
1419 /// \brief Test if RegClass is one of the VSrc classes
1420 static bool isVSrc(unsigned RegClass) {
1421   return AMDGPU::VSrc_32RegClassID == RegClass ||
1422          AMDGPU::VSrc_64RegClassID == RegClass;
1423 }
1424
1425 /// \brief Test if RegClass is one of the SSrc classes
1426 static bool isSSrc(unsigned RegClass) {
1427   return AMDGPU::SSrc_32RegClassID == RegClass ||
1428          AMDGPU::SSrc_64RegClassID == RegClass;
1429 }
1430
1431 /// \brief Analyze the possible immediate value Op
1432 ///
1433 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1434 /// and the immediate value if it's a literal immediate
1435 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1436
1437   union {
1438     int32_t I;
1439     float F;
1440   } Imm;
1441
1442   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1443     if (Node->getZExtValue() >> 32) {
1444         return -1;
1445     }
1446     Imm.I = Node->getSExtValue();
1447   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1448     if (N->getValueType(0) != MVT::f32)
1449       return -1;
1450     Imm.F = Node->getValueAPF().convertToFloat();
1451   } else
1452     return -1; // It isn't an immediate
1453
1454   if ((Imm.I >= -16 && Imm.I <= 64) ||
1455       Imm.F == 0.5f || Imm.F == -0.5f ||
1456       Imm.F == 1.0f || Imm.F == -1.0f ||
1457       Imm.F == 2.0f || Imm.F == -2.0f ||
1458       Imm.F == 4.0f || Imm.F == -4.0f)
1459     return 0; // It's an inline immediate
1460
1461   return Imm.I; // It's a literal immediate
1462 }
1463
1464 /// \brief Try to fold an immediate directly into an instruction
1465 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
1466                                bool &ScalarSlotUsed) const {
1467
1468   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
1469   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1470       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1471   if (!Mov || !TII->isMov(Mov->getMachineOpcode()))
1472     return false;
1473
1474   const SDValue &Op = Mov->getOperand(0);
1475   int32_t Value = analyzeImmediate(Op.getNode());
1476   if (Value == -1) {
1477     // Not an immediate at all
1478     return false;
1479
1480   } else if (Value == 0) {
1481     // Inline immediates can always be fold
1482     Operand = Op;
1483     return true;
1484
1485   } else if (Value == Immediate) {
1486     // Already fold literal immediate
1487     Operand = Op;
1488     return true;
1489
1490   } else if (!ScalarSlotUsed && !Immediate) {
1491     // Fold this literal immediate
1492     ScalarSlotUsed = true;
1493     Immediate = Value;
1494     Operand = Op;
1495     return true;
1496
1497   }
1498
1499   return false;
1500 }
1501
1502 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
1503                                    SelectionDAG &DAG, const SDValue &Op) const {
1504   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1505       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1506   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1507
1508   if (!Op->isMachineOpcode()) {
1509     switch(Op->getOpcode()) {
1510     case ISD::CopyFromReg: {
1511       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1512       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
1513       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1514         return MRI.getRegClass(Reg);
1515       }
1516       return TRI.getPhysRegClass(Reg);
1517     }
1518     default:  return nullptr;
1519     }
1520   }
1521   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
1522   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
1523   if (OpClassID != -1) {
1524     return TRI.getRegClass(OpClassID);
1525   }
1526   switch(Op.getMachineOpcode()) {
1527   case AMDGPU::COPY_TO_REGCLASS:
1528     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
1529     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
1530
1531     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
1532     // class, then the register class for the value could be either a
1533     // VReg or and SReg.  In order to get a more accurate
1534     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
1535         OpClassID == AMDGPU::VSrc_64RegClassID) {
1536       return getRegClassForNode(DAG, Op.getOperand(0));
1537     }
1538     return TRI.getRegClass(OpClassID);
1539   case AMDGPU::EXTRACT_SUBREG: {
1540     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1541     const TargetRegisterClass *SuperClass =
1542       getRegClassForNode(DAG, Op.getOperand(0));
1543     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
1544   }
1545   case AMDGPU::REG_SEQUENCE:
1546     // Operand 0 is the register class id for REG_SEQUENCE instructions.
1547     return TRI.getRegClass(
1548       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
1549   default:
1550     return getRegClassFor(Op.getSimpleValueType());
1551   }
1552 }
1553
1554 /// \brief Does "Op" fit into register class "RegClass" ?
1555 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
1556                                     unsigned RegClass) const {
1557   const TargetRegisterInfo *TRI =
1558       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1559   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
1560   if (!RC) {
1561     return false;
1562   }
1563   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
1564 }
1565
1566 /// \brief Make sure that we don't exeed the number of allowed scalars
1567 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
1568                                        unsigned RegClass,
1569                                        bool &ScalarSlotUsed) const {
1570
1571   // First map the operands register class to a destination class
1572   if (RegClass == AMDGPU::VSrc_32RegClassID)
1573     RegClass = AMDGPU::VReg_32RegClassID;
1574   else if (RegClass == AMDGPU::VSrc_64RegClassID)
1575     RegClass = AMDGPU::VReg_64RegClassID;
1576   else
1577     return;
1578
1579   // Nothing to do if they fit naturally
1580   if (fitsRegClass(DAG, Operand, RegClass))
1581     return;
1582
1583   // If the scalar slot isn't used yet use it now
1584   if (!ScalarSlotUsed) {
1585     ScalarSlotUsed = true;
1586     return;
1587   }
1588
1589   // This is a conservative aproach. It is possible that we can't determine the
1590   // correct register class and copy too often, but better safe than sorry.
1591
1592   SDNode *Node;
1593   // We can't use COPY_TO_REGCLASS with FrameIndex arguments.
1594   if (isa<FrameIndexSDNode>(Operand)) {
1595     unsigned Opcode = Operand.getValueType() == MVT::i32 ?
1596                       AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1597     Node = DAG.getMachineNode(Opcode, SDLoc(), Operand.getValueType(),
1598                               Operand);
1599   } else {
1600     SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
1601     Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
1602                               Operand.getValueType(), Operand, RC);
1603   }
1604   Operand = SDValue(Node, 0);
1605 }
1606
1607 /// \returns true if \p Node's operands are different from the SDValue list
1608 /// \p Ops
1609 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
1610   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
1611     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
1612       return true;
1613     }
1614   }
1615   return false;
1616 }
1617
1618 /// \brief Try to fold the Nodes operands into the Node
1619 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
1620                                        SelectionDAG &DAG) const {
1621
1622   // Original encoding (either e32 or e64)
1623   int Opcode = Node->getMachineOpcode();
1624   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1625       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1626   const MCInstrDesc *Desc = &TII->get(Opcode);
1627
1628   unsigned NumDefs = Desc->getNumDefs();
1629   unsigned NumOps = Desc->getNumOperands();
1630
1631   // Commuted opcode if available
1632   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
1633   const MCInstrDesc *DescRev = OpcodeRev == -1 ? nullptr : &TII->get(OpcodeRev);
1634
1635   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
1636   assert(!DescRev || DescRev->getNumOperands() == NumOps);
1637
1638   // e64 version if available, -1 otherwise
1639   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
1640   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? nullptr : &TII->get(OpcodeE64);
1641   int InputModifiers[3] = {0};
1642
1643   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
1644
1645   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
1646   bool HaveVSrc = false, HaveSSrc = false;
1647
1648   // First figure out what we already have in this instruction.
1649   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1650        i != e && Op < NumOps; ++i, ++Op) {
1651
1652     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1653     if (isVSrc(RegClass))
1654       HaveVSrc = true;
1655     else if (isSSrc(RegClass))
1656       HaveSSrc = true;
1657     else
1658       continue;
1659
1660     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
1661     if (Imm != -1 && Imm != 0) {
1662       // Literal immediate
1663       Immediate = Imm;
1664     }
1665   }
1666
1667   // If we neither have VSrc nor SSrc, it makes no sense to continue.
1668   if (!HaveVSrc && !HaveSSrc)
1669     return Node;
1670
1671   // No scalar allowed when we have both VSrc and SSrc
1672   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
1673
1674   // Second go over the operands and try to fold them
1675   std::vector<SDValue> Ops;
1676   bool Promote2e64 = false;
1677   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
1678        i != e && Op < NumOps; ++i, ++Op) {
1679
1680     const SDValue &Operand = Node->getOperand(i);
1681     Ops.push_back(Operand);
1682
1683     // Already folded immediate?
1684     if (isa<ConstantSDNode>(Operand.getNode()) ||
1685         isa<ConstantFPSDNode>(Operand.getNode()))
1686       continue;
1687
1688     // Is this a VSrc or SSrc operand?
1689     unsigned RegClass = Desc->OpInfo[Op].RegClass;
1690     if (isVSrc(RegClass) || isSSrc(RegClass)) {
1691       // Try to fold the immediates
1692       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
1693         // Folding didn't work, make sure we don't hit the SReg limit.
1694         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
1695       }
1696       continue;
1697     } else {
1698       // If it's not a VSrc or SSrc operand check if we have a GlobalAddress.
1699       // These will be lowered to immediates, so we will need to insert a MOV.
1700       if (isa<GlobalAddressSDNode>(Ops[i])) {
1701         SDNode *Node = DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, SDLoc(),
1702                                     Operand.getValueType(), Operand);
1703         Ops[i] = SDValue(Node, 0);
1704       }
1705     }
1706
1707     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
1708
1709       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
1710       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
1711
1712       // Test if it makes sense to swap operands
1713       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
1714           (!fitsRegClass(DAG, Ops[1], RegClass) &&
1715            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1716
1717         // Swap commutable operands
1718         std::swap(Ops[0], Ops[1]);
1719
1720         Desc = DescRev;
1721         DescRev = nullptr;
1722         continue;
1723       }
1724     }
1725
1726     if (Immediate)
1727       continue;
1728
1729     if (DescE64) {
1730       // Test if it makes sense to switch to e64 encoding
1731       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
1732       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
1733         continue;
1734
1735       int32_t TmpImm = -1;
1736       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
1737           (!fitsRegClass(DAG, Ops[i], RegClass) &&
1738            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
1739
1740         // Switch to e64 encoding
1741         Immediate = -1;
1742         Promote2e64 = true;
1743         Desc = DescE64;
1744         DescE64 = nullptr;
1745       }
1746     }
1747
1748     if (!DescE64 && !Promote2e64)
1749       continue;
1750     if (!Operand.isMachineOpcode())
1751       continue;
1752   }
1753
1754   if (Promote2e64) {
1755     std::vector<SDValue> OldOps(Ops);
1756     Ops.clear();
1757     bool HasModifiers = TII->hasModifiers(Desc->Opcode);
1758     for (unsigned i = 0; i < OldOps.size(); ++i) {
1759       // src_modifier
1760       if (HasModifiers)
1761         Ops.push_back(DAG.getTargetConstant(InputModifiers[i], MVT::i32));
1762       Ops.push_back(OldOps[i]);
1763     }
1764     // Add the modifier flags while promoting
1765     if (HasModifiers) {
1766       for (unsigned i = 0; i < 2; ++i)
1767         Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
1768     }
1769   }
1770
1771   // Add optional chain and glue
1772   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1773     Ops.push_back(Node->getOperand(i));
1774
1775   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1776   // this case a brand new node is always be created, even if the operands
1777   // are the same as before.  So, manually check if anything has been changed.
1778   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1779     return Node;
1780   }
1781
1782   // Create a complete new instruction
1783   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1784 }
1785
1786 /// \brief Helper function for adjustWritemask
1787 static unsigned SubIdx2Lane(unsigned Idx) {
1788   switch (Idx) {
1789   default: return 0;
1790   case AMDGPU::sub0: return 0;
1791   case AMDGPU::sub1: return 1;
1792   case AMDGPU::sub2: return 2;
1793   case AMDGPU::sub3: return 3;
1794   }
1795 }
1796
1797 /// \brief Adjust the writemask of MIMG instructions
1798 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1799                                        SelectionDAG &DAG) const {
1800   SDNode *Users[4] = { };
1801   unsigned Lane = 0;
1802   unsigned OldDmask = Node->getConstantOperandVal(0);
1803   unsigned NewDmask = 0;
1804
1805   // Try to figure out the used register components
1806   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1807        I != E; ++I) {
1808
1809     // Abort if we can't understand the usage
1810     if (!I->isMachineOpcode() ||
1811         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1812       return;
1813
1814     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1815     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1816     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1817     // set, etc.
1818     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1819
1820     // Set which texture component corresponds to the lane.
1821     unsigned Comp;
1822     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1823       assert(Dmask);
1824       Comp = countTrailingZeros(Dmask);
1825       Dmask &= ~(1 << Comp);
1826     }
1827
1828     // Abort if we have more than one user per component
1829     if (Users[Lane])
1830       return;
1831
1832     Users[Lane] = *I;
1833     NewDmask |= 1 << Comp;
1834   }
1835
1836   // Abort if there's no change
1837   if (NewDmask == OldDmask)
1838     return;
1839
1840   // Adjust the writemask in the node
1841   std::vector<SDValue> Ops;
1842   Ops.push_back(DAG.getTargetConstant(NewDmask, MVT::i32));
1843   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1844     Ops.push_back(Node->getOperand(i));
1845   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1846
1847   // If we only got one lane, replace it with a copy
1848   // (if NewDmask has only one bit set...)
1849   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1850     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1851     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1852                                       SDLoc(), Users[Lane]->getValueType(0),
1853                                       SDValue(Node, 0), RC);
1854     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1855     return;
1856   }
1857
1858   // Update the users of the node with the new indices
1859   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1860
1861     SDNode *User = Users[i];
1862     if (!User)
1863       continue;
1864
1865     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1866     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1867
1868     switch (Idx) {
1869     default: break;
1870     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1871     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1872     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1873     }
1874   }
1875 }
1876
1877 /// \brief Fold the instructions after selecting them.
1878 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1879                                           SelectionDAG &DAG) const {
1880   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1881       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1882   Node = AdjustRegClass(Node, DAG);
1883
1884   if (TII->isMIMG(Node->getMachineOpcode()))
1885     adjustWritemask(Node, DAG);
1886
1887   return foldOperands(Node, DAG);
1888 }
1889
1890 /// \brief Assign the register class depending on the number of
1891 /// bits set in the writemask
1892 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1893                                                      SDNode *Node) const {
1894   const SIInstrInfo *TII = static_cast<const SIInstrInfo *>(
1895       getTargetMachine().getSubtargetImpl()->getInstrInfo());
1896   if (!TII->isMIMG(MI->getOpcode()))
1897     return;
1898
1899   unsigned VReg = MI->getOperand(0).getReg();
1900   unsigned Writemask = MI->getOperand(1).getImm();
1901   unsigned BitsSet = 0;
1902   for (unsigned i = 0; i < 4; ++i)
1903     BitsSet += Writemask & (1 << i) ? 1 : 0;
1904
1905   const TargetRegisterClass *RC;
1906   switch (BitsSet) {
1907   default: return;
1908   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1909   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1910   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1911   }
1912
1913   unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
1914   MI->setDesc(TII->get(NewOpcode));
1915   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1916   MRI.setRegClass(VReg, RC);
1917 }
1918
1919 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1920                                                 SelectionDAG &DAG) const {
1921
1922   SDLoc DL(N);
1923   unsigned NewOpcode = N->getMachineOpcode();
1924
1925   switch (N->getMachineOpcode()) {
1926   default: return N;
1927   case AMDGPU::S_LOAD_DWORD_IMM:
1928     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1929     // Fall-through
1930   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1931     if (NewOpcode == N->getMachineOpcode()) {
1932       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1933     }
1934     // Fall-through
1935   case AMDGPU::S_LOAD_DWORDX4_IMM:
1936   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1937     if (NewOpcode == N->getMachineOpcode()) {
1938       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1939     }
1940     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1941       return N;
1942     }
1943     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1944     SDValue Ops[] = {
1945       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1946                                  DAG.getConstant(0, MVT::i64)), 0),
1947       N->getOperand(0),
1948       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1949     };
1950     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1951   }
1952   }
1953 }
1954
1955 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1956                                                const TargetRegisterClass *RC,
1957                                                unsigned Reg, EVT VT) const {
1958   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1959
1960   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1961                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1962 }