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/ADT/StringSwitch.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/ADT/SmallString.h"
37 
38 using namespace llvm;
39 
40 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
41   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
42   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
43     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
44       return AMDGPU::SGPR0 + Reg;
45     }
46   }
47   llvm_unreachable("Cannot allocate sgpr");
48 }
49 
50 SITargetLowering::SITargetLowering(TargetMachine &TM,
51                                    const AMDGPUSubtarget &STI)
52     : AMDGPUTargetLowering(TM, STI) {
53   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
54   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
55 
56   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
57   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
58 
59   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
60   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
61   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
62 
63   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
64   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
65 
66   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
67   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
68 
69   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
70   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
71 
72   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
73   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
74 
75   computeRegisterProperties(STI.getRegisterInfo());
76 
77   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
78   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
79   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
80   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
81 
82   setOperationAction(ISD::ADD, MVT::i32, Legal);
83   setOperationAction(ISD::ADDC, MVT::i32, Legal);
84   setOperationAction(ISD::ADDE, MVT::i32, Legal);
85   setOperationAction(ISD::SUBC, MVT::i32, Legal);
86   setOperationAction(ISD::SUBE, MVT::i32, Legal);
87 
88   setOperationAction(ISD::FSIN, MVT::f32, Custom);
89   setOperationAction(ISD::FCOS, MVT::f32, Custom);
90 
91   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
92   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
93 
94   // We need to custom lower vector stores from local memory
95   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
96   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
97   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
98 
99   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
100   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
101 
102   setOperationAction(ISD::STORE, MVT::i1, Custom);
103   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
104 
105   setOperationAction(ISD::SELECT, MVT::i64, Custom);
106   setOperationAction(ISD::SELECT, MVT::f64, Promote);
107   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
108 
109   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
110   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
111   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
112   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
113 
114   setOperationAction(ISD::SETCC, MVT::i1, Promote);
115   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
116   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
117 
118   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
119   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
120 
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
124 
125   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
128 
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
131   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
132 
133   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
134   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
135 
136   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
137   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
138   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
139   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
140 
141   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
142 
143   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
144   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
145   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
146   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
147   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
148   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
149 
150   // On SI this is s_memtime and s_memrealtime on VI.
151   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
152 
153   for (MVT VT : MVT::integer_valuetypes()) {
154     if (VT == MVT::i64)
155       continue;
156 
157     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
158     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
159     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
160     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
161 
162     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
163     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
164     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
165     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
166 
167     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
168     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
169     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
170     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
171   }
172 
173   for (MVT VT : MVT::integer_vector_valuetypes()) {
174     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
175     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
176   }
177 
178   for (MVT VT : MVT::fp_valuetypes())
179     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
180 
181   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
182   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
183 
184   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
185   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
186   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
187   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
188 
189 
190   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
191 
192   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
193   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
194 
195   setOperationAction(ISD::LOAD, MVT::i1, Custom);
196 
197   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
198   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
199 
200   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
201   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
202 
203   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
204 
205   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
206   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
207   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
208 
209   // These should use UDIVREM, so set them to expand
210   setOperationAction(ISD::UDIV, MVT::i64, Expand);
211   setOperationAction(ISD::UREM, MVT::i64, Expand);
212 
213   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
214   setOperationAction(ISD::SELECT, MVT::i1, Promote);
215 
216   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
217 
218 
219   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
220 
221   // We only support LOAD/STORE and vector manipulation ops for vectors
222   // with > 4 elements.
223   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
224     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
225       switch(Op) {
226       case ISD::LOAD:
227       case ISD::STORE:
228       case ISD::BUILD_VECTOR:
229       case ISD::BITCAST:
230       case ISD::EXTRACT_VECTOR_ELT:
231       case ISD::INSERT_VECTOR_ELT:
232       case ISD::INSERT_SUBVECTOR:
233       case ISD::EXTRACT_SUBVECTOR:
234       case ISD::SCALAR_TO_VECTOR:
235         break;
236       case ISD::CONCAT_VECTORS:
237         setOperationAction(Op, VT, Custom);
238         break;
239       default:
240         setOperationAction(Op, VT, Expand);
241         break;
242       }
243     }
244   }
245 
246   // Most operations are naturally 32-bit vector operations. We only support
247   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
248   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
249     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
250     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
251 
252     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
253     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
254 
255     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
256     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
257 
258     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
259     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
260   }
261 
262   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
263     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
264     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
265     setOperationAction(ISD::FRINT, MVT::f64, Legal);
266   }
267 
268   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
269   setOperationAction(ISD::FDIV, MVT::f32, Custom);
270   setOperationAction(ISD::FDIV, MVT::f64, Custom);
271 
272   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
273   // and output demarshalling
274   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
275   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
276 
277   // We can't return success/failure, only the old value,
278   // let LLVM add the comparison
279   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
280   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
281 
282   setTargetDAGCombine(ISD::FADD);
283   setTargetDAGCombine(ISD::FSUB);
284   setTargetDAGCombine(ISD::FMINNUM);
285   setTargetDAGCombine(ISD::FMAXNUM);
286   setTargetDAGCombine(ISD::SMIN);
287   setTargetDAGCombine(ISD::SMAX);
288   setTargetDAGCombine(ISD::UMIN);
289   setTargetDAGCombine(ISD::UMAX);
290   setTargetDAGCombine(ISD::SETCC);
291   setTargetDAGCombine(ISD::AND);
292   setTargetDAGCombine(ISD::OR);
293   setTargetDAGCombine(ISD::UINT_TO_FP);
294   setTargetDAGCombine(ISD::FCANONICALIZE);
295 
296   // All memory operations. Some folding on the pointer operand is done to help
297   // matching the constant offsets in the addressing modes.
298   setTargetDAGCombine(ISD::LOAD);
299   setTargetDAGCombine(ISD::STORE);
300   setTargetDAGCombine(ISD::ATOMIC_LOAD);
301   setTargetDAGCombine(ISD::ATOMIC_STORE);
302   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
303   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
304   setTargetDAGCombine(ISD::ATOMIC_SWAP);
305   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
306   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
307   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
308   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
309   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
310   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
311   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
312   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
313   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
314   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
315 
316   setSchedulingPreference(Sched::RegPressure);
317 }
318 
319 //===----------------------------------------------------------------------===//
320 // TargetLowering queries
321 //===----------------------------------------------------------------------===//
322 
323 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
324                                           const CallInst &CI,
325                                           unsigned IntrID) const {
326   switch (IntrID) {
327   case Intrinsic::amdgcn_atomic_inc:
328   case Intrinsic::amdgcn_atomic_dec:
329     Info.opc = ISD::INTRINSIC_W_CHAIN;
330     Info.memVT = MVT::getVT(CI.getType());
331     Info.ptrVal = CI.getOperand(0);
332     Info.align = 0;
333     Info.vol = false;
334     Info.readMem = true;
335     Info.writeMem = true;
336     return true;
337   default:
338     return false;
339   }
340 }
341 
342 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
343                                           EVT) const {
344   // SI has some legal vector types, but no legal vector operations. Say no
345   // shuffles are legal in order to prefer scalarizing some vector operations.
346   return false;
347 }
348 
349 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
350   // Flat instructions do not have offsets, and only have the register
351   // address.
352   return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
353 }
354 
355 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
356   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
357   // additionally can do r + r + i with addr64. 32-bit has more addressing
358   // mode options. Depending on the resource constant, it can also do
359   // (i64 r0) + (i32 r1) * (i14 i).
360   //
361   // Private arrays end up using a scratch buffer most of the time, so also
362   // assume those use MUBUF instructions. Scratch loads / stores are currently
363   // implemented as mubuf instructions with offen bit set, so slightly
364   // different than the normal addr64.
365   if (!isUInt<12>(AM.BaseOffs))
366     return false;
367 
368   // FIXME: Since we can split immediate into soffset and immediate offset,
369   // would it make sense to allow any immediate?
370 
371   switch (AM.Scale) {
372   case 0: // r + i or just i, depending on HasBaseReg.
373     return true;
374   case 1:
375     return true; // We have r + r or r + i.
376   case 2:
377     if (AM.HasBaseReg) {
378       // Reject 2 * r + r.
379       return false;
380     }
381 
382     // Allow 2 * r as r + r
383     // Or  2 * r + i is allowed as r + r + i.
384     return true;
385   default: // Don't allow n * r
386     return false;
387   }
388 }
389 
390 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
391                                              const AddrMode &AM, Type *Ty,
392                                              unsigned AS) const {
393   // No global is ever allowed as a base.
394   if (AM.BaseGV)
395     return false;
396 
397   switch (AS) {
398   case AMDGPUAS::GLOBAL_ADDRESS: {
399     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
400       // Assume the we will use FLAT for all global memory accesses
401       // on VI.
402       // FIXME: This assumption is currently wrong.  On VI we still use
403       // MUBUF instructions for the r + i addressing mode.  As currently
404       // implemented, the MUBUF instructions only work on buffer < 4GB.
405       // It may be possible to support > 4GB buffers with MUBUF instructions,
406       // by setting the stride value in the resource descriptor which would
407       // increase the size limit to (stride * 4GB).  However, this is risky,
408       // because it has never been validated.
409       return isLegalFlatAddressingMode(AM);
410     }
411 
412     return isLegalMUBUFAddressingMode(AM);
413   }
414   case AMDGPUAS::CONSTANT_ADDRESS: {
415     // If the offset isn't a multiple of 4, it probably isn't going to be
416     // correctly aligned.
417     if (AM.BaseOffs % 4 != 0)
418       return isLegalMUBUFAddressingMode(AM);
419 
420     // There are no SMRD extloads, so if we have to do a small type access we
421     // will use a MUBUF load.
422     // FIXME?: We also need to do this if unaligned, but we don't know the
423     // alignment here.
424     if (DL.getTypeStoreSize(Ty) < 4)
425       return isLegalMUBUFAddressingMode(AM);
426 
427     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
428       // SMRD instructions have an 8-bit, dword offset on SI.
429       if (!isUInt<8>(AM.BaseOffs / 4))
430         return false;
431     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
432       // On CI+, this can also be a 32-bit literal constant offset. If it fits
433       // in 8-bits, it can use a smaller encoding.
434       if (!isUInt<32>(AM.BaseOffs / 4))
435         return false;
436     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS) {
437       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
438       if (!isUInt<20>(AM.BaseOffs))
439         return false;
440     } else
441       llvm_unreachable("unhandled generation");
442 
443     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
444       return true;
445 
446     if (AM.Scale == 1 && AM.HasBaseReg)
447       return true;
448 
449     return false;
450   }
451 
452   case AMDGPUAS::PRIVATE_ADDRESS:
453   case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
454     return isLegalMUBUFAddressingMode(AM);
455 
456   case AMDGPUAS::LOCAL_ADDRESS:
457   case AMDGPUAS::REGION_ADDRESS: {
458     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
459     // field.
460     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
461     // an 8-bit dword offset but we don't know the alignment here.
462     if (!isUInt<16>(AM.BaseOffs))
463       return false;
464 
465     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
466       return true;
467 
468     if (AM.Scale == 1 && AM.HasBaseReg)
469       return true;
470 
471     return false;
472   }
473   case AMDGPUAS::FLAT_ADDRESS:
474     return isLegalFlatAddressingMode(AM);
475 
476   default:
477     llvm_unreachable("unhandled address space");
478   }
479 }
480 
481 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
482                                                       unsigned AddrSpace,
483                                                       unsigned Align,
484                                                       bool *IsFast) const {
485   if (IsFast)
486     *IsFast = false;
487 
488   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
489   // which isn't a simple VT.
490   if (!VT.isSimple() || VT == MVT::Other)
491     return false;
492 
493   // TODO - CI+ supports unaligned memory accesses, but this requires driver
494   // support.
495 
496   // XXX - The only mention I see of this in the ISA manual is for LDS direct
497   // reads the "byte address and must be dword aligned". Is it also true for the
498   // normal loads and stores?
499   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
500     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
501     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
502     // with adjacent offsets.
503     bool AlignedBy4 = (Align % 4 == 0);
504     if (IsFast)
505       *IsFast = AlignedBy4;
506     return AlignedBy4;
507   }
508 
509   // Smaller than dword value must be aligned.
510   // FIXME: This should be allowed on CI+
511   if (VT.bitsLT(MVT::i32))
512     return false;
513 
514   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
515   // byte-address are ignored, thus forcing Dword alignment.
516   // This applies to private, global, and constant memory.
517   if (IsFast)
518     *IsFast = true;
519 
520   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
521 }
522 
523 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
524                                           unsigned SrcAlign, bool IsMemset,
525                                           bool ZeroMemset,
526                                           bool MemcpyStrSrc,
527                                           MachineFunction &MF) const {
528   // FIXME: Should account for address space here.
529 
530   // The default fallback uses the private pointer size as a guess for a type to
531   // use. Make sure we switch these to 64-bit accesses.
532 
533   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
534     return MVT::v4i32;
535 
536   if (Size >= 8 && DstAlign >= 4)
537     return MVT::v2i32;
538 
539   // Use the default.
540   return MVT::Other;
541 }
542 
543 static bool isFlatGlobalAddrSpace(unsigned AS) {
544   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
545     AS == AMDGPUAS::FLAT_ADDRESS ||
546     AS == AMDGPUAS::CONSTANT_ADDRESS;
547 }
548 
549 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
550                                            unsigned DestAS) const {
551   return isFlatGlobalAddrSpace(SrcAS) &&  isFlatGlobalAddrSpace(DestAS);
552 }
553 
554 
555 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
556   const MemSDNode *MemNode = cast<MemSDNode>(N);
557   const Value *Ptr = MemNode->getMemOperand()->getValue();
558 
559   // UndefValue means this is a load of a kernel input.  These are uniform.
560   // Sometimes LDS instructions have constant pointers
561   if (isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || isa<Constant>(Ptr) ||
562       isa<GlobalValue>(Ptr))
563     return true;
564 
565   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
566   return I && I->getMetadata("amdgpu.uniform");
567 }
568 
569 TargetLoweringBase::LegalizeTypeAction
570 SITargetLowering::getPreferredVectorAction(EVT VT) const {
571   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
572     return TypeSplitVector;
573 
574   return TargetLoweringBase::getPreferredVectorAction(VT);
575 }
576 
577 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
578                                                          Type *Ty) const {
579   const SIInstrInfo *TII =
580       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
581   return TII->isInlineConstant(Imm);
582 }
583 
584 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
585 
586   // SimplifySetCC uses this function to determine whether or not it should
587   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
588   if (VT == MVT::i1 && Op == ISD::SETCC)
589     return false;
590 
591   return TargetLowering::isTypeDesirableForOp(Op, VT);
592 }
593 
594 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
595                                          SDLoc SL, SDValue Chain,
596                                          unsigned Offset, bool Signed) const {
597   const DataLayout &DL = DAG.getDataLayout();
598   MachineFunction &MF = DAG.getMachineFunction();
599   const SIRegisterInfo *TRI =
600       static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
601   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
602 
603   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
604 
605   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
606   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
607   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
608   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
609                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
610   SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
611                             DAG.getConstant(Offset, SL, PtrVT));
612   SDValue PtrOffset = DAG.getUNDEF(PtrVT);
613   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
614 
615   unsigned Align = DL.getABITypeAlignment(Ty);
616 
617   ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
618   if (MemVT.isFloatingPoint())
619     ExtTy = ISD::EXTLOAD;
620 
621   return DAG.getLoad(ISD::UNINDEXED, ExtTy,
622                      VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
623                      false, // isVolatile
624                      true, // isNonTemporal
625                      true, // isInvariant
626                      Align); // Alignment
627 }
628 
629 SDValue SITargetLowering::LowerFormalArguments(
630     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
631     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
632     SmallVectorImpl<SDValue> &InVals) const {
633   const SIRegisterInfo *TRI =
634       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
635 
636   MachineFunction &MF = DAG.getMachineFunction();
637   FunctionType *FType = MF.getFunction()->getFunctionType();
638   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
639   const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
640 
641   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
642     const Function *Fn = MF.getFunction();
643     DiagnosticInfoUnsupported NoGraphicsHSA(
644         *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
645     DAG.getContext()->diagnose(NoGraphicsHSA);
646     return SDValue();
647   }
648 
649   SmallVector<ISD::InputArg, 16> Splits;
650   BitVector Skipped(Ins.size());
651 
652   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
653     const ISD::InputArg &Arg = Ins[i];
654 
655     // First check if it's a PS input addr
656     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
657         !Arg.Flags.isByVal() && PSInputNum <= 15) {
658 
659       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
660         // We can safely skip PS inputs
661         Skipped.set(i);
662         ++PSInputNum;
663         continue;
664       }
665 
666       Info->markPSInputAllocated(PSInputNum);
667       if (Arg.Used)
668         Info->PSInputEna |= 1 << PSInputNum;
669 
670       ++PSInputNum;
671     }
672 
673     // Second split vertices into their elements
674     if (AMDGPU::isShader(CallConv) &&
675         Arg.VT.isVector()) {
676       ISD::InputArg NewArg = Arg;
677       NewArg.Flags.setSplit();
678       NewArg.VT = Arg.VT.getVectorElementType();
679 
680       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
681       // three or five element vertex only needs three or five registers,
682       // NOT four or eight.
683       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
684       unsigned NumElements = ParamType->getVectorNumElements();
685 
686       for (unsigned j = 0; j != NumElements; ++j) {
687         Splits.push_back(NewArg);
688         NewArg.PartOffset += NewArg.VT.getStoreSize();
689       }
690 
691     } else if (AMDGPU::isShader(CallConv)) {
692       Splits.push_back(Arg);
693     }
694   }
695 
696   SmallVector<CCValAssign, 16> ArgLocs;
697   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
698                  *DAG.getContext());
699 
700   // At least one interpolation mode must be enabled or else the GPU will hang.
701   //
702   // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
703   // PSInputAddr, the user wants to enable some bits after the compilation
704   // based on run-time states. Since we can't know what the final PSInputEna
705   // will look like, so we shouldn't do anything here and the user should take
706   // responsibility for the correct programming.
707   //
708   // Otherwise, the following restrictions apply:
709   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
710   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
711   //   enabled too.
712   if (CallConv == CallingConv::AMDGPU_PS &&
713       ((Info->getPSInputAddr() & 0x7F) == 0 ||
714        ((Info->getPSInputAddr() & 0xF) == 0 &&
715 	Info->isPSInputAllocated(11)))) {
716     CCInfo.AllocateReg(AMDGPU::VGPR0);
717     CCInfo.AllocateReg(AMDGPU::VGPR1);
718     Info->markPSInputAllocated(0);
719     Info->PSInputEna |= 1;
720   }
721 
722   if (!AMDGPU::isShader(CallConv)) {
723     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
724                             Splits);
725 
726     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
727   } else {
728     assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() &&
729            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
730            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
731            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
732            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
733            !Info->hasWorkItemIDZ());
734   }
735 
736   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
737   if (Info->hasPrivateSegmentBuffer()) {
738     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
739     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
740     CCInfo.AllocateReg(PrivateSegmentBufferReg);
741   }
742 
743   if (Info->hasDispatchPtr()) {
744     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
745     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
746     CCInfo.AllocateReg(DispatchPtrReg);
747   }
748 
749   if (Info->hasKernargSegmentPtr()) {
750     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
751     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
752     CCInfo.AllocateReg(InputPtrReg);
753   }
754 
755   if (Info->hasFlatScratchInit()) {
756     unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
757     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass);
758     CCInfo.AllocateReg(FlatScratchInitReg);
759   }
760 
761   AnalyzeFormalArguments(CCInfo, Splits);
762 
763   SmallVector<SDValue, 16> Chains;
764 
765   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
766 
767     const ISD::InputArg &Arg = Ins[i];
768     if (Skipped[i]) {
769       InVals.push_back(DAG.getUNDEF(Arg.VT));
770       continue;
771     }
772 
773     CCValAssign &VA = ArgLocs[ArgIdx++];
774     MVT VT = VA.getLocVT();
775 
776     if (VA.isMemLoc()) {
777       VT = Ins[i].VT;
778       EVT MemVT = Splits[i].VT;
779       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
780                               VA.getLocMemOffset();
781       // The first 36 bytes of the input buffer contains information about
782       // thread group and global sizes.
783       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
784                                    Offset, Ins[i].Flags.isSExt());
785       Chains.push_back(Arg.getValue(1));
786 
787       auto *ParamTy =
788         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
789       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
790           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
791         // On SI local pointers are just offsets into LDS, so they are always
792         // less than 16-bits.  On CI and newer they could potentially be
793         // real pointers, so we can't guarantee their size.
794         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
795                           DAG.getValueType(MVT::i16));
796       }
797 
798       InVals.push_back(Arg);
799       Info->ABIArgOffset = Offset + MemVT.getStoreSize();
800       continue;
801     }
802     assert(VA.isRegLoc() && "Parameter must be in a register!");
803 
804     unsigned Reg = VA.getLocReg();
805 
806     if (VT == MVT::i64) {
807       // For now assume it is a pointer
808       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
809                                      &AMDGPU::SReg_64RegClass);
810       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
811       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
812       InVals.push_back(Copy);
813       continue;
814     }
815 
816     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
817 
818     Reg = MF.addLiveIn(Reg, RC);
819     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
820 
821     if (Arg.VT.isVector()) {
822 
823       // Build a vector from the registers
824       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
825       unsigned NumElements = ParamType->getVectorNumElements();
826 
827       SmallVector<SDValue, 4> Regs;
828       Regs.push_back(Val);
829       for (unsigned j = 1; j != NumElements; ++j) {
830         Reg = ArgLocs[ArgIdx++].getLocReg();
831         Reg = MF.addLiveIn(Reg, RC);
832 
833         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
834         Regs.push_back(Copy);
835       }
836 
837       // Fill up the missing vector elements
838       NumElements = Arg.VT.getVectorNumElements() - NumElements;
839       Regs.append(NumElements, DAG.getUNDEF(VT));
840 
841       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
842       continue;
843     }
844 
845     InVals.push_back(Val);
846   }
847 
848   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
849   // these from the dispatch pointer.
850 
851   // Start adding system SGPRs.
852   if (Info->hasWorkGroupIDX()) {
853     unsigned Reg = Info->addWorkGroupIDX();
854     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
855     CCInfo.AllocateReg(Reg);
856   }
857 
858   if (Info->hasWorkGroupIDY()) {
859     unsigned Reg = Info->addWorkGroupIDY();
860     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
861     CCInfo.AllocateReg(Reg);
862   }
863 
864   if (Info->hasWorkGroupIDZ()) {
865     unsigned Reg = Info->addWorkGroupIDZ();
866     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
867     CCInfo.AllocateReg(Reg);
868   }
869 
870   if (Info->hasWorkGroupInfo()) {
871     unsigned Reg = Info->addWorkGroupInfo();
872     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
873     CCInfo.AllocateReg(Reg);
874   }
875 
876   if (Info->hasPrivateSegmentWaveByteOffset()) {
877     // Scratch wave offset passed in system SGPR.
878     unsigned PrivateSegmentWaveByteOffsetReg;
879 
880     if (AMDGPU::isShader(CallConv)) {
881       PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
882       Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
883     } else
884       PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
885 
886     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
887     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
888   }
889 
890   // Now that we've figured out where the scratch register inputs are, see if
891   // should reserve the arguments and use them directly.
892   bool HasStackObjects = MF.getFrameInfo()->hasStackObjects();
893   // Record that we know we have non-spill stack objects so we don't need to
894   // check all stack objects later.
895   if (HasStackObjects)
896     Info->setHasNonSpillStackObjects(true);
897 
898   if (ST.isAmdHsaOS()) {
899     // TODO: Assume we will spill without optimizations.
900     if (HasStackObjects) {
901       // If we have stack objects, we unquestionably need the private buffer
902       // resource. For the HSA ABI, this will be the first 4 user SGPR
903       // inputs. We can reserve those and use them directly.
904 
905       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
906         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
907       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
908 
909       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
910         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
911       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
912     } else {
913       unsigned ReservedBufferReg
914         = TRI->reservedPrivateSegmentBufferReg(MF);
915       unsigned ReservedOffsetReg
916         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
917 
918       // We tentatively reserve the last registers (skipping the last two
919       // which may contain VCC). After register allocation, we'll replace
920       // these with the ones immediately after those which were really
921       // allocated. In the prologue copies will be inserted from the argument
922       // to these reserved registers.
923       Info->setScratchRSrcReg(ReservedBufferReg);
924       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
925     }
926   } else {
927     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
928 
929     // Without HSA, relocations are used for the scratch pointer and the
930     // buffer resource setup is always inserted in the prologue. Scratch wave
931     // offset is still in an input SGPR.
932     Info->setScratchRSrcReg(ReservedBufferReg);
933 
934     if (HasStackObjects) {
935       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
936         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
937       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
938     } else {
939       unsigned ReservedOffsetReg
940         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
941       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
942     }
943   }
944 
945   if (Info->hasWorkItemIDX()) {
946     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
947     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
948     CCInfo.AllocateReg(Reg);
949   }
950 
951   if (Info->hasWorkItemIDY()) {
952     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
953     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
954     CCInfo.AllocateReg(Reg);
955   }
956 
957   if (Info->hasWorkItemIDZ()) {
958     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
959     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
960     CCInfo.AllocateReg(Reg);
961   }
962 
963   if (Chains.empty())
964     return Chain;
965 
966   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
967 }
968 
969 SDValue SITargetLowering::LowerReturn(SDValue Chain,
970                                       CallingConv::ID CallConv,
971                                       bool isVarArg,
972                                       const SmallVectorImpl<ISD::OutputArg> &Outs,
973                                       const SmallVectorImpl<SDValue> &OutVals,
974                                       SDLoc DL, SelectionDAG &DAG) const {
975   MachineFunction &MF = DAG.getMachineFunction();
976   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
977 
978   if (!AMDGPU::isShader(CallConv))
979     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
980                                              OutVals, DL, DAG);
981 
982   Info->setIfReturnsVoid(Outs.size() == 0);
983 
984   SmallVector<ISD::OutputArg, 48> Splits;
985   SmallVector<SDValue, 48> SplitVals;
986 
987   // Split vectors into their elements.
988   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
989     const ISD::OutputArg &Out = Outs[i];
990 
991     if (Out.VT.isVector()) {
992       MVT VT = Out.VT.getVectorElementType();
993       ISD::OutputArg NewOut = Out;
994       NewOut.Flags.setSplit();
995       NewOut.VT = VT;
996 
997       // We want the original number of vector elements here, e.g.
998       // three or five, not four or eight.
999       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1000 
1001       for (unsigned j = 0; j != NumElements; ++j) {
1002         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1003                                    DAG.getConstant(j, DL, MVT::i32));
1004         SplitVals.push_back(Elem);
1005         Splits.push_back(NewOut);
1006         NewOut.PartOffset += NewOut.VT.getStoreSize();
1007       }
1008     } else {
1009       SplitVals.push_back(OutVals[i]);
1010       Splits.push_back(Out);
1011     }
1012   }
1013 
1014   // CCValAssign - represent the assignment of the return value to a location.
1015   SmallVector<CCValAssign, 48> RVLocs;
1016 
1017   // CCState - Info about the registers and stack slots.
1018   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1019                  *DAG.getContext());
1020 
1021   // Analyze outgoing return values.
1022   AnalyzeReturn(CCInfo, Splits);
1023 
1024   SDValue Flag;
1025   SmallVector<SDValue, 48> RetOps;
1026   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1027 
1028   // Copy the result values into the output registers.
1029   for (unsigned i = 0, realRVLocIdx = 0;
1030        i != RVLocs.size();
1031        ++i, ++realRVLocIdx) {
1032     CCValAssign &VA = RVLocs[i];
1033     assert(VA.isRegLoc() && "Can only return in registers!");
1034 
1035     SDValue Arg = SplitVals[realRVLocIdx];
1036 
1037     // Copied from other backends.
1038     switch (VA.getLocInfo()) {
1039     default: llvm_unreachable("Unknown loc info!");
1040     case CCValAssign::Full:
1041       break;
1042     case CCValAssign::BCvt:
1043       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1044       break;
1045     }
1046 
1047     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1048     Flag = Chain.getValue(1);
1049     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1050   }
1051 
1052   // Update chain and glue.
1053   RetOps[0] = Chain;
1054   if (Flag.getNode())
1055     RetOps.push_back(Flag);
1056 
1057   return DAG.getNode(AMDGPUISD::RET_FLAG, DL, MVT::Other, RetOps);
1058 }
1059 
1060 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1061                                              SelectionDAG &DAG) const {
1062   unsigned Reg = StringSwitch<unsigned>(RegName)
1063     .Case("m0", AMDGPU::M0)
1064     .Case("exec", AMDGPU::EXEC)
1065     .Case("exec_lo", AMDGPU::EXEC_LO)
1066     .Case("exec_hi", AMDGPU::EXEC_HI)
1067     .Case("flat_scratch", AMDGPU::FLAT_SCR)
1068     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1069     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1070     .Default(AMDGPU::NoRegister);
1071 
1072   if (Reg == AMDGPU::NoRegister) {
1073     report_fatal_error(Twine("invalid register name \""
1074                              + StringRef(RegName)  + "\"."));
1075 
1076   }
1077 
1078   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
1079       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1080     report_fatal_error(Twine("invalid register \""
1081                              + StringRef(RegName)  + "\" for subtarget."));
1082   }
1083 
1084   switch (Reg) {
1085   case AMDGPU::M0:
1086   case AMDGPU::EXEC_LO:
1087   case AMDGPU::EXEC_HI:
1088   case AMDGPU::FLAT_SCR_LO:
1089   case AMDGPU::FLAT_SCR_HI:
1090     if (VT.getSizeInBits() == 32)
1091       return Reg;
1092     break;
1093   case AMDGPU::EXEC:
1094   case AMDGPU::FLAT_SCR:
1095     if (VT.getSizeInBits() == 64)
1096       return Reg;
1097     break;
1098   default:
1099     llvm_unreachable("missing register type checking");
1100   }
1101 
1102   report_fatal_error(Twine("invalid type for register \""
1103                            + StringRef(RegName) + "\"."));
1104 }
1105 
1106 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1107   MachineInstr *MI, MachineBasicBlock *BB) const {
1108   switch (MI->getOpcode()) {
1109   case AMDGPU::SI_INIT_M0: {
1110     const SIInstrInfo *TII =
1111       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1112     BuildMI(*BB, MI->getIterator(), MI->getDebugLoc(),
1113             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1114       .addOperand(MI->getOperand(0));
1115     MI->eraseFromParent();
1116     break;
1117   }
1118   case AMDGPU::BRANCH:
1119     return BB;
1120   case AMDGPU::GET_GROUPSTATICSIZE: {
1121     const SIInstrInfo *TII =
1122       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1123     MachineFunction *MF = BB->getParent();
1124     SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1125     DebugLoc DL = MI->getDebugLoc();
1126     BuildMI (*BB, MI, DL, TII->get(AMDGPU::S_MOVK_I32))
1127       .addOperand(MI->getOperand(0))
1128       .addImm(MFI->LDSSize);
1129     MI->eraseFromParent();
1130     return BB;
1131   }
1132   default:
1133     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1134   }
1135   return BB;
1136 }
1137 
1138 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1139   // This currently forces unfolding various combinations of fsub into fma with
1140   // free fneg'd operands. As long as we have fast FMA (controlled by
1141   // isFMAFasterThanFMulAndFAdd), we should perform these.
1142 
1143   // When fma is quarter rate, for f64 where add / sub are at best half rate,
1144   // most of these combines appear to be cycle neutral but save on instruction
1145   // count / code size.
1146   return true;
1147 }
1148 
1149 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
1150                                          EVT VT) const {
1151   if (!VT.isVector()) {
1152     return MVT::i1;
1153   }
1154   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1155 }
1156 
1157 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
1158   return MVT::i32;
1159 }
1160 
1161 // Answering this is somewhat tricky and depends on the specific device which
1162 // have different rates for fma or all f64 operations.
1163 //
1164 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1165 // regardless of which device (although the number of cycles differs between
1166 // devices), so it is always profitable for f64.
1167 //
1168 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1169 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1170 // which we can always do even without fused FP ops since it returns the same
1171 // result as the separate operations and since it is always full
1172 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1173 // however does not support denormals, so we do report fma as faster if we have
1174 // a fast fma device and require denormals.
1175 //
1176 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1177   VT = VT.getScalarType();
1178 
1179   if (!VT.isSimple())
1180     return false;
1181 
1182   switch (VT.getSimpleVT().SimpleTy) {
1183   case MVT::f32:
1184     // This is as fast on some subtargets. However, we always have full rate f32
1185     // mad available which returns the same result as the separate operations
1186     // which we should prefer over fma. We can't use this if we want to support
1187     // denormals, so only report this in these cases.
1188     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1189   case MVT::f64:
1190     return true;
1191   default:
1192     break;
1193   }
1194 
1195   return false;
1196 }
1197 
1198 //===----------------------------------------------------------------------===//
1199 // Custom DAG Lowering Operations
1200 //===----------------------------------------------------------------------===//
1201 
1202 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1203   switch (Op.getOpcode()) {
1204   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1205   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
1206   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1207   case ISD::LOAD: {
1208     SDValue Result = LowerLOAD(Op, DAG);
1209     assert((!Result.getNode() ||
1210             Result.getNode()->getNumValues() == 2) &&
1211            "Load should return a value and a chain");
1212     return Result;
1213   }
1214 
1215   case ISD::FSIN:
1216   case ISD::FCOS:
1217     return LowerTrig(Op, DAG);
1218   case ISD::SELECT: return LowerSELECT(Op, DAG);
1219   case ISD::FDIV: return LowerFDIV(Op, DAG);
1220   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
1221   case ISD::STORE: return LowerSTORE(Op, DAG);
1222   case ISD::GlobalAddress: {
1223     MachineFunction &MF = DAG.getMachineFunction();
1224     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1225     return LowerGlobalAddress(MFI, Op, DAG);
1226   }
1227   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1228   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1229   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1230   }
1231   return SDValue();
1232 }
1233 
1234 /// \brief Helper function for LowerBRCOND
1235 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1236 
1237   SDNode *Parent = Value.getNode();
1238   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1239        I != E; ++I) {
1240 
1241     if (I.getUse().get() != Value)
1242       continue;
1243 
1244     if (I->getOpcode() == Opcode)
1245       return *I;
1246   }
1247   return nullptr;
1248 }
1249 
1250 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
1251 
1252   SDLoc SL(Op);
1253   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
1254   unsigned FrameIndex = FINode->getIndex();
1255 
1256   // A FrameIndex node represents a 32-bit offset into scratch memory. If the
1257   // high bit of a frame index offset were to be set, this would mean that it
1258   // represented an offset of ~2GB * 64 = ~128GB from the start of the scratch
1259   // buffer, with 64 being the number of threads per wave.
1260   //
1261   // The maximum private allocation for the entire GPU is 4G, and we are
1262   // concerned with the largest the index could ever be for an individual
1263   // workitem. This will occur with the minmum dispatch size. If a program
1264   // requires more, the dispatch size will be reduced.
1265   //
1266   // With this limit, we can mark the high bit of the FrameIndex node as known
1267   // zero, which is important, because it means in most situations we can prove
1268   // that values derived from FrameIndex nodes are non-negative. This enables us
1269   // to take advantage of more addressing modes when accessing scratch buffers,
1270   // since for scratch reads/writes, the register offset must always be
1271   // positive.
1272 
1273   uint64_t MaxGPUAlloc = UINT64_C(4) * 1024 * 1024 * 1024;
1274 
1275   // XXX - It is unclear if partial dispatch works. Assume it works at half wave
1276   // granularity. It is probably a full wave.
1277   uint64_t MinGranularity = 32;
1278 
1279   unsigned KnownBits = Log2_64(MaxGPUAlloc / MinGranularity);
1280   EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), KnownBits);
1281 
1282   SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
1283   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
1284                      DAG.getValueType(ExtVT));
1285 }
1286 
1287 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
1288   if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN)
1289     return false;
1290 
1291   switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
1292   default: return false;
1293   case AMDGPUIntrinsic::amdgcn_if:
1294   case AMDGPUIntrinsic::amdgcn_else:
1295   case AMDGPUIntrinsic::amdgcn_break:
1296   case AMDGPUIntrinsic::amdgcn_if_break:
1297   case AMDGPUIntrinsic::amdgcn_else_break:
1298   case AMDGPUIntrinsic::amdgcn_loop:
1299   case AMDGPUIntrinsic::amdgcn_end_cf:
1300     return true;
1301   }
1302 }
1303 
1304 /// This transforms the control flow intrinsics to get the branch destination as
1305 /// last parameter, also switches branch target with BR if the need arise
1306 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1307                                       SelectionDAG &DAG) const {
1308 
1309   SDLoc DL(BRCOND);
1310 
1311   SDNode *Intr = BRCOND.getOperand(1).getNode();
1312   SDValue Target = BRCOND.getOperand(2);
1313   SDNode *BR = nullptr;
1314   SDNode *SetCC = nullptr;
1315 
1316   if (Intr->getOpcode() == ISD::SETCC) {
1317     // As long as we negate the condition everything is fine
1318     SetCC = Intr;
1319     Intr = SetCC->getOperand(0).getNode();
1320 
1321   } else {
1322     // Get the target from BR if we don't negate the condition
1323     BR = findUser(BRCOND, ISD::BR);
1324     Target = BR->getOperand(1);
1325   }
1326 
1327   if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN) {
1328     // This is a uniform branch so we don't need to legalize.
1329     return BRCOND;
1330   }
1331 
1332   assert(!SetCC ||
1333         (SetCC->getConstantOperandVal(1) == 1 &&
1334          isCFIntrinsic(Intr) &&
1335          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1336                                                              ISD::SETNE));
1337 
1338   // Build the result and
1339   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1340 
1341   // operands of the new intrinsic call
1342   SmallVector<SDValue, 4> Ops;
1343   Ops.push_back(BRCOND.getOperand(0));
1344   Ops.append(Intr->op_begin() + 1, Intr->op_end());
1345   Ops.push_back(Target);
1346 
1347   // build the new intrinsic call
1348   SDNode *Result = DAG.getNode(
1349     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1350     DAG.getVTList(Res), Ops).getNode();
1351 
1352   if (BR) {
1353     // Give the branch instruction our target
1354     SDValue Ops[] = {
1355       BR->getOperand(0),
1356       BRCOND.getOperand(2)
1357     };
1358     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
1359     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
1360     BR = NewBR.getNode();
1361   }
1362 
1363   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
1364 
1365   // Copy the intrinsic results to registers
1366   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
1367     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
1368     if (!CopyToReg)
1369       continue;
1370 
1371     Chain = DAG.getCopyToReg(
1372       Chain, DL,
1373       CopyToReg->getOperand(1),
1374       SDValue(Result, i - 1),
1375       SDValue());
1376 
1377     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
1378   }
1379 
1380   // Remove the old intrinsic from the chain
1381   DAG.ReplaceAllUsesOfValueWith(
1382     SDValue(Intr, Intr->getNumValues() - 1),
1383     Intr->getOperand(0));
1384 
1385   return Chain;
1386 }
1387 
1388 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1389                                              SDValue Op,
1390                                              SelectionDAG &DAG) const {
1391   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1392 
1393   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1394     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1395 
1396   SDLoc DL(GSD);
1397   const GlobalValue *GV = GSD->getGlobal();
1398   MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
1399 
1400   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
1401   return DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT, GA);
1402 }
1403 
1404 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1405                                    SDValue V) const {
1406   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
1407   // the destination register.
1408   //
1409   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1410   // so we will end up with redundant moves to m0.
1411   //
1412   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
1413 
1414   // A Null SDValue creates a glue result.
1415   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
1416                                   V, Chain);
1417   return SDValue(M0, 0);
1418 }
1419 
1420 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1421                                                  SDValue Op,
1422                                                  MVT VT,
1423                                                  unsigned Offset) const {
1424   SDLoc SL(Op);
1425   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1426                                  DAG.getEntryNode(), Offset, false);
1427   // The local size values will have the hi 16-bits as zero.
1428   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1429                      DAG.getValueType(VT));
1430 }
1431 
1432 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, EVT VT) {
1433   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
1434                                       "non-hsa intrinsic with hsa target");
1435   DAG.getContext()->diagnose(BadIntrin);
1436   return DAG.getUNDEF(VT);
1437 }
1438 
1439 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1440                                                   SelectionDAG &DAG) const {
1441   MachineFunction &MF = DAG.getMachineFunction();
1442   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1443   const SIRegisterInfo *TRI =
1444       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1445 
1446   EVT VT = Op.getValueType();
1447   SDLoc DL(Op);
1448   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1449 
1450   // TODO: Should this propagate fast-math-flags?
1451 
1452   switch (IntrinsicID) {
1453   case Intrinsic::amdgcn_dispatch_ptr:
1454     if (!Subtarget->isAmdHsaOS()) {
1455       DiagnosticInfoUnsupported BadIntrin(
1456           *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
1457           DL.getDebugLoc());
1458       DAG.getContext()->diagnose(BadIntrin);
1459       return DAG.getUNDEF(VT);
1460     }
1461 
1462     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1463       TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT);
1464   case Intrinsic::amdgcn_rcp:
1465     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
1466   case Intrinsic::amdgcn_rsq:
1467   case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name
1468     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
1469   case Intrinsic::amdgcn_rsq_clamp:
1470   case AMDGPUIntrinsic::AMDGPU_rsq_clamped: { // Legacy name
1471     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
1472       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
1473 
1474     Type *Type = VT.getTypeForEVT(*DAG.getContext());
1475     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
1476     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
1477 
1478     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
1479     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
1480                               DAG.getConstantFP(Max, DL, VT));
1481     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
1482                        DAG.getConstantFP(Min, DL, VT));
1483   }
1484   case Intrinsic::r600_read_ngroups_x:
1485     if (Subtarget->isAmdHsaOS())
1486       return emitNonHSAIntrinsicError(DAG, VT);
1487 
1488     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1489                           SI::KernelInputOffsets::NGROUPS_X, false);
1490   case Intrinsic::r600_read_ngroups_y:
1491     if (Subtarget->isAmdHsaOS())
1492       return emitNonHSAIntrinsicError(DAG, VT);
1493 
1494     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1495                           SI::KernelInputOffsets::NGROUPS_Y, false);
1496   case Intrinsic::r600_read_ngroups_z:
1497     if (Subtarget->isAmdHsaOS())
1498       return emitNonHSAIntrinsicError(DAG, VT);
1499 
1500     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1501                           SI::KernelInputOffsets::NGROUPS_Z, false);
1502   case Intrinsic::r600_read_global_size_x:
1503     if (Subtarget->isAmdHsaOS())
1504       return emitNonHSAIntrinsicError(DAG, VT);
1505 
1506     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1507                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1508   case Intrinsic::r600_read_global_size_y:
1509     if (Subtarget->isAmdHsaOS())
1510       return emitNonHSAIntrinsicError(DAG, VT);
1511 
1512     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1513                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1514   case Intrinsic::r600_read_global_size_z:
1515     if (Subtarget->isAmdHsaOS())
1516       return emitNonHSAIntrinsicError(DAG, VT);
1517 
1518     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1519                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1520   case Intrinsic::r600_read_local_size_x:
1521     if (Subtarget->isAmdHsaOS())
1522       return emitNonHSAIntrinsicError(DAG, VT);
1523 
1524     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1525                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
1526   case Intrinsic::r600_read_local_size_y:
1527     if (Subtarget->isAmdHsaOS())
1528       return emitNonHSAIntrinsicError(DAG, VT);
1529 
1530     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1531                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
1532   case Intrinsic::r600_read_local_size_z:
1533     if (Subtarget->isAmdHsaOS())
1534       return emitNonHSAIntrinsicError(DAG, VT);
1535 
1536     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1537                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
1538   case Intrinsic::amdgcn_read_workdim:
1539   case AMDGPUIntrinsic::AMDGPU_read_workdim: // Legacy name.
1540     // Really only 2 bits.
1541     return lowerImplicitZextParam(DAG, Op, MVT::i8,
1542                                   getImplicitParameterOffset(MFI, GRID_DIM));
1543   case Intrinsic::amdgcn_workgroup_id_x:
1544   case Intrinsic::r600_read_tgid_x:
1545     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1546       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1547   case Intrinsic::amdgcn_workgroup_id_y:
1548   case Intrinsic::r600_read_tgid_y:
1549     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1550       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1551   case Intrinsic::amdgcn_workgroup_id_z:
1552   case Intrinsic::r600_read_tgid_z:
1553     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1554       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1555   case Intrinsic::amdgcn_workitem_id_x:
1556   case Intrinsic::r600_read_tidig_x:
1557     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1558       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1559   case Intrinsic::amdgcn_workitem_id_y:
1560   case Intrinsic::r600_read_tidig_y:
1561     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1562       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1563   case Intrinsic::amdgcn_workitem_id_z:
1564   case Intrinsic::r600_read_tidig_z:
1565     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1566       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1567   case AMDGPUIntrinsic::SI_load_const: {
1568     SDValue Ops[] = {
1569       Op.getOperand(1),
1570       Op.getOperand(2)
1571     };
1572 
1573     MachineMemOperand *MMO = MF.getMachineMemOperand(
1574       MachinePointerInfo(),
1575       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1576       VT.getStoreSize(), 4);
1577     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1578                                    Op->getVTList(), Ops, VT, MMO);
1579   }
1580   case AMDGPUIntrinsic::SI_vs_load_input:
1581     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1582                        Op.getOperand(1),
1583                        Op.getOperand(2),
1584                        Op.getOperand(3));
1585 
1586   case AMDGPUIntrinsic::SI_fs_constant: {
1587     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1588     SDValue Glue = M0.getValue(1);
1589     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1590                        DAG.getConstant(2, DL, MVT::i32), // P0
1591                        Op.getOperand(1), Op.getOperand(2), Glue);
1592   }
1593   case AMDGPUIntrinsic::SI_packf16:
1594     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1595       return DAG.getUNDEF(MVT::i32);
1596     return Op;
1597   case AMDGPUIntrinsic::SI_fs_interp: {
1598     SDValue IJ = Op.getOperand(4);
1599     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1600                             DAG.getConstant(0, DL, MVT::i32));
1601     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1602                             DAG.getConstant(1, DL, MVT::i32));
1603     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1604     SDValue Glue = M0.getValue(1);
1605     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1606                              DAG.getVTList(MVT::f32, MVT::Glue),
1607                              I, Op.getOperand(1), Op.getOperand(2), Glue);
1608     Glue = SDValue(P1.getNode(), 1);
1609     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1610                              Op.getOperand(1), Op.getOperand(2), Glue);
1611   }
1612   case Intrinsic::amdgcn_interp_p1: {
1613     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
1614     SDValue Glue = M0.getValue(1);
1615     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
1616                        Op.getOperand(2), Op.getOperand(3), Glue);
1617   }
1618   case Intrinsic::amdgcn_interp_p2: {
1619     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
1620     SDValue Glue = SDValue(M0.getNode(), 1);
1621     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
1622                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
1623                        Glue);
1624   }
1625   case Intrinsic::amdgcn_sin:
1626     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
1627 
1628   case Intrinsic::amdgcn_cos:
1629     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
1630 
1631   case Intrinsic::amdgcn_log_clamp: {
1632     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
1633       return SDValue();
1634 
1635     DiagnosticInfoUnsupported BadIntrin(
1636       *MF.getFunction(), "intrinsic not supported on subtarget",
1637       DL.getDebugLoc());
1638       DAG.getContext()->diagnose(BadIntrin);
1639       return DAG.getUNDEF(VT);
1640   }
1641   case Intrinsic::amdgcn_ldexp:
1642     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
1643                        Op.getOperand(1), Op.getOperand(2));
1644   case Intrinsic::amdgcn_class:
1645     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
1646                        Op.getOperand(1), Op.getOperand(2));
1647   case Intrinsic::amdgcn_div_fmas:
1648     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
1649                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
1650                        Op.getOperand(4));
1651 
1652   case Intrinsic::amdgcn_div_fixup:
1653     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
1654                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
1655 
1656   case Intrinsic::amdgcn_trig_preop:
1657     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
1658                        Op.getOperand(1), Op.getOperand(2));
1659   case Intrinsic::amdgcn_div_scale: {
1660     // 3rd parameter required to be a constant.
1661     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
1662     if (!Param)
1663       return DAG.getUNDEF(VT);
1664 
1665     // Translate to the operands expected by the machine instruction. The
1666     // first parameter must be the same as the first instruction.
1667     SDValue Numerator = Op.getOperand(1);
1668     SDValue Denominator = Op.getOperand(2);
1669 
1670     // Note this order is opposite of the machine instruction's operations,
1671     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
1672     // intrinsic has the numerator as the first operand to match a normal
1673     // division operation.
1674 
1675     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
1676 
1677     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
1678                        Denominator, Numerator);
1679   }
1680   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
1681     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
1682   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
1683     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
1684   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
1685     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
1686   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
1687     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
1688   default:
1689     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1690   }
1691 }
1692 
1693 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
1694                                                  SelectionDAG &DAG) const {
1695   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1696   switch (IntrID) {
1697   case Intrinsic::amdgcn_atomic_inc:
1698   case Intrinsic::amdgcn_atomic_dec: {
1699     MemSDNode *M = cast<MemSDNode>(Op);
1700     unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
1701       AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
1702     SDValue Ops[] = {
1703       M->getOperand(0), // Chain
1704       M->getOperand(2), // Ptr
1705       M->getOperand(3)  // Value
1706     };
1707 
1708     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
1709                                    M->getMemoryVT(), M->getMemOperand());
1710   }
1711   default:
1712     return SDValue();
1713   }
1714 }
1715 
1716 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1717                                               SelectionDAG &DAG) const {
1718   MachineFunction &MF = DAG.getMachineFunction();
1719   SDLoc DL(Op);
1720   SDValue Chain = Op.getOperand(0);
1721   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1722 
1723   switch (IntrinsicID) {
1724   case AMDGPUIntrinsic::SI_sendmsg: {
1725     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1726     SDValue Glue = Chain.getValue(1);
1727     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1728                        Op.getOperand(2), Glue);
1729   }
1730   case AMDGPUIntrinsic::SI_tbuffer_store: {
1731     SDValue Ops[] = {
1732       Chain,
1733       Op.getOperand(2),
1734       Op.getOperand(3),
1735       Op.getOperand(4),
1736       Op.getOperand(5),
1737       Op.getOperand(6),
1738       Op.getOperand(7),
1739       Op.getOperand(8),
1740       Op.getOperand(9),
1741       Op.getOperand(10),
1742       Op.getOperand(11),
1743       Op.getOperand(12),
1744       Op.getOperand(13),
1745       Op.getOperand(14)
1746     };
1747 
1748     EVT VT = Op.getOperand(3).getValueType();
1749 
1750     MachineMemOperand *MMO = MF.getMachineMemOperand(
1751       MachinePointerInfo(),
1752       MachineMemOperand::MOStore,
1753       VT.getStoreSize(), 4);
1754     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1755                                    Op->getVTList(), Ops, VT, MMO);
1756   }
1757   default:
1758     return SDValue();
1759   }
1760 }
1761 
1762 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1763   SDLoc DL(Op);
1764   LoadSDNode *Load = cast<LoadSDNode>(Op);
1765   ISD::LoadExtType ExtType = Load->getExtensionType();
1766   EVT MemVT = Load->getMemoryVT();
1767 
1768   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
1769     assert(MemVT == MVT::i1 && "Only i1 non-extloads expected");
1770     // FIXME: Copied from PPC
1771     // First, load into 32 bits, then truncate to 1 bit.
1772 
1773     SDValue Chain = Load->getChain();
1774     SDValue BasePtr = Load->getBasePtr();
1775     MachineMemOperand *MMO = Load->getMemOperand();
1776 
1777     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1778                                    BasePtr, MVT::i8, MMO);
1779 
1780     SDValue Ops[] = {
1781       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
1782       NewLD.getValue(1)
1783     };
1784 
1785     return DAG.getMergeValues(Ops, DL);
1786   }
1787 
1788   if (!MemVT.isVector())
1789     return SDValue();
1790 
1791   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1792          "Custom lowering for non-i32 vectors hasn't been implemented.");
1793   unsigned NumElements = MemVT.getVectorNumElements();
1794   assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1795 
1796   switch (Load->getAddressSpace()) {
1797   case AMDGPUAS::CONSTANT_ADDRESS:
1798     if (isMemOpUniform(Load))
1799       return SDValue();
1800     // Non-uniform loads will be selected to MUBUF instructions, so they
1801     // have the same legalization requires ments as global and private
1802     // loads.
1803     //
1804     // Fall-through
1805   case AMDGPUAS::GLOBAL_ADDRESS:
1806   case AMDGPUAS::FLAT_ADDRESS:
1807     if (NumElements > 4)
1808       return SplitVectorLoad(Op, DAG);
1809     // v4 loads are supported for private and global memory.
1810     return SDValue();
1811   case AMDGPUAS::PRIVATE_ADDRESS: {
1812     // Depending on the setting of the private_element_size field in the
1813     // resource descriptor, we can only make private accesses up to a certain
1814     // size.
1815     switch (Subtarget->getMaxPrivateElementSize()) {
1816     case 4:
1817       return scalarizeVectorLoad(Load, DAG);
1818     case 8:
1819       if (NumElements > 2)
1820         return SplitVectorLoad(Op, DAG);
1821       return SDValue();
1822     case 16:
1823       // Same as global/flat
1824       if (NumElements > 4)
1825         return SplitVectorLoad(Op, DAG);
1826       return SDValue();
1827     default:
1828       llvm_unreachable("unsupported private_element_size");
1829     }
1830   }
1831   case AMDGPUAS::LOCAL_ADDRESS:
1832     // If properly aligned, if we split we might be able to use ds_read_b64.
1833     return SplitVectorLoad(Op, DAG);
1834   default:
1835     return SDValue();
1836   }
1837 }
1838 
1839 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1840   if (Op.getValueType() != MVT::i64)
1841     return SDValue();
1842 
1843   SDLoc DL(Op);
1844   SDValue Cond = Op.getOperand(0);
1845 
1846   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1847   SDValue One = DAG.getConstant(1, DL, MVT::i32);
1848 
1849   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1850   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1851 
1852   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1853   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1854 
1855   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1856 
1857   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1858   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1859 
1860   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1861 
1862   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1863   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1864 }
1865 
1866 // Catch division cases where we can use shortcuts with rcp and rsq
1867 // instructions.
1868 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1869   SDLoc SL(Op);
1870   SDValue LHS = Op.getOperand(0);
1871   SDValue RHS = Op.getOperand(1);
1872   EVT VT = Op.getValueType();
1873   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1874 
1875   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1876     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1877         CLHS->isExactlyValue(1.0)) {
1878       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1879       // the CI documentation has a worst case error of 1 ulp.
1880       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1881       // use it as long as we aren't trying to use denormals.
1882 
1883       // 1.0 / sqrt(x) -> rsq(x)
1884       //
1885       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1886       // error seems really high at 2^29 ULP.
1887       if (RHS.getOpcode() == ISD::FSQRT)
1888         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1889 
1890       // 1.0 / x -> rcp(x)
1891       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1892     }
1893   }
1894 
1895   if (Unsafe) {
1896     // Turn into multiply by the reciprocal.
1897     // x / y -> x * (1.0 / y)
1898     SDNodeFlags Flags;
1899     Flags.setUnsafeAlgebra(true);
1900     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1901     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1902   }
1903 
1904   return SDValue();
1905 }
1906 
1907 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1908   if (SDValue FastLowered = LowerFastFDIV(Op, DAG))
1909     return FastLowered;
1910 
1911   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1912   // selection error for now rather than do something incorrect.
1913   if (Subtarget->hasFP32Denormals())
1914     return SDValue();
1915 
1916   SDLoc SL(Op);
1917   SDValue LHS = Op.getOperand(0);
1918   SDValue RHS = Op.getOperand(1);
1919 
1920   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1921 
1922   const APFloat K0Val(BitsToFloat(0x6f800000));
1923   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1924 
1925   const APFloat K1Val(BitsToFloat(0x2f800000));
1926   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1927 
1928   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1929 
1930   EVT SetCCVT =
1931       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1932 
1933   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1934 
1935   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1936 
1937   // TODO: Should this propagate fast-math-flags?
1938 
1939   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1940 
1941   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1942 
1943   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1944 
1945   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1946 }
1947 
1948 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1949   if (DAG.getTarget().Options.UnsafeFPMath)
1950     return LowerFastFDIV(Op, DAG);
1951 
1952   SDLoc SL(Op);
1953   SDValue X = Op.getOperand(0);
1954   SDValue Y = Op.getOperand(1);
1955 
1956   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1957 
1958   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1959 
1960   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1961 
1962   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1963 
1964   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1965 
1966   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1967 
1968   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1969 
1970   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1971 
1972   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1973 
1974   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1975   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1976 
1977   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1978                              NegDivScale0, Mul, DivScale1);
1979 
1980   SDValue Scale;
1981 
1982   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1983     // Workaround a hardware bug on SI where the condition output from div_scale
1984     // is not usable.
1985 
1986     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1987 
1988     // Figure out if the scale to use for div_fmas.
1989     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1990     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1991     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1992     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1993 
1994     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1995     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1996 
1997     SDValue Scale0Hi
1998       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1999     SDValue Scale1Hi
2000       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
2001 
2002     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
2003     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
2004     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
2005   } else {
2006     Scale = DivScale1.getValue(1);
2007   }
2008 
2009   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
2010                              Fma4, Fma3, Mul, Scale);
2011 
2012   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
2013 }
2014 
2015 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
2016   EVT VT = Op.getValueType();
2017 
2018   if (VT == MVT::f32)
2019     return LowerFDIV32(Op, DAG);
2020 
2021   if (VT == MVT::f64)
2022     return LowerFDIV64(Op, DAG);
2023 
2024   llvm_unreachable("Unexpected type for fdiv");
2025 }
2026 
2027 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2028   SDLoc DL(Op);
2029   StoreSDNode *Store = cast<StoreSDNode>(Op);
2030   EVT VT = Store->getMemoryVT();
2031 
2032   if (VT == MVT::i1) {
2033     return DAG.getTruncStore(Store->getChain(), DL,
2034        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
2035        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
2036   }
2037 
2038   assert(Store->getValue().getValueType().getScalarType() == MVT::i32);
2039 
2040   unsigned NumElements = VT.getVectorNumElements();
2041   switch (Store->getAddressSpace()) {
2042   case AMDGPUAS::GLOBAL_ADDRESS:
2043   case AMDGPUAS::FLAT_ADDRESS:
2044     if (NumElements > 4)
2045       return SplitVectorStore(Op, DAG);
2046     return SDValue();
2047   case AMDGPUAS::PRIVATE_ADDRESS: {
2048     switch (Subtarget->getMaxPrivateElementSize()) {
2049     case 4:
2050       return scalarizeVectorStore(Store, DAG);
2051     case 8:
2052       if (NumElements > 2)
2053         return SplitVectorStore(Op, DAG);
2054       return SDValue();
2055     case 16:
2056       if (NumElements > 4)
2057         return SplitVectorStore(Op, DAG);
2058       return SDValue();
2059     default:
2060       llvm_unreachable("unsupported private_element_size");
2061     }
2062   }
2063   case AMDGPUAS::LOCAL_ADDRESS:
2064     // If properly aligned, if we split we might be able to use ds_write_b64.
2065     return SplitVectorStore(Op, DAG);
2066   default:
2067     llvm_unreachable("unhandled address space");
2068   }
2069 }
2070 
2071 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
2072   SDLoc DL(Op);
2073   EVT VT = Op.getValueType();
2074   SDValue Arg = Op.getOperand(0);
2075   // TODO: Should this propagate fast-math-flags?
2076   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
2077                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
2078                                               DAG.getConstantFP(0.5/M_PI, DL,
2079                                                                 VT)));
2080 
2081   switch (Op.getOpcode()) {
2082   case ISD::FCOS:
2083     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
2084   case ISD::FSIN:
2085     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
2086   default:
2087     llvm_unreachable("Wrong trig opcode");
2088   }
2089 }
2090 
2091 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
2092   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
2093   assert(AtomicNode->isCompareAndSwap());
2094   unsigned AS = AtomicNode->getAddressSpace();
2095 
2096   // No custom lowering required for local address space
2097   if (!isFlatGlobalAddrSpace(AS))
2098     return Op;
2099 
2100   // Non-local address space requires custom lowering for atomic compare
2101   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
2102   SDLoc DL(Op);
2103   SDValue ChainIn = Op.getOperand(0);
2104   SDValue Addr = Op.getOperand(1);
2105   SDValue Old = Op.getOperand(2);
2106   SDValue New = Op.getOperand(3);
2107   EVT VT = Op.getValueType();
2108   MVT SimpleVT = VT.getSimpleVT();
2109   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
2110 
2111   SDValue NewOld = DAG.getNode(ISD::BUILD_VECTOR, DL, VecType,
2112                                New, Old);
2113   SDValue Ops[] = { ChainIn, Addr, NewOld };
2114   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2115   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL,
2116                                  VTList, Ops, VT, AtomicNode->getMemOperand());
2117 }
2118 
2119 //===----------------------------------------------------------------------===//
2120 // Custom DAG optimizations
2121 //===----------------------------------------------------------------------===//
2122 
2123 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
2124                                                      DAGCombinerInfo &DCI) const {
2125   EVT VT = N->getValueType(0);
2126   EVT ScalarVT = VT.getScalarType();
2127   if (ScalarVT != MVT::f32)
2128     return SDValue();
2129 
2130   SelectionDAG &DAG = DCI.DAG;
2131   SDLoc DL(N);
2132 
2133   SDValue Src = N->getOperand(0);
2134   EVT SrcVT = Src.getValueType();
2135 
2136   // TODO: We could try to match extracting the higher bytes, which would be
2137   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
2138   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
2139   // about in practice.
2140   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
2141     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
2142       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
2143       DCI.AddToWorklist(Cvt.getNode());
2144       return Cvt;
2145     }
2146   }
2147 
2148   // We are primarily trying to catch operations on illegal vector types
2149   // before they are expanded.
2150   // For scalars, we can use the more flexible method of checking masked bits
2151   // after legalization.
2152   if (!DCI.isBeforeLegalize() ||
2153       !SrcVT.isVector() ||
2154       SrcVT.getVectorElementType() != MVT::i8) {
2155     return SDValue();
2156   }
2157 
2158   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
2159 
2160   // Weird sized vectors are a pain to handle, but we know 3 is really the same
2161   // size as 4.
2162   unsigned NElts = SrcVT.getVectorNumElements();
2163   if (!SrcVT.isSimple() && NElts != 3)
2164     return SDValue();
2165 
2166   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
2167   // prevent a mess from expanding to v4i32 and repacking.
2168   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
2169     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
2170     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
2171     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
2172     LoadSDNode *Load = cast<LoadSDNode>(Src);
2173 
2174     unsigned AS = Load->getAddressSpace();
2175     unsigned Align = Load->getAlignment();
2176     Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
2177     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
2178 
2179     // Don't try to replace the load if we have to expand it due to alignment
2180     // problems. Otherwise we will end up scalarizing the load, and trying to
2181     // repack into the vector for no real reason.
2182     if (Align < ABIAlignment &&
2183         !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
2184       return SDValue();
2185     }
2186 
2187     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
2188                                      Load->getChain(),
2189                                      Load->getBasePtr(),
2190                                      LoadVT,
2191                                      Load->getMemOperand());
2192 
2193     // Make sure successors of the original load stay after it by updating
2194     // them to use the new Chain.
2195     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
2196 
2197     SmallVector<SDValue, 4> Elts;
2198     if (RegVT.isVector())
2199       DAG.ExtractVectorElements(NewLoad, Elts);
2200     else
2201       Elts.push_back(NewLoad);
2202 
2203     SmallVector<SDValue, 4> Ops;
2204 
2205     unsigned EltIdx = 0;
2206     for (SDValue Elt : Elts) {
2207       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
2208       for (unsigned I = 0; I < ComponentsInElt; ++I) {
2209         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
2210         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
2211         DCI.AddToWorklist(Cvt.getNode());
2212         Ops.push_back(Cvt);
2213       }
2214 
2215       ++EltIdx;
2216     }
2217 
2218     assert(Ops.size() == NElts);
2219 
2220     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
2221   }
2222 
2223   return SDValue();
2224 }
2225 
2226 /// \brief Return true if the given offset Size in bytes can be folded into
2227 /// the immediate offsets of a memory instruction for the given address space.
2228 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
2229                           const AMDGPUSubtarget &STI) {
2230   switch (AS) {
2231   case AMDGPUAS::GLOBAL_ADDRESS: {
2232     // MUBUF instructions a 12-bit offset in bytes.
2233     return isUInt<12>(OffsetSize);
2234   }
2235   case AMDGPUAS::CONSTANT_ADDRESS: {
2236     // SMRD instructions have an 8-bit offset in dwords on SI and
2237     // a 20-bit offset in bytes on VI.
2238     if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2239       return isUInt<20>(OffsetSize);
2240     else
2241       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
2242   }
2243   case AMDGPUAS::LOCAL_ADDRESS:
2244   case AMDGPUAS::REGION_ADDRESS: {
2245     // The single offset versions have a 16-bit offset in bytes.
2246     return isUInt<16>(OffsetSize);
2247   }
2248   case AMDGPUAS::PRIVATE_ADDRESS:
2249   // Indirect register addressing does not use any offsets.
2250   default:
2251     return 0;
2252   }
2253 }
2254 
2255 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
2256 
2257 // This is a variant of
2258 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
2259 //
2260 // The normal DAG combiner will do this, but only if the add has one use since
2261 // that would increase the number of instructions.
2262 //
2263 // This prevents us from seeing a constant offset that can be folded into a
2264 // memory instruction's addressing mode. If we know the resulting add offset of
2265 // a pointer can be folded into an addressing offset, we can replace the pointer
2266 // operand with the add of new constant offset. This eliminates one of the uses,
2267 // and may allow the remaining use to also be simplified.
2268 //
2269 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
2270                                                unsigned AddrSpace,
2271                                                DAGCombinerInfo &DCI) const {
2272   SDValue N0 = N->getOperand(0);
2273   SDValue N1 = N->getOperand(1);
2274 
2275   if (N0.getOpcode() != ISD::ADD)
2276     return SDValue();
2277 
2278   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
2279   if (!CN1)
2280     return SDValue();
2281 
2282   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2283   if (!CAdd)
2284     return SDValue();
2285 
2286   // If the resulting offset is too large, we can't fold it into the addressing
2287   // mode offset.
2288   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
2289   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
2290     return SDValue();
2291 
2292   SelectionDAG &DAG = DCI.DAG;
2293   SDLoc SL(N);
2294   EVT VT = N->getValueType(0);
2295 
2296   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
2297   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
2298 
2299   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
2300 }
2301 
2302 SDValue SITargetLowering::performAndCombine(SDNode *N,
2303                                             DAGCombinerInfo &DCI) const {
2304   if (DCI.isBeforeLegalize())
2305     return SDValue();
2306 
2307   if (SDValue Base = AMDGPUTargetLowering::performAndCombine(N, DCI))
2308     return Base;
2309 
2310   SelectionDAG &DAG = DCI.DAG;
2311 
2312   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
2313   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
2314   SDValue LHS = N->getOperand(0);
2315   SDValue RHS = N->getOperand(1);
2316 
2317   if (LHS.getOpcode() == ISD::SETCC &&
2318       RHS.getOpcode() == ISD::SETCC) {
2319     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
2320     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
2321 
2322     SDValue X = LHS.getOperand(0);
2323     SDValue Y = RHS.getOperand(0);
2324     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
2325       return SDValue();
2326 
2327     if (LCC == ISD::SETO) {
2328       if (X != LHS.getOperand(1))
2329         return SDValue();
2330 
2331       if (RCC == ISD::SETUNE) {
2332         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
2333         if (!C1 || !C1->isInfinity() || C1->isNegative())
2334           return SDValue();
2335 
2336         const uint32_t Mask = SIInstrFlags::N_NORMAL |
2337                               SIInstrFlags::N_SUBNORMAL |
2338                               SIInstrFlags::N_ZERO |
2339                               SIInstrFlags::P_ZERO |
2340                               SIInstrFlags::P_SUBNORMAL |
2341                               SIInstrFlags::P_NORMAL;
2342 
2343         static_assert(((~(SIInstrFlags::S_NAN |
2344                           SIInstrFlags::Q_NAN |
2345                           SIInstrFlags::N_INFINITY |
2346                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
2347                       "mask not equal");
2348 
2349         SDLoc DL(N);
2350         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
2351                            X, DAG.getConstant(Mask, DL, MVT::i32));
2352       }
2353     }
2354   }
2355 
2356   return SDValue();
2357 }
2358 
2359 SDValue SITargetLowering::performOrCombine(SDNode *N,
2360                                            DAGCombinerInfo &DCI) const {
2361   SelectionDAG &DAG = DCI.DAG;
2362   SDValue LHS = N->getOperand(0);
2363   SDValue RHS = N->getOperand(1);
2364 
2365   EVT VT = N->getValueType(0);
2366   if (VT == MVT::i64) {
2367     // TODO: This could be a generic combine with a predicate for extracting the
2368     // high half of an integer being free.
2369 
2370     // (or i64:x, (zero_extend i32:y)) ->
2371     //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
2372     if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
2373         RHS.getOpcode() != ISD::ZERO_EXTEND)
2374       std::swap(LHS, RHS);
2375 
2376     if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
2377       SDValue ExtSrc = RHS.getOperand(0);
2378       EVT SrcVT = ExtSrc.getValueType();
2379       if (SrcVT == MVT::i32) {
2380         SDLoc SL(N);
2381         SDValue LowLHS, HiBits;
2382         std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
2383         SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
2384 
2385         DCI.AddToWorklist(LowOr.getNode());
2386         DCI.AddToWorklist(HiBits.getNode());
2387 
2388         SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
2389                                   LowOr, HiBits);
2390         return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2391       }
2392     }
2393   }
2394 
2395   // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
2396   if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
2397       RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
2398     SDValue Src = LHS.getOperand(0);
2399     if (Src != RHS.getOperand(0))
2400       return SDValue();
2401 
2402     const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
2403     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
2404     if (!CLHS || !CRHS)
2405       return SDValue();
2406 
2407     // Only 10 bits are used.
2408     static const uint32_t MaxMask = 0x3ff;
2409 
2410     uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
2411     SDLoc DL(N);
2412     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
2413                        Src, DAG.getConstant(NewMask, DL, MVT::i32));
2414   }
2415 
2416   return SDValue();
2417 }
2418 
2419 SDValue SITargetLowering::performClassCombine(SDNode *N,
2420                                               DAGCombinerInfo &DCI) const {
2421   SelectionDAG &DAG = DCI.DAG;
2422   SDValue Mask = N->getOperand(1);
2423 
2424   // fp_class x, 0 -> false
2425   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
2426     if (CMask->isNullValue())
2427       return DAG.getConstant(0, SDLoc(N), MVT::i1);
2428   }
2429 
2430   return SDValue();
2431 }
2432 
2433 // Constant fold canonicalize.
2434 SDValue SITargetLowering::performFCanonicalizeCombine(
2435   SDNode *N,
2436   DAGCombinerInfo &DCI) const {
2437   ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
2438   if (!CFP)
2439     return SDValue();
2440 
2441   SelectionDAG &DAG = DCI.DAG;
2442   const APFloat &C = CFP->getValueAPF();
2443 
2444   // Flush denormals to 0 if not enabled.
2445   if (C.isDenormal()) {
2446     EVT VT = N->getValueType(0);
2447     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals())
2448       return DAG.getConstantFP(0.0, SDLoc(N), VT);
2449 
2450     if (VT == MVT::f64 && !Subtarget->hasFP64Denormals())
2451       return DAG.getConstantFP(0.0, SDLoc(N), VT);
2452   }
2453 
2454   if (C.isNaN()) {
2455     EVT VT = N->getValueType(0);
2456     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
2457     if (C.isSignaling()) {
2458       // Quiet a signaling NaN.
2459       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
2460     }
2461 
2462     // Make sure it is the canonical NaN bitpattern.
2463     //
2464     // TODO: Can we use -1 as the canonical NaN value since it's an inline
2465     // immediate?
2466     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
2467       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
2468   }
2469 
2470   return SDValue(CFP, 0);
2471 }
2472 
2473 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
2474   switch (Opc) {
2475   case ISD::FMAXNUM:
2476     return AMDGPUISD::FMAX3;
2477   case ISD::SMAX:
2478     return AMDGPUISD::SMAX3;
2479   case ISD::UMAX:
2480     return AMDGPUISD::UMAX3;
2481   case ISD::FMINNUM:
2482     return AMDGPUISD::FMIN3;
2483   case ISD::SMIN:
2484     return AMDGPUISD::SMIN3;
2485   case ISD::UMIN:
2486     return AMDGPUISD::UMIN3;
2487   default:
2488     llvm_unreachable("Not a min/max opcode");
2489   }
2490 }
2491 
2492 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG,
2493                                         SDLoc SL,
2494                                         SDValue Op0,
2495                                         SDValue Op1,
2496                                         bool Signed) {
2497   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
2498   if (!K1)
2499     return SDValue();
2500 
2501   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
2502   if (!K0)
2503     return SDValue();
2504 
2505 
2506   if (Signed) {
2507     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
2508       return SDValue();
2509   } else {
2510     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
2511       return SDValue();
2512   }
2513 
2514   EVT VT = K0->getValueType(0);
2515   return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT,
2516                      Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
2517 }
2518 
2519 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
2520   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
2521     return true;
2522 
2523   return DAG.isKnownNeverNaN(Op);
2524 }
2525 
2526 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG,
2527                                        SDLoc SL,
2528                                        SDValue Op0,
2529                                        SDValue Op1) {
2530   ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
2531   if (!K1)
2532     return SDValue();
2533 
2534   ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
2535   if (!K0)
2536     return SDValue();
2537 
2538   // Ordered >= (although NaN inputs should have folded away by now).
2539   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
2540   if (Cmp == APFloat::cmpGreaterThan)
2541     return SDValue();
2542 
2543   // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
2544   // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
2545   // give the other result, which is different from med3 with a NaN input.
2546   SDValue Var = Op0.getOperand(0);
2547   if (!isKnownNeverSNan(DAG, Var))
2548     return SDValue();
2549 
2550   return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
2551                      Var, SDValue(K0, 0), SDValue(K1, 0));
2552 }
2553 
2554 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
2555                                                DAGCombinerInfo &DCI) const {
2556   SelectionDAG &DAG = DCI.DAG;
2557 
2558   unsigned Opc = N->getOpcode();
2559   SDValue Op0 = N->getOperand(0);
2560   SDValue Op1 = N->getOperand(1);
2561 
2562   // Only do this if the inner op has one use since this will just increases
2563   // register pressure for no benefit.
2564 
2565   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) {
2566     // max(max(a, b), c) -> max3(a, b, c)
2567     // min(min(a, b), c) -> min3(a, b, c)
2568     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
2569       SDLoc DL(N);
2570       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2571                          DL,
2572                          N->getValueType(0),
2573                          Op0.getOperand(0),
2574                          Op0.getOperand(1),
2575                          Op1);
2576     }
2577 
2578     // Try commuted.
2579     // max(a, max(b, c)) -> max3(a, b, c)
2580     // min(a, min(b, c)) -> min3(a, b, c)
2581     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
2582       SDLoc DL(N);
2583       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2584                          DL,
2585                          N->getValueType(0),
2586                          Op0,
2587                          Op1.getOperand(0),
2588                          Op1.getOperand(1));
2589     }
2590   }
2591 
2592   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
2593   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
2594     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
2595       return Med3;
2596   }
2597 
2598   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
2599     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
2600       return Med3;
2601   }
2602 
2603   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
2604   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
2605        (Opc == AMDGPUISD::FMIN_LEGACY &&
2606         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
2607       N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) {
2608     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
2609       return Res;
2610   }
2611 
2612   return SDValue();
2613 }
2614 
2615 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
2616                                               DAGCombinerInfo &DCI) const {
2617   SelectionDAG &DAG = DCI.DAG;
2618   SDLoc SL(N);
2619 
2620   SDValue LHS = N->getOperand(0);
2621   SDValue RHS = N->getOperand(1);
2622   EVT VT = LHS.getValueType();
2623 
2624   if (VT != MVT::f32 && VT != MVT::f64)
2625     return SDValue();
2626 
2627   // Match isinf pattern
2628   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
2629   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2630   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
2631     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
2632     if (!CRHS)
2633       return SDValue();
2634 
2635     const APFloat &APF = CRHS->getValueAPF();
2636     if (APF.isInfinity() && !APF.isNegative()) {
2637       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
2638       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
2639                          DAG.getConstant(Mask, SL, MVT::i32));
2640     }
2641   }
2642 
2643   return SDValue();
2644 }
2645 
2646 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
2647                                             DAGCombinerInfo &DCI) const {
2648   SelectionDAG &DAG = DCI.DAG;
2649   SDLoc DL(N);
2650 
2651   switch (N->getOpcode()) {
2652   default:
2653     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2654   case ISD::SETCC:
2655     return performSetCCCombine(N, DCI);
2656   case ISD::FMAXNUM:
2657   case ISD::FMINNUM:
2658   case ISD::SMAX:
2659   case ISD::SMIN:
2660   case ISD::UMAX:
2661   case ISD::UMIN:
2662   case AMDGPUISD::FMIN_LEGACY:
2663   case AMDGPUISD::FMAX_LEGACY: {
2664     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
2665         N->getValueType(0) != MVT::f64 &&
2666         getTargetMachine().getOptLevel() > CodeGenOpt::None)
2667       return performMinMaxCombine(N, DCI);
2668     break;
2669   }
2670 
2671   case AMDGPUISD::CVT_F32_UBYTE0:
2672   case AMDGPUISD::CVT_F32_UBYTE1:
2673   case AMDGPUISD::CVT_F32_UBYTE2:
2674   case AMDGPUISD::CVT_F32_UBYTE3: {
2675     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
2676 
2677     SDValue Src = N->getOperand(0);
2678     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
2679 
2680     APInt KnownZero, KnownOne;
2681     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2682                                           !DCI.isBeforeLegalizeOps());
2683     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2684     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
2685         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
2686       DCI.CommitTargetLoweringOpt(TLO);
2687     }
2688 
2689     break;
2690   }
2691 
2692   case ISD::UINT_TO_FP: {
2693     return performUCharToFloatCombine(N, DCI);
2694   }
2695   case ISD::FADD: {
2696     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2697       break;
2698 
2699     EVT VT = N->getValueType(0);
2700     if (VT != MVT::f32)
2701       break;
2702 
2703     // Only do this if we are not trying to support denormals. v_mad_f32 does
2704     // not support denormals ever.
2705     if (Subtarget->hasFP32Denormals())
2706       break;
2707 
2708     SDValue LHS = N->getOperand(0);
2709     SDValue RHS = N->getOperand(1);
2710 
2711     // These should really be instruction patterns, but writing patterns with
2712     // source modiifiers is a pain.
2713 
2714     // fadd (fadd (a, a), b) -> mad 2.0, a, b
2715     if (LHS.getOpcode() == ISD::FADD) {
2716       SDValue A = LHS.getOperand(0);
2717       if (A == LHS.getOperand(1)) {
2718         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2719         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
2720       }
2721     }
2722 
2723     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
2724     if (RHS.getOpcode() == ISD::FADD) {
2725       SDValue A = RHS.getOperand(0);
2726       if (A == RHS.getOperand(1)) {
2727         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2728         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
2729       }
2730     }
2731 
2732     return SDValue();
2733   }
2734   case ISD::FSUB: {
2735     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2736       break;
2737 
2738     EVT VT = N->getValueType(0);
2739 
2740     // Try to get the fneg to fold into the source modifier. This undoes generic
2741     // DAG combines and folds them into the mad.
2742     //
2743     // Only do this if we are not trying to support denormals. v_mad_f32 does
2744     // not support denormals ever.
2745     if (VT == MVT::f32 &&
2746         !Subtarget->hasFP32Denormals()) {
2747       SDValue LHS = N->getOperand(0);
2748       SDValue RHS = N->getOperand(1);
2749       if (LHS.getOpcode() == ISD::FADD) {
2750         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
2751 
2752         SDValue A = LHS.getOperand(0);
2753         if (A == LHS.getOperand(1)) {
2754           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2755           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
2756 
2757           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
2758         }
2759       }
2760 
2761       if (RHS.getOpcode() == ISD::FADD) {
2762         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
2763 
2764         SDValue A = RHS.getOperand(0);
2765         if (A == RHS.getOperand(1)) {
2766           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
2767           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
2768         }
2769       }
2770 
2771       return SDValue();
2772     }
2773 
2774     break;
2775   }
2776   case ISD::LOAD:
2777   case ISD::STORE:
2778   case ISD::ATOMIC_LOAD:
2779   case ISD::ATOMIC_STORE:
2780   case ISD::ATOMIC_CMP_SWAP:
2781   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2782   case ISD::ATOMIC_SWAP:
2783   case ISD::ATOMIC_LOAD_ADD:
2784   case ISD::ATOMIC_LOAD_SUB:
2785   case ISD::ATOMIC_LOAD_AND:
2786   case ISD::ATOMIC_LOAD_OR:
2787   case ISD::ATOMIC_LOAD_XOR:
2788   case ISD::ATOMIC_LOAD_NAND:
2789   case ISD::ATOMIC_LOAD_MIN:
2790   case ISD::ATOMIC_LOAD_MAX:
2791   case ISD::ATOMIC_LOAD_UMIN:
2792   case ISD::ATOMIC_LOAD_UMAX:
2793   case AMDGPUISD::ATOMIC_INC:
2794   case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics.
2795     if (DCI.isBeforeLegalize())
2796       break;
2797 
2798     MemSDNode *MemNode = cast<MemSDNode>(N);
2799     SDValue Ptr = MemNode->getBasePtr();
2800 
2801     // TODO: We could also do this for multiplies.
2802     unsigned AS = MemNode->getAddressSpace();
2803     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
2804       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
2805       if (NewPtr) {
2806         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
2807 
2808         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
2809         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
2810       }
2811     }
2812     break;
2813   }
2814   case ISD::AND:
2815     return performAndCombine(N, DCI);
2816   case ISD::OR:
2817     return performOrCombine(N, DCI);
2818   case AMDGPUISD::FP_CLASS:
2819     return performClassCombine(N, DCI);
2820   case ISD::FCANONICALIZE:
2821     return performFCanonicalizeCombine(N, DCI);
2822   }
2823   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2824 }
2825 
2826 /// \brief Analyze the possible immediate value Op
2827 ///
2828 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
2829 /// and the immediate value if it's a literal immediate
2830 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
2831 
2832   const SIInstrInfo *TII =
2833       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2834 
2835   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2836     if (TII->isInlineConstant(Node->getAPIntValue()))
2837       return 0;
2838 
2839     uint64_t Val = Node->getZExtValue();
2840     return isUInt<32>(Val) ? Val : -1;
2841   }
2842 
2843   if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2844     if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2845       return 0;
2846 
2847     if (Node->getValueType(0) == MVT::f32)
2848       return FloatToBits(Node->getValueAPF().convertToFloat());
2849 
2850     return -1;
2851   }
2852 
2853   return -1;
2854 }
2855 
2856 /// \brief Helper function for adjustWritemask
2857 static unsigned SubIdx2Lane(unsigned Idx) {
2858   switch (Idx) {
2859   default: return 0;
2860   case AMDGPU::sub0: return 0;
2861   case AMDGPU::sub1: return 1;
2862   case AMDGPU::sub2: return 2;
2863   case AMDGPU::sub3: return 3;
2864   }
2865 }
2866 
2867 /// \brief Adjust the writemask of MIMG instructions
2868 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2869                                        SelectionDAG &DAG) const {
2870   SDNode *Users[4] = { };
2871   unsigned Lane = 0;
2872   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
2873   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
2874   unsigned NewDmask = 0;
2875 
2876   // Try to figure out the used register components
2877   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2878        I != E; ++I) {
2879 
2880     // Abort if we can't understand the usage
2881     if (!I->isMachineOpcode() ||
2882         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2883       return;
2884 
2885     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2886     // Note that subregs are packed, i.e. Lane==0 is the first bit set
2887     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2888     // set, etc.
2889     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2890 
2891     // Set which texture component corresponds to the lane.
2892     unsigned Comp;
2893     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2894       assert(Dmask);
2895       Comp = countTrailingZeros(Dmask);
2896       Dmask &= ~(1 << Comp);
2897     }
2898 
2899     // Abort if we have more than one user per component
2900     if (Users[Lane])
2901       return;
2902 
2903     Users[Lane] = *I;
2904     NewDmask |= 1 << Comp;
2905   }
2906 
2907   // Abort if there's no change
2908   if (NewDmask == OldDmask)
2909     return;
2910 
2911   // Adjust the writemask in the node
2912   std::vector<SDValue> Ops;
2913   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
2914   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2915   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
2916   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2917 
2918   // If we only got one lane, replace it with a copy
2919   // (if NewDmask has only one bit set...)
2920   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2921     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2922                                        MVT::i32);
2923     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2924                                       SDLoc(), Users[Lane]->getValueType(0),
2925                                       SDValue(Node, 0), RC);
2926     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2927     return;
2928   }
2929 
2930   // Update the users of the node with the new indices
2931   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2932 
2933     SDNode *User = Users[i];
2934     if (!User)
2935       continue;
2936 
2937     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2938     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2939 
2940     switch (Idx) {
2941     default: break;
2942     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2943     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2944     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2945     }
2946   }
2947 }
2948 
2949 static bool isFrameIndexOp(SDValue Op) {
2950   if (Op.getOpcode() == ISD::AssertZext)
2951     Op = Op.getOperand(0);
2952 
2953   return isa<FrameIndexSDNode>(Op);
2954 }
2955 
2956 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2957 /// with frame index operands.
2958 /// LLVM assumes that inputs are to these instructions are registers.
2959 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2960                                                      SelectionDAG &DAG) const {
2961 
2962   SmallVector<SDValue, 8> Ops;
2963   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2964     if (!isFrameIndexOp(Node->getOperand(i))) {
2965       Ops.push_back(Node->getOperand(i));
2966       continue;
2967     }
2968 
2969     SDLoc DL(Node);
2970     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2971                                      Node->getOperand(i).getValueType(),
2972                                      Node->getOperand(i)), 0));
2973   }
2974 
2975   DAG.UpdateNodeOperands(Node, Ops);
2976 }
2977 
2978 /// \brief Fold the instructions after selecting them.
2979 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2980                                           SelectionDAG &DAG) const {
2981   const SIInstrInfo *TII =
2982       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2983   unsigned Opcode = Node->getMachineOpcode();
2984 
2985   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore())
2986     adjustWritemask(Node, DAG);
2987 
2988   if (Opcode == AMDGPU::INSERT_SUBREG ||
2989       Opcode == AMDGPU::REG_SEQUENCE) {
2990     legalizeTargetIndependentNode(Node, DAG);
2991     return Node;
2992   }
2993   return Node;
2994 }
2995 
2996 /// \brief Assign the register class depending on the number of
2997 /// bits set in the writemask
2998 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2999                                                      SDNode *Node) const {
3000   const SIInstrInfo *TII =
3001       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
3002 
3003   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
3004 
3005   if (TII->isVOP3(MI->getOpcode())) {
3006     // Make sure constant bus requirements are respected.
3007     TII->legalizeOperandsVOP3(MRI, MI);
3008     return;
3009   }
3010 
3011   if (TII->isMIMG(*MI)) {
3012     unsigned VReg = MI->getOperand(0).getReg();
3013     unsigned DmaskIdx = MI->getNumOperands() == 12 ? 3 : 4;
3014     unsigned Writemask = MI->getOperand(DmaskIdx).getImm();
3015     unsigned BitsSet = 0;
3016     for (unsigned i = 0; i < 4; ++i)
3017       BitsSet += Writemask & (1 << i) ? 1 : 0;
3018 
3019     const TargetRegisterClass *RC;
3020     switch (BitsSet) {
3021     default: return;
3022     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
3023     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
3024     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
3025     }
3026 
3027     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
3028     MI->setDesc(TII->get(NewOpcode));
3029     MRI.setRegClass(VReg, RC);
3030     return;
3031   }
3032 
3033   // Replace unused atomics with the no return version.
3034   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
3035   if (NoRetAtomicOp != -1) {
3036     if (!Node->hasAnyUseOfValue(0)) {
3037       MI->setDesc(TII->get(NoRetAtomicOp));
3038       MI->RemoveOperand(0);
3039       return;
3040     }
3041 
3042     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
3043     // instruction, because the return type of these instructions is a vec2 of
3044     // the memory type, so it can be tied to the input operand.
3045     // This means these instructions always have a use, so we need to add a
3046     // special case to check if the atomic has only one extract_subreg use,
3047     // which itself has no uses.
3048     if ((Node->hasNUsesOfValue(1, 0) &&
3049          Node->use_begin()->isMachineOpcode() &&
3050          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
3051          !Node->use_begin()->hasAnyUseOfValue(0))) {
3052       unsigned Def = MI->getOperand(0).getReg();
3053 
3054       // Change this into a noret atomic.
3055       MI->setDesc(TII->get(NoRetAtomicOp));
3056       MI->RemoveOperand(0);
3057 
3058       // If we only remove the def operand from the atomic instruction, the
3059       // extract_subreg will be left with a use of a vreg without a def.
3060       // So we need to insert an implicit_def to avoid machine verifier
3061       // errors.
3062       BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3063               TII->get(AMDGPU::IMPLICIT_DEF), Def);
3064     }
3065     return;
3066   }
3067 }
3068 
3069 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
3070   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
3071   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
3072 }
3073 
3074 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
3075                                                 SDLoc DL,
3076                                                 SDValue Ptr) const {
3077   const SIInstrInfo *TII =
3078     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
3079 
3080   // Build the half of the subregister with the constants before building the
3081   // full 128-bit register. If we are building multiple resource descriptors,
3082   // this will allow CSEing of the 2-component register.
3083   const SDValue Ops0[] = {
3084     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
3085     buildSMovImm32(DAG, DL, 0),
3086     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
3087     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
3088     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
3089   };
3090 
3091   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
3092                                                 MVT::v2i32, Ops0), 0);
3093 
3094   // Combine the constants and the pointer.
3095   const SDValue Ops1[] = {
3096     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
3097     Ptr,
3098     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
3099     SubRegHi,
3100     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
3101   };
3102 
3103   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
3104 }
3105 
3106 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
3107 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
3108 ///        of the resource descriptor) to create an offset, which is added to
3109 ///        the resource pointer.
3110 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
3111                                            SDLoc DL,
3112                                            SDValue Ptr,
3113                                            uint32_t RsrcDword1,
3114                                            uint64_t RsrcDword2And3) const {
3115   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
3116   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
3117   if (RsrcDword1) {
3118     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
3119                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
3120                     0);
3121   }
3122 
3123   SDValue DataLo = buildSMovImm32(DAG, DL,
3124                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
3125   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
3126 
3127   const SDValue Ops[] = {
3128     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
3129     PtrLo,
3130     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
3131     PtrHi,
3132     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
3133     DataLo,
3134     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
3135     DataHi,
3136     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
3137   };
3138 
3139   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
3140 }
3141 
3142 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
3143                                                const TargetRegisterClass *RC,
3144                                                unsigned Reg, EVT VT) const {
3145   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
3146 
3147   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
3148                             cast<RegisterSDNode>(VReg)->getReg(), VT);
3149 }
3150 
3151 //===----------------------------------------------------------------------===//
3152 //                         SI Inline Assembly Support
3153 //===----------------------------------------------------------------------===//
3154 
3155 std::pair<unsigned, const TargetRegisterClass *>
3156 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3157                                                StringRef Constraint,
3158                                                MVT VT) const {
3159 
3160   if (Constraint.size() == 1) {
3161     switch (Constraint[0]) {
3162     case 's':
3163     case 'r':
3164       switch (VT.getSizeInBits()) {
3165       default:
3166         return std::make_pair(0U, nullptr);
3167       case 32:
3168         return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
3169       case 64:
3170         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
3171       case 128:
3172         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
3173       case 256:
3174         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
3175       }
3176 
3177     case 'v':
3178       switch (VT.getSizeInBits()) {
3179       default:
3180         return std::make_pair(0U, nullptr);
3181       case 32:
3182         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
3183       case 64:
3184         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
3185       case 96:
3186         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
3187       case 128:
3188         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
3189       case 256:
3190         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
3191       case 512:
3192         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
3193       }
3194     }
3195   }
3196 
3197   if (Constraint.size() > 1) {
3198     const TargetRegisterClass *RC = nullptr;
3199     if (Constraint[1] == 'v') {
3200       RC = &AMDGPU::VGPR_32RegClass;
3201     } else if (Constraint[1] == 's') {
3202       RC = &AMDGPU::SGPR_32RegClass;
3203     }
3204 
3205     if (RC) {
3206       uint32_t Idx;
3207       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
3208       if (!Failed && Idx < RC->getNumRegs())
3209         return std::make_pair(RC->getRegister(Idx), RC);
3210     }
3211   }
3212   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3213 }
3214 
3215 SITargetLowering::ConstraintType
3216 SITargetLowering::getConstraintType(StringRef Constraint) const {
3217   if (Constraint.size() == 1) {
3218     switch (Constraint[0]) {
3219     default: break;
3220     case 's':
3221     case 'v':
3222       return C_RegisterClass;
3223     }
3224   }
3225   return TargetLowering::getConstraintType(Constraint);
3226 }
3227