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