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