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