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