27c6e6095e59138cc647803fc5b03821daabdb43
[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 static bool isFlatGlobalAddrSpace(unsigned AS) {
496   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
497     AS == AMDGPUAS::FLAT_ADDRESS ||
498     AS == AMDGPUAS::CONSTANT_ADDRESS;
499 }
500
501 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
502                                            unsigned DestAS) const {
503   return isFlatGlobalAddrSpace(SrcAS) &&  isFlatGlobalAddrSpace(DestAS);
504 }
505
506 TargetLoweringBase::LegalizeTypeAction
507 SITargetLowering::getPreferredVectorAction(EVT VT) const {
508   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
509     return TypeSplitVector;
510
511   return TargetLoweringBase::getPreferredVectorAction(VT);
512 }
513
514 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
515                                                          Type *Ty) const {
516   const SIInstrInfo *TII =
517       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
518   return TII->isInlineConstant(Imm);
519 }
520
521 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
522                                          SDLoc SL, SDValue Chain,
523                                          unsigned Offset, bool Signed) const {
524   const DataLayout &DL = DAG.getDataLayout();
525   MachineFunction &MF = DAG.getMachineFunction();
526   const SIRegisterInfo *TRI =
527       static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
528   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
529
530   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
531
532   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
533   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
534   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
535   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
536                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
537   SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
538                             DAG.getConstant(Offset, SL, PtrVT));
539   SDValue PtrOffset = DAG.getUNDEF(PtrVT);
540   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
541
542   unsigned Align = DL.getABITypeAlignment(Ty);
543
544   ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
545   if (MemVT.isFloatingPoint())
546     ExtTy = ISD::EXTLOAD;
547
548   return DAG.getLoad(ISD::UNINDEXED, ExtTy,
549                      VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
550                      false, // isVolatile
551                      true, // isNonTemporal
552                      true, // isInvariant
553                      Align); // Alignment
554 }
555
556 SDValue SITargetLowering::LowerFormalArguments(
557     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
558     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
559     SmallVectorImpl<SDValue> &InVals) const {
560   const SIRegisterInfo *TRI =
561       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
562
563   MachineFunction &MF = DAG.getMachineFunction();
564   FunctionType *FType = MF.getFunction()->getFunctionType();
565   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
566   const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
567
568   if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) {
569     const Function *Fn = MF.getFunction();
570     DiagnosticInfoUnsupported NoGraphicsHSA(*Fn, "non-compute shaders with HSA");
571     DAG.getContext()->diagnose(NoGraphicsHSA);
572     return SDValue();
573   }
574
575   // FIXME: We currently assume all calling conventions are kernels.
576
577   SmallVector<ISD::InputArg, 16> Splits;
578   BitVector Skipped(Ins.size());
579
580   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
581     const ISD::InputArg &Arg = Ins[i];
582
583     // First check if it's a PS input addr
584     if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
585         !Arg.Flags.isByVal()) {
586
587       assert((PSInputNum <= 15) && "Too many PS inputs!");
588
589       if (!Arg.Used) {
590         // We can safely skip PS inputs
591         Skipped.set(i);
592         ++PSInputNum;
593         continue;
594       }
595
596       Info->PSInputAddr |= 1 << PSInputNum++;
597     }
598
599     // Second split vertices into their elements
600     if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
601       ISD::InputArg NewArg = Arg;
602       NewArg.Flags.setSplit();
603       NewArg.VT = Arg.VT.getVectorElementType();
604
605       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
606       // three or five element vertex only needs three or five registers,
607       // NOT four or eight.
608       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
609       unsigned NumElements = ParamType->getVectorNumElements();
610
611       for (unsigned j = 0; j != NumElements; ++j) {
612         Splits.push_back(NewArg);
613         NewArg.PartOffset += NewArg.VT.getStoreSize();
614       }
615
616     } else if (Info->getShaderType() != ShaderType::COMPUTE) {
617       Splits.push_back(Arg);
618     }
619   }
620
621   SmallVector<CCValAssign, 16> ArgLocs;
622   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
623                  *DAG.getContext());
624
625   // At least one interpolation mode must be enabled or else the GPU will hang.
626   if (Info->getShaderType() == ShaderType::PIXEL &&
627       (Info->PSInputAddr & 0x7F) == 0) {
628     Info->PSInputAddr |= 1;
629     CCInfo.AllocateReg(AMDGPU::VGPR0);
630     CCInfo.AllocateReg(AMDGPU::VGPR1);
631   }
632
633   if (Info->getShaderType() == ShaderType::COMPUTE) {
634     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
635                             Splits);
636   }
637
638   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
639   if (Info->hasPrivateSegmentBuffer()) {
640     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
641     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
642     CCInfo.AllocateReg(PrivateSegmentBufferReg);
643   }
644
645   if (Info->hasDispatchPtr()) {
646     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
647     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
648     CCInfo.AllocateReg(DispatchPtrReg);
649   }
650
651   if (Info->hasKernargSegmentPtr()) {
652     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
653     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
654     CCInfo.AllocateReg(InputPtrReg);
655   }
656
657   AnalyzeFormalArguments(CCInfo, Splits);
658
659   SmallVector<SDValue, 16> Chains;
660
661   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
662
663     const ISD::InputArg &Arg = Ins[i];
664     if (Skipped[i]) {
665       InVals.push_back(DAG.getUNDEF(Arg.VT));
666       continue;
667     }
668
669     CCValAssign &VA = ArgLocs[ArgIdx++];
670     MVT VT = VA.getLocVT();
671
672     if (VA.isMemLoc()) {
673       VT = Ins[i].VT;
674       EVT MemVT = Splits[i].VT;
675       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
676                               VA.getLocMemOffset();
677       // The first 36 bytes of the input buffer contains information about
678       // thread group and global sizes.
679       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
680                                    Offset, Ins[i].Flags.isSExt());
681       Chains.push_back(Arg.getValue(1));
682
683       auto *ParamTy =
684         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
685       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
686           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
687         // On SI local pointers are just offsets into LDS, so they are always
688         // less than 16-bits.  On CI and newer they could potentially be
689         // real pointers, so we can't guarantee their size.
690         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
691                           DAG.getValueType(MVT::i16));
692       }
693
694       InVals.push_back(Arg);
695       Info->ABIArgOffset = Offset + MemVT.getStoreSize();
696       continue;
697     }
698     assert(VA.isRegLoc() && "Parameter must be in a register!");
699
700     unsigned Reg = VA.getLocReg();
701
702     if (VT == MVT::i64) {
703       // For now assume it is a pointer
704       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
705                                      &AMDGPU::SReg_64RegClass);
706       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
707       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
708       InVals.push_back(Copy);
709       continue;
710     }
711
712     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
713
714     Reg = MF.addLiveIn(Reg, RC);
715     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
716
717     if (Arg.VT.isVector()) {
718
719       // Build a vector from the registers
720       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
721       unsigned NumElements = ParamType->getVectorNumElements();
722
723       SmallVector<SDValue, 4> Regs;
724       Regs.push_back(Val);
725       for (unsigned j = 1; j != NumElements; ++j) {
726         Reg = ArgLocs[ArgIdx++].getLocReg();
727         Reg = MF.addLiveIn(Reg, RC);
728
729         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
730         Regs.push_back(Copy);
731       }
732
733       // Fill up the missing vector elements
734       NumElements = Arg.VT.getVectorNumElements() - NumElements;
735       Regs.append(NumElements, DAG.getUNDEF(VT));
736
737       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
738       continue;
739     }
740
741     InVals.push_back(Val);
742   }
743
744   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
745   // these from the dispatch pointer.
746
747   // Start adding system SGPRs.
748   if (Info->hasWorkGroupIDX()) {
749     unsigned Reg = Info->addWorkGroupIDX();
750     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
751     CCInfo.AllocateReg(Reg);
752   } else
753     llvm_unreachable("work group id x is always enabled");
754
755   if (Info->hasWorkGroupIDY()) {
756     unsigned Reg = Info->addWorkGroupIDY();
757     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
758     CCInfo.AllocateReg(Reg);
759   }
760
761   if (Info->hasWorkGroupIDZ()) {
762     unsigned Reg = Info->addWorkGroupIDZ();
763     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
764     CCInfo.AllocateReg(Reg);
765   }
766
767   if (Info->hasWorkGroupInfo()) {
768     unsigned Reg = Info->addWorkGroupInfo();
769     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
770     CCInfo.AllocateReg(Reg);
771   }
772
773   if (Info->hasPrivateSegmentWaveByteOffset()) {
774     // Scratch wave offset passed in system SGPR.
775     unsigned PrivateSegmentWaveByteOffsetReg
776       = Info->addPrivateSegmentWaveByteOffset();
777
778     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
779     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
780   }
781
782   // Now that we've figured out where the scratch register inputs are, see if
783   // should reserve the arguments and use them directly.
784
785   bool HasStackObjects = MF.getFrameInfo()->hasStackObjects();
786
787   if (ST.isAmdHsaOS()) {
788     // TODO: Assume we will spill without optimizations.
789     if (HasStackObjects) {
790       // If we have stack objects, we unquestionably need the private buffer
791       // resource. For the HSA ABI, this will be the first 4 user SGPR
792       // inputs. We can reserve those and use them directly.
793
794       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
795         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
796       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
797
798       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
799         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
800       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
801     } else {
802       unsigned ReservedBufferReg
803         = TRI->reservedPrivateSegmentBufferReg(MF);
804       unsigned ReservedOffsetReg
805         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
806
807       // We tentatively reserve the last registers (skipping the last two
808       // which may contain VCC). After register allocation, we'll replace
809       // these with the ones immediately after those which were really
810       // allocated. In the prologue copies will be inserted from the argument
811       // to these reserved registers.
812       Info->setScratchRSrcReg(ReservedBufferReg);
813       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
814     }
815   } else {
816     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
817
818     // Without HSA, relocations are used for the scratch pointer and the
819     // buffer resource setup is always inserted in the prologue. Scratch wave
820     // offset is still in an input SGPR.
821     Info->setScratchRSrcReg(ReservedBufferReg);
822
823     if (HasStackObjects) {
824       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
825         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
826       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
827     } else {
828       unsigned ReservedOffsetReg
829         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
830       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
831     }
832   }
833
834   if (Info->hasWorkItemIDX()) {
835     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
836     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
837     CCInfo.AllocateReg(Reg);
838   } else
839     llvm_unreachable("workitem id x should always be enabled");
840
841   if (Info->hasWorkItemIDY()) {
842     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
843     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
844     CCInfo.AllocateReg(Reg);
845   }
846
847   if (Info->hasWorkItemIDZ()) {
848     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
849     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
850     CCInfo.AllocateReg(Reg);
851   }
852
853   if (Chains.empty())
854     return Chain;
855
856   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
857 }
858
859 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
860     MachineInstr * MI, MachineBasicBlock * BB) const {
861
862   switch (MI->getOpcode()) {
863   default:
864     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
865   case AMDGPU::BRANCH:
866     return BB;
867   }
868   return BB;
869 }
870
871 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
872   // This currently forces unfolding various combinations of fsub into fma with
873   // free fneg'd operands. As long as we have fast FMA (controlled by
874   // isFMAFasterThanFMulAndFAdd), we should perform these.
875
876   // When fma is quarter rate, for f64 where add / sub are at best half rate,
877   // most of these combines appear to be cycle neutral but save on instruction
878   // count / code size.
879   return true;
880 }
881
882 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
883                                          EVT VT) const {
884   if (!VT.isVector()) {
885     return MVT::i1;
886   }
887   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
888 }
889
890 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
891   return MVT::i32;
892 }
893
894 // Answering this is somewhat tricky and depends on the specific device which
895 // have different rates for fma or all f64 operations.
896 //
897 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
898 // regardless of which device (although the number of cycles differs between
899 // devices), so it is always profitable for f64.
900 //
901 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
902 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
903 // which we can always do even without fused FP ops since it returns the same
904 // result as the separate operations and since it is always full
905 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
906 // however does not support denormals, so we do report fma as faster if we have
907 // a fast fma device and require denormals.
908 //
909 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
910   VT = VT.getScalarType();
911
912   if (!VT.isSimple())
913     return false;
914
915   switch (VT.getSimpleVT().SimpleTy) {
916   case MVT::f32:
917     // This is as fast on some subtargets. However, we always have full rate f32
918     // mad available which returns the same result as the separate operations
919     // which we should prefer over fma. We can't use this if we want to support
920     // denormals, so only report this in these cases.
921     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
922   case MVT::f64:
923     return true;
924   default:
925     break;
926   }
927
928   return false;
929 }
930
931 //===----------------------------------------------------------------------===//
932 // Custom DAG Lowering Operations
933 //===----------------------------------------------------------------------===//
934
935 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
936   switch (Op.getOpcode()) {
937   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
938   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
939   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
940   case ISD::LOAD: {
941     SDValue Result = LowerLOAD(Op, DAG);
942     assert((!Result.getNode() ||
943             Result.getNode()->getNumValues() == 2) &&
944            "Load should return a value and a chain");
945     return Result;
946   }
947
948   case ISD::FSIN:
949   case ISD::FCOS:
950     return LowerTrig(Op, DAG);
951   case ISD::SELECT: return LowerSELECT(Op, DAG);
952   case ISD::FDIV: return LowerFDIV(Op, DAG);
953   case ISD::STORE: return LowerSTORE(Op, DAG);
954   case ISD::GlobalAddress: {
955     MachineFunction &MF = DAG.getMachineFunction();
956     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
957     return LowerGlobalAddress(MFI, Op, DAG);
958   }
959   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
960   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
961   }
962   return SDValue();
963 }
964
965 /// \brief Helper function for LowerBRCOND
966 static SDNode *findUser(SDValue Value, unsigned Opcode) {
967
968   SDNode *Parent = Value.getNode();
969   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
970        I != E; ++I) {
971
972     if (I.getUse().get() != Value)
973       continue;
974
975     if (I->getOpcode() == Opcode)
976       return *I;
977   }
978   return nullptr;
979 }
980
981 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
982
983   SDLoc SL(Op);
984   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
985   unsigned FrameIndex = FINode->getIndex();
986
987   // A FrameIndex node represents a 32-bit offset into scratch memory.  If
988   // the high bit of a frame index offset were to be set, this would mean
989   // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
990   // scratch buffer, with 64 being the number of threads per wave.
991   //
992   // If we know the machine uses less than 128GB of scratch, then we can
993   // amrk the high bit of the FrameIndex node as known zero,
994   // which is important, because it means in most situations we can
995   // prove that values derived from FrameIndex nodes are non-negative.
996   // This enables us to take advantage of more addressing modes when
997   // accessing scratch buffers, since for scratch reads/writes, the register
998   // offset must always be positive.
999
1000   SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
1001   if (Subtarget->enableHugeScratchBuffer())
1002     return TFI;
1003
1004   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
1005                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
1006 }
1007
1008 /// This transforms the control flow intrinsics to get the branch destination as
1009 /// last parameter, also switches branch target with BR if the need arise
1010 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1011                                       SelectionDAG &DAG) const {
1012
1013   SDLoc DL(BRCOND);
1014
1015   SDNode *Intr = BRCOND.getOperand(1).getNode();
1016   SDValue Target = BRCOND.getOperand(2);
1017   SDNode *BR = nullptr;
1018
1019   if (Intr->getOpcode() == ISD::SETCC) {
1020     // As long as we negate the condition everything is fine
1021     SDNode *SetCC = Intr;
1022     assert(SetCC->getConstantOperandVal(1) == 1);
1023     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1024            ISD::SETNE);
1025     Intr = SetCC->getOperand(0).getNode();
1026
1027   } else {
1028     // Get the target from BR if we don't negate the condition
1029     BR = findUser(BRCOND, ISD::BR);
1030     Target = BR->getOperand(1);
1031   }
1032
1033   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
1034
1035   // Build the result and
1036   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1037
1038   // operands of the new intrinsic call
1039   SmallVector<SDValue, 4> Ops;
1040   Ops.push_back(BRCOND.getOperand(0));
1041   Ops.append(Intr->op_begin() + 1, Intr->op_end());
1042   Ops.push_back(Target);
1043
1044   // build the new intrinsic call
1045   SDNode *Result = DAG.getNode(
1046     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1047     DAG.getVTList(Res), Ops).getNode();
1048
1049   if (BR) {
1050     // Give the branch instruction our target
1051     SDValue Ops[] = {
1052       BR->getOperand(0),
1053       BRCOND.getOperand(2)
1054     };
1055     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
1056     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
1057     BR = NewBR.getNode();
1058   }
1059
1060   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
1061
1062   // Copy the intrinsic results to registers
1063   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
1064     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
1065     if (!CopyToReg)
1066       continue;
1067
1068     Chain = DAG.getCopyToReg(
1069       Chain, DL,
1070       CopyToReg->getOperand(1),
1071       SDValue(Result, i - 1),
1072       SDValue());
1073
1074     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
1075   }
1076
1077   // Remove the old intrinsic from the chain
1078   DAG.ReplaceAllUsesOfValueWith(
1079     SDValue(Intr, Intr->getNumValues() - 1),
1080     Intr->getOperand(0));
1081
1082   return Chain;
1083 }
1084
1085 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1086                                              SDValue Op,
1087                                              SelectionDAG &DAG) const {
1088   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1089
1090   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1091     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1092
1093   SDLoc DL(GSD);
1094   const GlobalValue *GV = GSD->getGlobal();
1095   MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
1096
1097   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
1098   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
1099
1100   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
1101                               DAG.getConstant(0, DL, MVT::i32));
1102   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
1103                               DAG.getConstant(1, DL, MVT::i32));
1104
1105   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
1106                            PtrLo, GA);
1107   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
1108                            PtrHi, DAG.getConstant(0, DL, MVT::i32),
1109                            SDValue(Lo.getNode(), 1));
1110   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
1111 }
1112
1113 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1114                                    SDValue V) const {
1115   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1116   // so we will end up with redundant moves to m0.
1117   //
1118   // We can't use S_MOV_B32, because there is no way to specify m0 as the
1119   // destination register.
1120   //
1121   // We have to use them both.  Machine cse will combine all the S_MOV_B32
1122   // instructions and the register coalescer eliminate the extra copies.
1123   SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1124   return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1125                           SDValue(M0, 0), SDValue()); // Glue
1126                                                       // A Null SDValue creates
1127                                                       // a glue result.
1128 }
1129
1130 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1131                                                  SDValue Op,
1132                                                  MVT VT,
1133                                                  unsigned Offset) const {
1134   SDLoc SL(Op);
1135   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1136                                  DAG.getEntryNode(), Offset, false);
1137   // The local size values will have the hi 16-bits as zero.
1138   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1139                      DAG.getValueType(VT));
1140 }
1141
1142 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1143                                                   SelectionDAG &DAG) const {
1144   MachineFunction &MF = DAG.getMachineFunction();
1145   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1146   const SIRegisterInfo *TRI =
1147       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1148
1149   EVT VT = Op.getValueType();
1150   SDLoc DL(Op);
1151   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1152
1153   // TODO: Should this propagate fast-math-flags?
1154
1155   switch (IntrinsicID) {
1156   case Intrinsic::amdgcn_dispatch_ptr:
1157     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1158       TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT);
1159
1160   case Intrinsic::r600_read_ngroups_x:
1161     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1162                           SI::KernelInputOffsets::NGROUPS_X, false);
1163   case Intrinsic::r600_read_ngroups_y:
1164     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1165                           SI::KernelInputOffsets::NGROUPS_Y, false);
1166   case Intrinsic::r600_read_ngroups_z:
1167     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1168                           SI::KernelInputOffsets::NGROUPS_Z, false);
1169   case Intrinsic::r600_read_global_size_x:
1170     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1171                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1172   case Intrinsic::r600_read_global_size_y:
1173     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1174                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1175   case Intrinsic::r600_read_global_size_z:
1176     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1177                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1178   case Intrinsic::r600_read_local_size_x:
1179     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1180                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
1181   case Intrinsic::r600_read_local_size_y:
1182     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1183                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
1184   case Intrinsic::r600_read_local_size_z:
1185     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1186                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
1187   case Intrinsic::AMDGPU_read_workdim:
1188     // Really only 2 bits.
1189     return lowerImplicitZextParam(DAG, Op, MVT::i8,
1190                                   getImplicitParameterOffset(MFI, GRID_DIM));
1191   case Intrinsic::r600_read_tgid_x:
1192     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1193       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1194   case Intrinsic::r600_read_tgid_y:
1195     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1196       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1197   case Intrinsic::r600_read_tgid_z:
1198     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1199       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1200   case Intrinsic::r600_read_tidig_x:
1201     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1202       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1203   case Intrinsic::r600_read_tidig_y:
1204     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1205       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1206   case Intrinsic::r600_read_tidig_z:
1207     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1208       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1209   case AMDGPUIntrinsic::SI_load_const: {
1210     SDValue Ops[] = {
1211       Op.getOperand(1),
1212       Op.getOperand(2)
1213     };
1214
1215     MachineMemOperand *MMO = MF.getMachineMemOperand(
1216       MachinePointerInfo(),
1217       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1218       VT.getStoreSize(), 4);
1219     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1220                                    Op->getVTList(), Ops, VT, MMO);
1221   }
1222   case AMDGPUIntrinsic::SI_sample:
1223     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1224   case AMDGPUIntrinsic::SI_sampleb:
1225     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1226   case AMDGPUIntrinsic::SI_sampled:
1227     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1228   case AMDGPUIntrinsic::SI_samplel:
1229     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1230   case AMDGPUIntrinsic::SI_vs_load_input:
1231     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1232                        Op.getOperand(1),
1233                        Op.getOperand(2),
1234                        Op.getOperand(3));
1235
1236   case AMDGPUIntrinsic::AMDGPU_fract:
1237   case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1238     return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1239                        DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1240   case AMDGPUIntrinsic::SI_fs_constant: {
1241     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1242     SDValue Glue = M0.getValue(1);
1243     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1244                        DAG.getConstant(2, DL, MVT::i32), // P0
1245                        Op.getOperand(1), Op.getOperand(2), Glue);
1246   }
1247   case AMDGPUIntrinsic::SI_packf16:
1248     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1249       return DAG.getUNDEF(MVT::i32);
1250     return Op;
1251   case AMDGPUIntrinsic::SI_fs_interp: {
1252     SDValue IJ = Op.getOperand(4);
1253     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1254                             DAG.getConstant(0, DL, MVT::i32));
1255     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1256                             DAG.getConstant(1, DL, MVT::i32));
1257     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1258     SDValue Glue = M0.getValue(1);
1259     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1260                              DAG.getVTList(MVT::f32, MVT::Glue),
1261                              I, Op.getOperand(1), Op.getOperand(2), Glue);
1262     Glue = SDValue(P1.getNode(), 1);
1263     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1264                              Op.getOperand(1), Op.getOperand(2), Glue);
1265   }
1266   default:
1267     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1268   }
1269 }
1270
1271 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1272                                               SelectionDAG &DAG) const {
1273   MachineFunction &MF = DAG.getMachineFunction();
1274   SDLoc DL(Op);
1275   SDValue Chain = Op.getOperand(0);
1276   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1277
1278   switch (IntrinsicID) {
1279   case AMDGPUIntrinsic::SI_sendmsg: {
1280     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1281     SDValue Glue = Chain.getValue(1);
1282     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1283                        Op.getOperand(2), Glue);
1284   }
1285   case AMDGPUIntrinsic::SI_tbuffer_store: {
1286     SDValue Ops[] = {
1287       Chain,
1288       Op.getOperand(2),
1289       Op.getOperand(3),
1290       Op.getOperand(4),
1291       Op.getOperand(5),
1292       Op.getOperand(6),
1293       Op.getOperand(7),
1294       Op.getOperand(8),
1295       Op.getOperand(9),
1296       Op.getOperand(10),
1297       Op.getOperand(11),
1298       Op.getOperand(12),
1299       Op.getOperand(13),
1300       Op.getOperand(14)
1301     };
1302
1303     EVT VT = Op.getOperand(3).getValueType();
1304
1305     MachineMemOperand *MMO = MF.getMachineMemOperand(
1306       MachinePointerInfo(),
1307       MachineMemOperand::MOStore,
1308       VT.getStoreSize(), 4);
1309     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1310                                    Op->getVTList(), Ops, VT, MMO);
1311   }
1312   default:
1313     return SDValue();
1314   }
1315 }
1316
1317 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1318   SDLoc DL(Op);
1319   LoadSDNode *Load = cast<LoadSDNode>(Op);
1320
1321   if (Op.getValueType().isVector()) {
1322     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1323            "Custom lowering for non-i32 vectors hasn't been implemented.");
1324     unsigned NumElements = Op.getValueType().getVectorNumElements();
1325     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1326
1327     switch (Load->getAddressSpace()) {
1328       default: break;
1329       case AMDGPUAS::GLOBAL_ADDRESS:
1330       case AMDGPUAS::PRIVATE_ADDRESS:
1331         if (NumElements >= 8)
1332           return SplitVectorLoad(Op, DAG);
1333
1334         // v4 loads are supported for private and global memory.
1335         if (NumElements <= 4)
1336           break;
1337         // fall-through
1338       case AMDGPUAS::LOCAL_ADDRESS:
1339         // If properly aligned, if we split we might be able to use ds_read_b64.
1340         return SplitVectorLoad(Op, DAG);
1341     }
1342   }
1343
1344   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1345 }
1346
1347 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1348                                                const SDValue &Op,
1349                                                SelectionDAG &DAG) const {
1350   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1351                      Op.getOperand(2),
1352                      Op.getOperand(3),
1353                      Op.getOperand(4));
1354 }
1355
1356 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1357   if (Op.getValueType() != MVT::i64)
1358     return SDValue();
1359
1360   SDLoc DL(Op);
1361   SDValue Cond = Op.getOperand(0);
1362
1363   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1364   SDValue One = DAG.getConstant(1, DL, MVT::i32);
1365
1366   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1367   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1368
1369   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1370   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1371
1372   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1373
1374   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1375   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1376
1377   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1378
1379   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1380   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1381 }
1382
1383 // Catch division cases where we can use shortcuts with rcp and rsq
1384 // instructions.
1385 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1386   SDLoc SL(Op);
1387   SDValue LHS = Op.getOperand(0);
1388   SDValue RHS = Op.getOperand(1);
1389   EVT VT = Op.getValueType();
1390   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1391
1392   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1393     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1394         CLHS->isExactlyValue(1.0)) {
1395       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1396       // the CI documentation has a worst case error of 1 ulp.
1397       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1398       // use it as long as we aren't trying to use denormals.
1399
1400       // 1.0 / sqrt(x) -> rsq(x)
1401       //
1402       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1403       // error seems really high at 2^29 ULP.
1404       if (RHS.getOpcode() == ISD::FSQRT)
1405         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1406
1407       // 1.0 / x -> rcp(x)
1408       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1409     }
1410   }
1411
1412   if (Unsafe) {
1413     // Turn into multiply by the reciprocal.
1414     // x / y -> x * (1.0 / y)
1415     SDNodeFlags Flags;
1416     Flags.setUnsafeAlgebra(true);
1417     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1418     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1419   }
1420
1421   return SDValue();
1422 }
1423
1424 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1425   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1426   if (FastLowered.getNode())
1427     return FastLowered;
1428
1429   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1430   // selection error for now rather than do something incorrect.
1431   if (Subtarget->hasFP32Denormals())
1432     return SDValue();
1433
1434   SDLoc SL(Op);
1435   SDValue LHS = Op.getOperand(0);
1436   SDValue RHS = Op.getOperand(1);
1437
1438   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1439
1440   const APFloat K0Val(BitsToFloat(0x6f800000));
1441   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1442
1443   const APFloat K1Val(BitsToFloat(0x2f800000));
1444   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1445
1446   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1447
1448   EVT SetCCVT =
1449       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1450
1451   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1452
1453   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1454
1455   // TODO: Should this propagate fast-math-flags?
1456
1457   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1458
1459   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1460
1461   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1462
1463   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1464 }
1465
1466 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1467   if (DAG.getTarget().Options.UnsafeFPMath)
1468     return LowerFastFDIV(Op, DAG);
1469
1470   SDLoc SL(Op);
1471   SDValue X = Op.getOperand(0);
1472   SDValue Y = Op.getOperand(1);
1473
1474   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1475
1476   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1477
1478   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1479
1480   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1481
1482   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1483
1484   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1485
1486   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1487
1488   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1489
1490   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1491
1492   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1493   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1494
1495   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1496                              NegDivScale0, Mul, DivScale1);
1497
1498   SDValue Scale;
1499
1500   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1501     // Workaround a hardware bug on SI where the condition output from div_scale
1502     // is not usable.
1503
1504     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1505
1506     // Figure out if the scale to use for div_fmas.
1507     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1508     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1509     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1510     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1511
1512     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1513     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1514
1515     SDValue Scale0Hi
1516       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1517     SDValue Scale1Hi
1518       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1519
1520     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1521     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1522     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1523   } else {
1524     Scale = DivScale1.getValue(1);
1525   }
1526
1527   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1528                              Fma4, Fma3, Mul, Scale);
1529
1530   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1531 }
1532
1533 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1534   EVT VT = Op.getValueType();
1535
1536   if (VT == MVT::f32)
1537     return LowerFDIV32(Op, DAG);
1538
1539   if (VT == MVT::f64)
1540     return LowerFDIV64(Op, DAG);
1541
1542   llvm_unreachable("Unexpected type for fdiv");
1543 }
1544
1545 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1546   SDLoc DL(Op);
1547   StoreSDNode *Store = cast<StoreSDNode>(Op);
1548   EVT VT = Store->getMemoryVT();
1549
1550   // These stores are legal.
1551   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1552     if (VT.isVector() && VT.getVectorNumElements() > 4)
1553       return ScalarizeVectorStore(Op, DAG);
1554     return SDValue();
1555   }
1556
1557   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1558   if (Ret.getNode())
1559     return Ret;
1560
1561   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1562       return SplitVectorStore(Op, DAG);
1563
1564   if (VT == MVT::i1)
1565     return DAG.getTruncStore(Store->getChain(), DL,
1566                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1567                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1568
1569   return SDValue();
1570 }
1571
1572 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1573   SDLoc DL(Op);
1574   EVT VT = Op.getValueType();
1575   SDValue Arg = Op.getOperand(0);
1576   // TODO: Should this propagate fast-math-flags?
1577   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1578                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
1579                                               DAG.getConstantFP(0.5/M_PI, DL,
1580                                                                 VT)));
1581
1582   switch (Op.getOpcode()) {
1583   case ISD::FCOS:
1584     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1585   case ISD::FSIN:
1586     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1587   default:
1588     llvm_unreachable("Wrong trig opcode");
1589   }
1590 }
1591
1592 //===----------------------------------------------------------------------===//
1593 // Custom DAG optimizations
1594 //===----------------------------------------------------------------------===//
1595
1596 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1597                                                      DAGCombinerInfo &DCI) const {
1598   EVT VT = N->getValueType(0);
1599   EVT ScalarVT = VT.getScalarType();
1600   if (ScalarVT != MVT::f32)
1601     return SDValue();
1602
1603   SelectionDAG &DAG = DCI.DAG;
1604   SDLoc DL(N);
1605
1606   SDValue Src = N->getOperand(0);
1607   EVT SrcVT = Src.getValueType();
1608
1609   // TODO: We could try to match extracting the higher bytes, which would be
1610   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1611   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1612   // about in practice.
1613   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1614     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1615       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1616       DCI.AddToWorklist(Cvt.getNode());
1617       return Cvt;
1618     }
1619   }
1620
1621   // We are primarily trying to catch operations on illegal vector types
1622   // before they are expanded.
1623   // For scalars, we can use the more flexible method of checking masked bits
1624   // after legalization.
1625   if (!DCI.isBeforeLegalize() ||
1626       !SrcVT.isVector() ||
1627       SrcVT.getVectorElementType() != MVT::i8) {
1628     return SDValue();
1629   }
1630
1631   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1632
1633   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1634   // size as 4.
1635   unsigned NElts = SrcVT.getVectorNumElements();
1636   if (!SrcVT.isSimple() && NElts != 3)
1637     return SDValue();
1638
1639   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1640   // prevent a mess from expanding to v4i32 and repacking.
1641   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1642     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1643     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1644     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1645     LoadSDNode *Load = cast<LoadSDNode>(Src);
1646
1647     unsigned AS = Load->getAddressSpace();
1648     unsigned Align = Load->getAlignment();
1649     Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1650     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1651
1652     // Don't try to replace the load if we have to expand it due to alignment
1653     // problems. Otherwise we will end up scalarizing the load, and trying to
1654     // repack into the vector for no real reason.
1655     if (Align < ABIAlignment &&
1656         !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1657       return SDValue();
1658     }
1659
1660     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1661                                      Load->getChain(),
1662                                      Load->getBasePtr(),
1663                                      LoadVT,
1664                                      Load->getMemOperand());
1665
1666     // Make sure successors of the original load stay after it by updating
1667     // them to use the new Chain.
1668     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1669
1670     SmallVector<SDValue, 4> Elts;
1671     if (RegVT.isVector())
1672       DAG.ExtractVectorElements(NewLoad, Elts);
1673     else
1674       Elts.push_back(NewLoad);
1675
1676     SmallVector<SDValue, 4> Ops;
1677
1678     unsigned EltIdx = 0;
1679     for (SDValue Elt : Elts) {
1680       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1681       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1682         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1683         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1684         DCI.AddToWorklist(Cvt.getNode());
1685         Ops.push_back(Cvt);
1686       }
1687
1688       ++EltIdx;
1689     }
1690
1691     assert(Ops.size() == NElts);
1692
1693     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1694   }
1695
1696   return SDValue();
1697 }
1698
1699 /// \brief Return true if the given offset Size in bytes can be folded into
1700 /// the immediate offsets of a memory instruction for the given address space.
1701 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1702                           const AMDGPUSubtarget &STI) {
1703   switch (AS) {
1704   case AMDGPUAS::GLOBAL_ADDRESS: {
1705     // MUBUF instructions a 12-bit offset in bytes.
1706     return isUInt<12>(OffsetSize);
1707   }
1708   case AMDGPUAS::CONSTANT_ADDRESS: {
1709     // SMRD instructions have an 8-bit offset in dwords on SI and
1710     // a 20-bit offset in bytes on VI.
1711     if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1712       return isUInt<20>(OffsetSize);
1713     else
1714       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1715   }
1716   case AMDGPUAS::LOCAL_ADDRESS:
1717   case AMDGPUAS::REGION_ADDRESS: {
1718     // The single offset versions have a 16-bit offset in bytes.
1719     return isUInt<16>(OffsetSize);
1720   }
1721   case AMDGPUAS::PRIVATE_ADDRESS:
1722   // Indirect register addressing does not use any offsets.
1723   default:
1724     return 0;
1725   }
1726 }
1727
1728 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1729
1730 // This is a variant of
1731 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1732 //
1733 // The normal DAG combiner will do this, but only if the add has one use since
1734 // that would increase the number of instructions.
1735 //
1736 // This prevents us from seeing a constant offset that can be folded into a
1737 // memory instruction's addressing mode. If we know the resulting add offset of
1738 // a pointer can be folded into an addressing offset, we can replace the pointer
1739 // operand with the add of new constant offset. This eliminates one of the uses,
1740 // and may allow the remaining use to also be simplified.
1741 //
1742 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1743                                                unsigned AddrSpace,
1744                                                DAGCombinerInfo &DCI) const {
1745   SDValue N0 = N->getOperand(0);
1746   SDValue N1 = N->getOperand(1);
1747
1748   if (N0.getOpcode() != ISD::ADD)
1749     return SDValue();
1750
1751   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1752   if (!CN1)
1753     return SDValue();
1754
1755   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1756   if (!CAdd)
1757     return SDValue();
1758
1759   // If the resulting offset is too large, we can't fold it into the addressing
1760   // mode offset.
1761   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1762   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1763     return SDValue();
1764
1765   SelectionDAG &DAG = DCI.DAG;
1766   SDLoc SL(N);
1767   EVT VT = N->getValueType(0);
1768
1769   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1770   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1771
1772   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1773 }
1774
1775 SDValue SITargetLowering::performAndCombine(SDNode *N,
1776                                             DAGCombinerInfo &DCI) const {
1777   if (DCI.isBeforeLegalize())
1778     return SDValue();
1779
1780   SelectionDAG &DAG = DCI.DAG;
1781
1782   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1783   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1784   SDValue LHS = N->getOperand(0);
1785   SDValue RHS = N->getOperand(1);
1786
1787   if (LHS.getOpcode() == ISD::SETCC &&
1788       RHS.getOpcode() == ISD::SETCC) {
1789     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1790     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1791
1792     SDValue X = LHS.getOperand(0);
1793     SDValue Y = RHS.getOperand(0);
1794     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1795       return SDValue();
1796
1797     if (LCC == ISD::SETO) {
1798       if (X != LHS.getOperand(1))
1799         return SDValue();
1800
1801       if (RCC == ISD::SETUNE) {
1802         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1803         if (!C1 || !C1->isInfinity() || C1->isNegative())
1804           return SDValue();
1805
1806         const uint32_t Mask = SIInstrFlags::N_NORMAL |
1807                               SIInstrFlags::N_SUBNORMAL |
1808                               SIInstrFlags::N_ZERO |
1809                               SIInstrFlags::P_ZERO |
1810                               SIInstrFlags::P_SUBNORMAL |
1811                               SIInstrFlags::P_NORMAL;
1812
1813         static_assert(((~(SIInstrFlags::S_NAN |
1814                           SIInstrFlags::Q_NAN |
1815                           SIInstrFlags::N_INFINITY |
1816                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1817                       "mask not equal");
1818
1819         SDLoc DL(N);
1820         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1821                            X, DAG.getConstant(Mask, DL, MVT::i32));
1822       }
1823     }
1824   }
1825
1826   return SDValue();
1827 }
1828
1829 SDValue SITargetLowering::performOrCombine(SDNode *N,
1830                                            DAGCombinerInfo &DCI) const {
1831   SelectionDAG &DAG = DCI.DAG;
1832   SDValue LHS = N->getOperand(0);
1833   SDValue RHS = N->getOperand(1);
1834
1835   // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1836   if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1837       RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1838     SDValue Src = LHS.getOperand(0);
1839     if (Src != RHS.getOperand(0))
1840       return SDValue();
1841
1842     const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1843     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1844     if (!CLHS || !CRHS)
1845       return SDValue();
1846
1847     // Only 10 bits are used.
1848     static const uint32_t MaxMask = 0x3ff;
1849
1850     uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1851     SDLoc DL(N);
1852     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1853                        Src, DAG.getConstant(NewMask, DL, MVT::i32));
1854   }
1855
1856   return SDValue();
1857 }
1858
1859 SDValue SITargetLowering::performClassCombine(SDNode *N,
1860                                               DAGCombinerInfo &DCI) const {
1861   SelectionDAG &DAG = DCI.DAG;
1862   SDValue Mask = N->getOperand(1);
1863
1864   // fp_class x, 0 -> false
1865   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1866     if (CMask->isNullValue())
1867       return DAG.getConstant(0, SDLoc(N), MVT::i1);
1868   }
1869
1870   return SDValue();
1871 }
1872
1873 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1874   switch (Opc) {
1875   case ISD::FMAXNUM:
1876     return AMDGPUISD::FMAX3;
1877   case ISD::SMAX:
1878     return AMDGPUISD::SMAX3;
1879   case ISD::UMAX:
1880     return AMDGPUISD::UMAX3;
1881   case ISD::FMINNUM:
1882     return AMDGPUISD::FMIN3;
1883   case ISD::SMIN:
1884     return AMDGPUISD::SMIN3;
1885   case ISD::UMIN:
1886     return AMDGPUISD::UMIN3;
1887   default:
1888     llvm_unreachable("Not a min/max opcode");
1889   }
1890 }
1891
1892 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1893                                                  DAGCombinerInfo &DCI) const {
1894   SelectionDAG &DAG = DCI.DAG;
1895
1896   unsigned Opc = N->getOpcode();
1897   SDValue Op0 = N->getOperand(0);
1898   SDValue Op1 = N->getOperand(1);
1899
1900   // Only do this if the inner op has one use since this will just increases
1901   // register pressure for no benefit.
1902
1903   // max(max(a, b), c)
1904   if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1905     SDLoc DL(N);
1906     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1907                        DL,
1908                        N->getValueType(0),
1909                        Op0.getOperand(0),
1910                        Op0.getOperand(1),
1911                        Op1);
1912   }
1913
1914   // max(a, max(b, c))
1915   if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1916     SDLoc DL(N);
1917     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1918                        DL,
1919                        N->getValueType(0),
1920                        Op0,
1921                        Op1.getOperand(0),
1922                        Op1.getOperand(1));
1923   }
1924
1925   return SDValue();
1926 }
1927
1928 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1929                                               DAGCombinerInfo &DCI) const {
1930   SelectionDAG &DAG = DCI.DAG;
1931   SDLoc SL(N);
1932
1933   SDValue LHS = N->getOperand(0);
1934   SDValue RHS = N->getOperand(1);
1935   EVT VT = LHS.getValueType();
1936
1937   if (VT != MVT::f32 && VT != MVT::f64)
1938     return SDValue();
1939
1940   // Match isinf pattern
1941   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1942   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1943   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1944     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1945     if (!CRHS)
1946       return SDValue();
1947
1948     const APFloat &APF = CRHS->getValueAPF();
1949     if (APF.isInfinity() && !APF.isNegative()) {
1950       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1951       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1952                          DAG.getConstant(Mask, SL, MVT::i32));
1953     }
1954   }
1955
1956   return SDValue();
1957 }
1958
1959 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1960                                             DAGCombinerInfo &DCI) const {
1961   SelectionDAG &DAG = DCI.DAG;
1962   SDLoc DL(N);
1963
1964   switch (N->getOpcode()) {
1965   default:
1966     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1967   case ISD::SETCC:
1968     return performSetCCCombine(N, DCI);
1969   case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1970   case ISD::FMINNUM:
1971   case ISD::SMAX:
1972   case ISD::SMIN:
1973   case ISD::UMAX:
1974   case ISD::UMIN: {
1975     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1976         N->getValueType(0) != MVT::f64 &&
1977         getTargetMachine().getOptLevel() > CodeGenOpt::None)
1978       return performMin3Max3Combine(N, DCI);
1979     break;
1980   }
1981
1982   case AMDGPUISD::CVT_F32_UBYTE0:
1983   case AMDGPUISD::CVT_F32_UBYTE1:
1984   case AMDGPUISD::CVT_F32_UBYTE2:
1985   case AMDGPUISD::CVT_F32_UBYTE3: {
1986     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1987
1988     SDValue Src = N->getOperand(0);
1989     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1990
1991     APInt KnownZero, KnownOne;
1992     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1993                                           !DCI.isBeforeLegalizeOps());
1994     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1995     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1996         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1997       DCI.CommitTargetLoweringOpt(TLO);
1998     }
1999
2000     break;
2001   }
2002
2003   case ISD::UINT_TO_FP: {
2004     return performUCharToFloatCombine(N, DCI);
2005
2006   case ISD::FADD: {
2007     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2008       break;
2009
2010     EVT VT = N->getValueType(0);
2011     if (VT != MVT::f32)
2012       break;
2013
2014     // Only do this if we are not trying to support denormals. v_mad_f32 does
2015     // not support denormals ever.
2016     if (Subtarget->hasFP32Denormals())
2017       break;
2018
2019     SDValue LHS = N->getOperand(0);
2020     SDValue RHS = N->getOperand(1);
2021
2022     // These should really be instruction patterns, but writing patterns with
2023     // source modiifiers is a pain.
2024
2025     // fadd (fadd (a, a), b) -> mad 2.0, a, b
2026     if (LHS.getOpcode() == ISD::FADD) {
2027       SDValue A = LHS.getOperand(0);
2028       if (A == LHS.getOperand(1)) {
2029         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2030         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
2031       }
2032     }
2033
2034     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
2035     if (RHS.getOpcode() == ISD::FADD) {
2036       SDValue A = RHS.getOperand(0);
2037       if (A == RHS.getOperand(1)) {
2038         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2039         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
2040       }
2041     }
2042
2043     return SDValue();
2044   }
2045   case ISD::FSUB: {
2046     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2047       break;
2048
2049     EVT VT = N->getValueType(0);
2050
2051     // Try to get the fneg to fold into the source modifier. This undoes generic
2052     // DAG combines and folds them into the mad.
2053     //
2054     // Only do this if we are not trying to support denormals. v_mad_f32 does
2055     // not support denormals ever.
2056     if (VT == MVT::f32 &&
2057         !Subtarget->hasFP32Denormals()) {
2058       SDValue LHS = N->getOperand(0);
2059       SDValue RHS = N->getOperand(1);
2060       if (LHS.getOpcode() == ISD::FADD) {
2061         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
2062
2063         SDValue A = LHS.getOperand(0);
2064         if (A == LHS.getOperand(1)) {
2065           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2066           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
2067
2068           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
2069         }
2070       }
2071
2072       if (RHS.getOpcode() == ISD::FADD) {
2073         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
2074
2075         SDValue A = RHS.getOperand(0);
2076         if (A == RHS.getOperand(1)) {
2077           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
2078           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
2079         }
2080       }
2081
2082       return SDValue();
2083     }
2084
2085     break;
2086   }
2087   }
2088   case ISD::LOAD:
2089   case ISD::STORE:
2090   case ISD::ATOMIC_LOAD:
2091   case ISD::ATOMIC_STORE:
2092   case ISD::ATOMIC_CMP_SWAP:
2093   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2094   case ISD::ATOMIC_SWAP:
2095   case ISD::ATOMIC_LOAD_ADD:
2096   case ISD::ATOMIC_LOAD_SUB:
2097   case ISD::ATOMIC_LOAD_AND:
2098   case ISD::ATOMIC_LOAD_OR:
2099   case ISD::ATOMIC_LOAD_XOR:
2100   case ISD::ATOMIC_LOAD_NAND:
2101   case ISD::ATOMIC_LOAD_MIN:
2102   case ISD::ATOMIC_LOAD_MAX:
2103   case ISD::ATOMIC_LOAD_UMIN:
2104   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
2105     if (DCI.isBeforeLegalize())
2106       break;
2107
2108     MemSDNode *MemNode = cast<MemSDNode>(N);
2109     SDValue Ptr = MemNode->getBasePtr();
2110
2111     // TODO: We could also do this for multiplies.
2112     unsigned AS = MemNode->getAddressSpace();
2113     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
2114       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
2115       if (NewPtr) {
2116         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
2117
2118         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
2119         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
2120       }
2121     }
2122     break;
2123   }
2124   case ISD::AND:
2125     return performAndCombine(N, DCI);
2126   case ISD::OR:
2127     return performOrCombine(N, DCI);
2128   case AMDGPUISD::FP_CLASS:
2129     return performClassCombine(N, DCI);
2130   }
2131   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2132 }
2133
2134 /// \brief Analyze the possible immediate value Op
2135 ///
2136 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
2137 /// and the immediate value if it's a literal immediate
2138 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
2139
2140   const SIInstrInfo *TII =
2141       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2142
2143   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2144     if (TII->isInlineConstant(Node->getAPIntValue()))
2145       return 0;
2146
2147     uint64_t Val = Node->getZExtValue();
2148     return isUInt<32>(Val) ? Val : -1;
2149   }
2150
2151   if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2152     if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2153       return 0;
2154
2155     if (Node->getValueType(0) == MVT::f32)
2156       return FloatToBits(Node->getValueAPF().convertToFloat());
2157
2158     return -1;
2159   }
2160
2161   return -1;
2162 }
2163
2164 /// \brief Helper function for adjustWritemask
2165 static unsigned SubIdx2Lane(unsigned Idx) {
2166   switch (Idx) {
2167   default: return 0;
2168   case AMDGPU::sub0: return 0;
2169   case AMDGPU::sub1: return 1;
2170   case AMDGPU::sub2: return 2;
2171   case AMDGPU::sub3: return 3;
2172   }
2173 }
2174
2175 /// \brief Adjust the writemask of MIMG instructions
2176 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2177                                        SelectionDAG &DAG) const {
2178   SDNode *Users[4] = { };
2179   unsigned Lane = 0;
2180   unsigned OldDmask = Node->getConstantOperandVal(0);
2181   unsigned NewDmask = 0;
2182
2183   // Try to figure out the used register components
2184   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2185        I != E; ++I) {
2186
2187     // Abort if we can't understand the usage
2188     if (!I->isMachineOpcode() ||
2189         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2190       return;
2191
2192     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2193     // Note that subregs are packed, i.e. Lane==0 is the first bit set
2194     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2195     // set, etc.
2196     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2197
2198     // Set which texture component corresponds to the lane.
2199     unsigned Comp;
2200     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2201       assert(Dmask);
2202       Comp = countTrailingZeros(Dmask);
2203       Dmask &= ~(1 << Comp);
2204     }
2205
2206     // Abort if we have more than one user per component
2207     if (Users[Lane])
2208       return;
2209
2210     Users[Lane] = *I;
2211     NewDmask |= 1 << Comp;
2212   }
2213
2214   // Abort if there's no change
2215   if (NewDmask == OldDmask)
2216     return;
2217
2218   // Adjust the writemask in the node
2219   std::vector<SDValue> Ops;
2220   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2221   Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2222   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2223
2224   // If we only got one lane, replace it with a copy
2225   // (if NewDmask has only one bit set...)
2226   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2227     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2228                                        MVT::i32);
2229     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2230                                       SDLoc(), Users[Lane]->getValueType(0),
2231                                       SDValue(Node, 0), RC);
2232     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2233     return;
2234   }
2235
2236   // Update the users of the node with the new indices
2237   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2238
2239     SDNode *User = Users[i];
2240     if (!User)
2241       continue;
2242
2243     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2244     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2245
2246     switch (Idx) {
2247     default: break;
2248     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2249     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2250     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2251     }
2252   }
2253 }
2254
2255 static bool isFrameIndexOp(SDValue Op) {
2256   if (Op.getOpcode() == ISD::AssertZext)
2257     Op = Op.getOperand(0);
2258
2259   return isa<FrameIndexSDNode>(Op);
2260 }
2261
2262 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2263 /// with frame index operands.
2264 /// LLVM assumes that inputs are to these instructions are registers.
2265 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2266                                                      SelectionDAG &DAG) const {
2267
2268   SmallVector<SDValue, 8> Ops;
2269   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2270     if (!isFrameIndexOp(Node->getOperand(i))) {
2271       Ops.push_back(Node->getOperand(i));
2272       continue;
2273     }
2274
2275     SDLoc DL(Node);
2276     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2277                                      Node->getOperand(i).getValueType(),
2278                                      Node->getOperand(i)), 0));
2279   }
2280
2281   DAG.UpdateNodeOperands(Node, Ops);
2282 }
2283
2284 /// \brief Fold the instructions after selecting them.
2285 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2286                                           SelectionDAG &DAG) const {
2287   const SIInstrInfo *TII =
2288       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2289
2290   if (TII->isMIMG(Node->getMachineOpcode()))
2291     adjustWritemask(Node, DAG);
2292
2293   if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2294       Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2295     legalizeTargetIndependentNode(Node, DAG);
2296     return Node;
2297   }
2298   return Node;
2299 }
2300
2301 /// \brief Assign the register class depending on the number of
2302 /// bits set in the writemask
2303 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2304                                                      SDNode *Node) const {
2305   const SIInstrInfo *TII =
2306       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2307
2308   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2309
2310   if (TII->isVOP3(MI->getOpcode())) {
2311     // Make sure constant bus requirements are respected.
2312     TII->legalizeOperandsVOP3(MRI, MI);
2313     return;
2314   }
2315
2316   if (TII->isMIMG(*MI)) {
2317     unsigned VReg = MI->getOperand(0).getReg();
2318     unsigned Writemask = MI->getOperand(1).getImm();
2319     unsigned BitsSet = 0;
2320     for (unsigned i = 0; i < 4; ++i)
2321       BitsSet += Writemask & (1 << i) ? 1 : 0;
2322
2323     const TargetRegisterClass *RC;
2324     switch (BitsSet) {
2325     default: return;
2326     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
2327     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
2328     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
2329     }
2330
2331     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2332     MI->setDesc(TII->get(NewOpcode));
2333     MRI.setRegClass(VReg, RC);
2334     return;
2335   }
2336
2337   // Replace unused atomics with the no return version.
2338   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2339   if (NoRetAtomicOp != -1) {
2340     if (!Node->hasAnyUseOfValue(0)) {
2341       MI->setDesc(TII->get(NoRetAtomicOp));
2342       MI->RemoveOperand(0);
2343     }
2344
2345     return;
2346   }
2347 }
2348
2349 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2350   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2351   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2352 }
2353
2354 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2355                                                 SDLoc DL,
2356                                                 SDValue Ptr) const {
2357   const SIInstrInfo *TII =
2358     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2359
2360   // Build the half of the subregister with the constants before building the
2361   // full 128-bit register. If we are building multiple resource descriptors,
2362   // this will allow CSEing of the 2-component register.
2363   const SDValue Ops0[] = {
2364     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2365     buildSMovImm32(DAG, DL, 0),
2366     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2367     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2368     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2369   };
2370
2371   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2372                                                 MVT::v2i32, Ops0), 0);
2373
2374   // Combine the constants and the pointer.
2375   const SDValue Ops1[] = {
2376     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2377     Ptr,
2378     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2379     SubRegHi,
2380     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2381   };
2382
2383   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2384 }
2385
2386 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2387 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2388 ///        of the resource descriptor) to create an offset, which is added to
2389 ///        the resource pointer.
2390 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2391                                            SDLoc DL,
2392                                            SDValue Ptr,
2393                                            uint32_t RsrcDword1,
2394                                            uint64_t RsrcDword2And3) const {
2395   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2396   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2397   if (RsrcDword1) {
2398     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2399                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2400                     0);
2401   }
2402
2403   SDValue DataLo = buildSMovImm32(DAG, DL,
2404                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2405   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2406
2407   const SDValue Ops[] = {
2408     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2409     PtrLo,
2410     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2411     PtrHi,
2412     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2413     DataLo,
2414     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2415     DataHi,
2416     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2417   };
2418
2419   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2420 }
2421
2422 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2423                                                const TargetRegisterClass *RC,
2424                                                unsigned Reg, EVT VT) const {
2425   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2426
2427   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2428                             cast<RegisterSDNode>(VReg)->getReg(), VT);
2429 }
2430
2431 //===----------------------------------------------------------------------===//
2432 //                         SI Inline Assembly Support
2433 //===----------------------------------------------------------------------===//
2434
2435 std::pair<unsigned, const TargetRegisterClass *>
2436 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2437                                                StringRef Constraint,
2438                                                MVT VT) const {
2439
2440   if (Constraint.size() == 1) {
2441     switch (Constraint[0]) {
2442     case 's':
2443     case 'r':
2444       switch (VT.getSizeInBits()) {
2445       default:
2446         return std::make_pair(0U, nullptr);
2447       case 32:
2448         return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2449       case 64:
2450         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2451       case 128:
2452         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
2453       case 256:
2454         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
2455       }
2456
2457     case 'v':
2458       switch (VT.getSizeInBits()) {
2459       default:
2460         return std::make_pair(0U, nullptr);
2461       case 32:
2462         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
2463       case 64:
2464         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
2465       case 96:
2466         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
2467       case 128:
2468         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
2469       case 256:
2470         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
2471       case 512:
2472         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
2473       }
2474     }
2475   }
2476
2477   if (Constraint.size() > 1) {
2478     const TargetRegisterClass *RC = nullptr;
2479     if (Constraint[1] == 'v') {
2480       RC = &AMDGPU::VGPR_32RegClass;
2481     } else if (Constraint[1] == 's') {
2482       RC = &AMDGPU::SGPR_32RegClass;
2483     }
2484
2485     if (RC) {
2486       uint32_t Idx;
2487       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2488       if (!Failed && Idx < RC->getNumRegs())
2489         return std::make_pair(RC->getRegister(Idx), RC);
2490     }
2491   }
2492   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2493 }
2494
2495 SITargetLowering::ConstraintType
2496 SITargetLowering::getConstraintType(StringRef Constraint) const {
2497   if (Constraint.size() == 1) {
2498     switch (Constraint[0]) {
2499     default: break;
2500     case 's':
2501     case 'v':
2502       return C_RegisterClass;
2503     }
2504   }
2505   return TargetLowering::getConstraintType(Constraint);
2506 }