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