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