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