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