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